From 186b46adb7a87245c8778ebe10a784a774d8ae7a Mon Sep 17 00:00:00 2001 From: leemour Date: Wed, 25 Nov 2026 23:52:55 +0100 Subject: [PATCH 1/2] feat(mail): type: and reach: fields in mail search memo searches mail only through cli-core's search, and a filter after the search returns short pages, so the type and reach filters run inside the query's SQL. - type: takes one of the 16 mail types, reach: direct, group or broadcast (enum fields, terms only, mail only; tg and max refuse them). - A search that names either field first types the mail the store has not typed yet (storeMailTypes, 5,000 per write), outside the search's read and its 2 s time limit. The compiler itself never writes: when types are not current (a read-only open, or rankings and statistics that skip the fill) it works the untyped mail out in memory, checking the time limit between batches. A search without these fields types nothing. - Email hits carry mailType and reach (mail_type and reach in --json, and on the text line); untyped hits get theirs worked out in memory for the page. - SENDER_BOT_PREFIX is exported from ./store, MAIL_TYPES, MailType, REACHES and Reach from ./store/areas. - The emails.ts line limit goes 1033 -> 1038 for the batched hit typing. Co-Authored-By: Claude Opus 5.5 --- api/index.api.txt | 2 ++ biome.json | 2 +- changes/feat-search-mail-type.md | 12 +++++++ docs/dev/GLOSSARY.md | 4 +-- docs/search/query-language.md | 10 ++++-- src/cli/messenger/message-items.ts | 2 ++ src/cli/messenger/search-answers.ts | 2 ++ src/domain/models.ts | 5 +++ src/entities/message.ts | 4 +++ src/mail/cli/index.ts | 2 +- src/mail/read.ts | 1 + src/search/lucene/registry.ts | 25 +++++++++++++ src/services/mail-search.test.ts | 55 +++++++++++++++++++++++++++++ src/services/messages-search.ts | 2 +- src/store/areas.ts | 3 ++ src/store/public.ts | 2 +- src/store/queries.ts | 10 +++++- src/store/sqlite/email-types.ts | 22 ++++++++++-- src/store/sqlite/emails.ts | 13 ++++--- src/store/sqlite/lucene-fields.ts | 15 ++++++++ src/store/sqlite/lucene.ts | 6 ++++ 21 files changed, 183 insertions(+), 16 deletions(-) create mode 100644 changes/feat-search-mail-type.md diff --git a/api/index.api.txt b/api/index.api.txt index 408057bb5..1ebd67203 100644 --- a/api/index.api.txt +++ b/api/index.api.txt @@ -401,6 +401,8 @@ MailFields · interface · labels: string[]; MailFields · interface · thread: string; MailFields · interface · read: boolean | null; MailFields · interface · flagged: boolean | null; +MailFields · interface · mailType?: MailType; +MailFields · interface · reach?: Reach; MailFields · interface · senderScore?: { MailFields · interface · score: number; MailFields · interface · signals: string[]; diff --git a/biome.json b/biome.json index ca106dce4..9a2bda3e3 100644 --- a/biome.json +++ b/biome.json @@ -792,7 +792,7 @@ "noExcessiveLinesPerFile": { "level": "error", "options": { - "maxLines": 1033 + "maxLines": 1038 } } } diff --git a/changes/feat-search-mail-type.md b/changes/feat-search-mail-type.md new file mode 100644 index 000000000..736cdd206 --- /dev/null +++ b/changes/feat-search-mail-type.md @@ -0,0 +1,12 @@ +### Added + +- **Mail search filters by mail type and reach.** `type:` takes one of the [mail types](../docs/dev/GLOSSARY.md#mail-types) + and `reach:` takes `direct`, `group` or `broadcast`, in the query itself, so a page is never short: + `memo search mail 'type:order OR type:bill'`, `memo search mail 'invoice -type:promotion reach:direct'`. A search + that names either field first types the mail the store has not typed yet, 5,000 emails per write; on 100,000 + untyped emails the first such search after an upgrade takes seconds, later ones the usual milliseconds. A store + opened read-only works the missing types out in memory for that search. tg and max refuse both as mail fields. +- **Email hits show their type and reach**: `email.mail_type` and `email.reach` in `--json`, and both on the hit's + line in mail's text output. In the API they are `MailFields.mailType` and `MailFields.reach` (experimental). +- **`SENDER_BOT_PREFIX` is exported from `@wirecat/cli-core/store`, and `MAIL_TYPES`, `MailType`, `REACHES` and + `Reach` from `@wirecat/cli-core/store/areas`** (experimental), so a CLI no longer copies them. diff --git a/docs/dev/GLOSSARY.md b/docs/dev/GLOSSARY.md index 69cc0cc29..b53c22cd3 100644 --- a/docs/dev/GLOSSARY.md +++ b/docs/dev/GLOSSARY.md @@ -77,9 +77,9 @@ Verbs used but not in cli-base's vocabulary, by CLI (2026-10-12). Each needs a r | organization | a company, team, family or community | entity | none | | person | one human, across every messenger and mail (`person:`) | user, people | tg bot help: "user: for a person", "the person's user id"; drive `people` | | bot | a program that writes to the owner: a no-reply or alert address, a messenger's bot, a service's mail; an entity apart from people, with a name, identities and an optional organization, and no ties, tasks or merge review (`sender-bot:`, the `sender_bots` table). Not an agent: `bot:` and the `bots` table are agents that work here | automated person, sender (for a bot) | `people list kind:automated` still lists people a name or a bulk mailbox marks; memo's `{ bot }` author and `bot list` mean agents and a messenger's bot account | -| mail type | what one email is, apart from who sent it: one of the words in [Mail types](#mail-types), worked out per email from what the store keeps of it (`emails.mail_type`, key `mailType`). A sender's view is a summary of its mail, so a shop that sends receipts and sales counts under `order` and under `promotion` | category, kind (a person's `kind` is another thing), label | none | +| mail type | what one email is, apart from who sent it: one of the words in [Mail types](#mail-types), worked out per email from what the store keeps of it (`emails.mail_type`; key `mailType` in the API, `mail_type` in CLI JSON; search field `type:`). A sender's view is a summary of its mail, so a shop that sends receipts and sales counts under `order` and under `promotion` | category, kind (a person's `kind` is another thing), label | none | | sorting rule | the owner's or the program's word on what mail is, by one of five scopes tried in this order: one mail, a List-Id or a subject pattern, an address, a registrable domain; then the header classifier. It sets a mail type, makes the sender a bot or a person for its whole history, or files the sender under an organization (`mail_sort_rules`, `store.mail.sorting`). An email it typed has `typeSignal` `rule:`. Not a mail rule: `mail_rules` decide how one account's sync stores mail | filter, mail rule, label rule | none | -| reach | how a message reached the owner: `direct` (to the owner or a few people), `group` (a large group or a discussion list), `broadcast` (one sender to many readers who cannot answer in place). Worked out per email (`emails.reach`) and per sender (`people list`) | audience, scope | none | +| reach | how a message reached the owner: `direct` (to the owner or a few people), `group` (a large group or a discussion list), `broadcast` (one sender to many readers who cannot answer in place). Worked out per email (`emails.reach`, key `reach`, search field `reach:`) and per sender (`people list`) | audience, scope | none | | contact | one person as one source knows them: a mail correspondent, a Telegram user, a Drive owner, a calendar attendee; an `identities` row | user | none found beyond the above | | entity | the thing the owner means — a person, an event, a document; it carries no provider id ([WC-DATA-2](https://github.com/WireCatLabs/cli-base/blob/main/docs/standards/data-model.md)) | record, object | none | | source record | one source's copy of an entity, keyed by account and `external_id`: a contact, a Zoom meeting, an email, a message | entity, item | none | diff --git a/docs/search/query-language.md b/docs/search/query-language.md index 4f8bc872b..b47d60cf2 100644 --- a/docs/search/query-language.md +++ b/docs/search/query-language.md @@ -24,7 +24,11 @@ StandardSyntaxParser и PrecedenceQueryParser, default AND, default field `text` `bcc:` (человек, как в `from:`), `subject:` (слова темы) и `mailbox:` (папка или ярлык по id или имени; `label:` — то же самое), `is:unread`, `is:read` и `is:starred` (письмо не прочитано, прочитано, помечено флагом — как их показал почтовый ящик при импорте; письмо, для которого импорт этого не узнал, не находит -ни `is:read`, ни `is:unread`). `is:starred` находит и сообщения, которые владелец отметил звёздочкой +ни `is:read`, ни `is:unread`), `type:` (тип письма, одно из слов [Mail types](../dev/GLOSSARY.md#mail-types): +`type:order OR type:bill`) и `reach:` (как письмо дошло: `direct`, `group`, `broadcast`). Тип хранится лениво: поиск +с `type:` или `reach:` сначала определяет и сохраняет тип писем, у которых его ещё нет, пачками по 5 000 (первый такой +поиск после обновления на 100 000 писем — секунды); хранилище, открытое только для чтения, определяет их в памяти на +время поиска. `is:starred` находит и сообщения, которые владелец отметил звёздочкой (`messages star`), где у мессенджера есть звёзды. Профиль действует и для MCP-инструментов `search_*` (`source` у каждого). Поле, которого у вида нет, в `search all` пропускает этот вид, и ответ называет причину в `skipped`. `bot search messages` читает тот же язык в копиях ботов; строгий поиск общего архива выбирает bot accounts через `in:bots`. @@ -454,6 +458,8 @@ enum или unsupported сочетание дают ошибку, а не пус | `label` | kw | the same as mailbox:; mail only | `label:Projects` | term, phrase, wildcard | | `list` | kw | the List-Id of a mailing list, lower case; a domain matches every list under it; mail only | `list:github.com` | term, phrase | | `is` | enum | unread, read, starred | `is:unread` | term, phrase | +| `type` | enum | auto_reply, security, calendar, travel, event_ticket, order, shipping, bill, social_notification, discussion_list, newsletter, promotion, system_alert, account_notice, personal, other | `type:order OR type:bill` | term, phrase | +| `reach` | enum | direct, group, broadcast | `reach:direct` | term, phrase | | `chat` | kw | account-scoped: an id or chat: reference as is; with * or ? a pattern over title, @username (up to 50); else a title | `chat:*fixture*` | term, phrase, wildcard | | `date` | time | ISO/calendar timezone; today, yesterday, 30m/2h/7d ago | `date:[2026-01-01 TO 2026-02-01}` | term, phrase, range | | `source` | enum | internal, file | `source:internal` | term, phrase | @@ -907,7 +913,7 @@ Low-level `searchStore` и `MessagesService.search` без language сохран фразы, `from:` `to:` `cc:` `subject:` `body:` (слово или фраза), `is:unread|read|starred` и `date:` (на день шире с каждой стороны: сервер считает дни в своём поясе). Верхний OR — отдельный поиск на ветку; вызов — одна ветка в одной папке, не больше 3, 100 новейших писем на вызов. Остальное -(`has:`, `list:`, `mailbox:`, отрицания, шаблоны, `from:me`) — только локально; запрос без того, что +(`has:`, `list:`, `mailbox:`, `type:`, `reach:`, отрицания, шаблоны, `from:me`) — только локально; запрос без того, что сервер читает, его не спрашивает (`no_words`). IMAP ищет подстроку без форм слов, поэтому сервер может не найти другую форму слова; строгий проход убирает лишние находки, но не возвращает пропущенные. Gmail получает `X-GM-RAW` по All Mail, другие серверы — `UID SEARCH` по INBOX, Sent и diff --git a/src/cli/messenger/message-items.ts b/src/cli/messenger/message-items.ts index 8ded90d32..16b731131 100644 --- a/src/cli/messenger/message-items.ts +++ b/src/cli/messenger/message-items.ts @@ -118,6 +118,8 @@ export const messageItem = (message: ReadMessage, reader: AccountKey): MessageIt thread: message.email.thread, read: message.email.read, flagged: message.email.flagged, + mail_type: message.email.mailType, + reach: message.email.reach, sender_score: message.email.senderScore, }, provider_metadata: message.providerMetadata, diff --git a/src/cli/messenger/search-answers.ts b/src/cli/messenger/search-answers.ts index d474b6443..75a3a9240 100644 --- a/src/cli/messenger/search-answers.ts +++ b/src/cli/messenger/search-answers.ts @@ -100,6 +100,8 @@ export const messageHitItem = (hit: FoundMessage, query = ""): MessageHitItem => thread: hit.email.thread, read: hit.email.read, flagged: hit.email.flagged, + mail_type: hit.email.mailType, + reach: hit.email.reach, sender_score: hit.email.senderScore, } : undefined, diff --git a/src/domain/models.ts b/src/domain/models.ts index e435ed4ac..c4a6364d4 100644 --- a/src/domain/models.ts +++ b/src/domain/models.ts @@ -1,3 +1,4 @@ +import type { MailType, MailTypeOf } from "../mail/mail-types.js" import type { Upload } from "./attachments.js" import type { CounterObservation, CounterObservations } from "./counters.js" @@ -477,6 +478,10 @@ export interface MailFields { thread: string read: boolean | null flagged: boolean | null + /** What the email is, apart from its sender. @experimental */ + mailType?: MailType + /** How it reached the owner. @experimental */ + reach?: MailTypeOf["reach"] /** How much the sender's mail looks like spam, a scam or a robot, and why; absent when the sender is not scored. */ senderScore?: { score: number; signals: string[]; demoted?: true } } diff --git a/src/entities/message.ts b/src/entities/message.ts index 4b65167ac..90080dbf2 100644 --- a/src/entities/message.ts +++ b/src/entities/message.ts @@ -117,6 +117,10 @@ export const message = v.strictObject({ thread: reference, read: v.nullable(v.boolean()), flagged: v.nullable(v.boolean()), + /** What the email is, apart from its sender: one of the mail types. @experimental */ + mail_type: v.optional(text), + /** How it reached the owner: direct, group or broadcast. @experimental */ + reach: v.optional(text), /** How much the sender's mail looks like spam, a scam or a robot (memo's score), and why; absent when unscored. */ sender_score: v.optional( v.strictObject({ score: v.number(), signals: v.array(text), demoted: v.optional(v.literal(true)) }), diff --git a/src/mail/cli/index.ts b/src/mail/cli/index.ts index e1d3c1ce0..a99690d5f 100644 --- a/src/mail/cli/index.ts +++ b/src/mail/cli/index.ts @@ -174,7 +174,7 @@ const searchCommand = (mail: MailReads): Command => { "after", ` Fields: from: to: cc: bcc: subject: body: mailbox: (or label:) list: (a List-Id or its domain) is:unread|read|starred -has:attachment, filename:, content: (the text of attachments), size>, date: — \`${mail.app.command} personal search messages 'content:invoice'\`. +type: (order, bill, promotion… — what the email is) reach:direct|group|broadcast has:attachment, filename:, content: (the text of attachments), size>, date: — \`${mail.app.command} personal search messages 'content:invoice'\`. chat: names a thread by its subject. Mail sent to many is in the mailbox bulk; NOT mailbox:bulk leaves it out. Mail from senders with signs of fraud comes after the rest of the page; --plain-order keeps it in place. --json: the list is items; each hit's reference is ref (msg:email/…), which messages show reads.${ diff --git a/src/mail/read.ts b/src/mail/read.ts index 14dd457c2..ba77f7c7e 100644 --- a/src/mail/read.ts +++ b/src/mail/read.ts @@ -140,6 +140,7 @@ export const hitText = ( mail.to.length ? `to ${names(mail.to)}` : "", mail.cc.length ? `cc ${names(mail.cc)}` : "", mail.labels.join(", "), + [mail.mailType, mail.reach].filter(Boolean).join(", "), ] .filter(Boolean) .join(" · ") diff --git a/src/search/lucene/registry.ts b/src/search/lucene/registry.ts index aca544b30..51c978129 100644 --- a/src/search/lucene/registry.ts +++ b/src/search/lucene/registry.ts @@ -12,6 +12,8 @@ import { } from "@wirecat/cli-base/query" import * as v from "valibot" import { tagOf } from "../../domain/tags.js" +import { MAIL_TYPES } from "../../mail/mail-types.js" +import { REACHES } from "../../store/sqlite/sender-signals.js" import { MOST_WORDS_APART, QUERY_LIMITS, SEARCH_QUERY, searchError } from "./types.js" export const FIELD_VERSION = 2 @@ -173,6 +175,29 @@ export const QUERY_FIELDS: readonly MessageField[] = [ support: "A1", values: ["unread", "read", "starred"], }, + { + name: "type", + example: "type:order OR type:bill", + index: "emails.mail_type (emails_by_mail_type)", + aliases: [], + type: "enum", + operators: terms, + normalization: + "lowercase; what one email is, apart from its sender; mail not typed yet is typed before the search; mail only", + support: "A1", + values: MAIL_TYPES, + }, + { + name: "reach", + example: "reach:direct", + index: "emails.reach", + aliases: [], + type: "enum", + operators: terms, + normalization: "lowercase; how one email reached the owner; mail only", + support: "A1", + values: REACHES, + }, { name: "chat", example: "chat:*fixture*", diff --git a/src/services/mail-search.test.ts b/src/services/mail-search.test.ts index 2adc9158f..3f2cdb6a8 100644 --- a/src/services/mail-search.test.ts +++ b/src/services/mail-search.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path" import { afterEach, describe, expect, it } from "vitest" import { formatLocator } from "../domain/locator.js" import type { AttachmentInput, EmailInput } from "../store/index.js" +import { openCache } from "../store/open.js" import { type AccountKey, type MessageStore, openStore, type ScoredHit } from "../store/store.js" import { storeOnlyDeps } from "./deps.js" import { embeddingsService } from "./embeddings.js" @@ -290,6 +291,60 @@ describe("search mail over the mail tables", () => { expect(await found(store, "link:click?id=1")).toEqual([""]) }) + it("filters by mail type and reach, typing the mail the store has not typed yet", async () => { + const path = join(mkdtempSync(join(tmpdir(), "mail-types-search-")), "store.db") + const typed = await openStore({ path }) + live.push(typed) + const owner = await typed.accounts.saveAccount(MAIL, { name: null }) + await typed.mail.saveThread({ + accountId: owner, + externalId: "thread-9", + now: at(10), + emails: [ + email("", { + subject: "Thank you for your order #4411", + from: { address: "orders@shop.example.com", name: "Shop" }, + }), + email("", { + subject: "Your bill is ready", + from: { address: "billing@phone.example.com", name: "Phone Co" }, + }), + email("", { + subject: "All hands", + to: Array.from({ length: 12 }, (_, i) => ({ address: `colleague${i}@example.com`, name: null })), + }), + ], + }) + const untyped = await openCache(path) + live.push({ close: async () => untyped.close() } as MessageStore) + const left = () => Number(untyped.prepare("SELECT count(*) AS n FROM emails WHERE mail_type IS NULL").get()?.n) + const sorted = async (text: string, on = typed) => + (await searchStore(on, MAIL, { text, kind: "mail", limit: 10 })).items.map(({ id }) => id).sort() + + expect(await sorted("roadmap")).toHaveLength(3) + expect(left()).toBe(3) + + const readOnly = await openStore({ path, readOnly: true }) + live.push(readOnly) + expect(await sorted("type:order OR type:BILL", readOnly)).toEqual(["", ""]) + expect(left()).toBe(3) + + expect(await sorted("type:order OR type:BILL")).toEqual(["", ""]) + expect(left()).toBe(0) + expect(await sorted("reach:group")).toEqual([""]) + expect(await sorted("roadmap -type:bill -reach:group")).toEqual([""]) + expect(await sorted("bill type:bill")).toEqual([""]) + expect(await sorted("bill type:order")).toEqual([]) + + const [hit] = (await searchStore(typed, MAIL, { text: "type:order", kind: "mail", limit: 1 })).items + expect(hit?.email).toMatchObject({ mailType: "order", reach: "direct" }) + await expect(search(typed, "type:receipt")).rejects.toThrow("type takes auto_reply") + await expect(search(typed, "reach:everyone")).rejects.toThrow("reach takes direct, group, broadcast") + await expect( + searchStore(typed, { provider: "tg", account: "1" }, { text: "type:order", limit: 5 }), + ).rejects.toThrow("type: is a mail field") + }) + it("refuses messenger-only fields", async () => { const { store } = await seeded() await expect(search(store, "kind:group")).rejects.toThrow("mail has no kind") diff --git a/src/services/messages-search.ts b/src/services/messages-search.ts index 1011b0e3a..81fa8ee6d 100644 --- a/src/services/messages-search.ts +++ b/src/services/messages-search.ts @@ -32,7 +32,7 @@ import type { SearchFound, SearchQuery } from "./messages.js" import { accountsOfKind, listedAccounts, MAIL } from "./search-kind.js" const PERSON_FIELDS = new Set(["from", "to", "cc", "bcc"]) -const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list"]) +const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list", "type", "reach"]) import { type Predicate, diff --git a/src/store/areas.ts b/src/store/areas.ts index d7ccf7148..2f9e6a128 100644 --- a/src/store/areas.ts +++ b/src/store/areas.ts @@ -2,6 +2,8 @@ * Store area types and constants some CLIs use beyond the stable `@wirecat/cli-core/store`: experimental, so a * minor release may change them. */ + +export { MAIL_TYPES, type MailType } from "../mail/mail-types.js" export { type AddedSource, type AddedSourceContent, @@ -51,6 +53,7 @@ export type { SenderBot, SenderBotDetails, } from "./sqlite/sender-bots.js" +export { REACHES, type Reach } from "./sqlite/sender-signals.js" export type { SubscriptionFilter } from "./sqlite/subscriptions.js" export { PROJECT_TASK_FIELDS, TASK_SORTS, type TaskSort } from "./sqlite/task-board.js" export { TASK_RELATION_KINDS, type TaskRelationKind } from "./sqlite/task-relations.js" diff --git a/src/store/public.ts b/src/store/public.ts index 921711c7b..8cf1597f9 100644 --- a/src/store/public.ts +++ b/src/store/public.ts @@ -16,7 +16,7 @@ export { TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js" -export { type KindSignal, PERSON_KINDS, type PersonKind } from "../domain/person-kinds.js" +export { type KindSignal, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX } from "../domain/person-kinds.js" export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js" export type { TagConsolidationApplyOptions, diff --git a/src/store/queries.ts b/src/store/queries.ts index 80d1809e9..c19e50192 100644 --- a/src/store/queries.ts +++ b/src/store/queries.ts @@ -1,9 +1,11 @@ +import { walkQuery } from "@wirecat/cli-base/query" import type { Page } from "../domain/models.js" import type { QueryExecution } from "../search/lucene/resolved.js" import type { Stemmer, Stemmers } from "../search/stem.js" import { type AdminStoreRequest, type AdminStoreResult, adminStatisticsQuery } from "./sqlite/admin-statistics.js" import { type ConversationEligibility, conversationEligibility } from "./sqlite/conversation-eligibility.js" import { drainEmailIndex } from "./sqlite/email-index.js" +import { storeMailTypes } from "./sqlite/email-types.js" import type { QueryGroup, QueryGrouping } from "./sqlite/lucene.js" import * as lucene from "./sqlite/lucene.js" import type { StoreContext } from "./sqlite/open.js" @@ -37,9 +39,15 @@ export interface QueriesStore { waitingChats(scope: ChatScope, waits: (newest: NewestMessage) => boolean, cap: number): Promise } +// Outside the search's read and its time limit: the first such search after an upgrade types every email. +const asksMailType = ({ root }: QueryExecution): boolean => + walkQuery(root).some(({ field }) => field === "type" || field === "reach") + export const queriesStoreOver = (context: StoreContext, stemmerFor: (stemmers: Stemmers) => Stemmer): QueriesStore => { const mailIndexed = (execution: QueryExecution) => { - if (execution.corpus === "mail") drainEmailIndex(context.database, stemmerFor) + if (execution.corpus !== "mail") return execution + drainEmailIndex(context.database, stemmerFor) + if (asksMailType(execution)) storeMailTypes(context.database) return execution } return { diff --git a/src/store/sqlite/email-types.ts b/src/store/sqlite/email-types.ts index e2745c381..f99ed80bf 100644 --- a/src/store/sqlite/email-types.ts +++ b/src/store/sqlite/email-types.ts @@ -192,7 +192,21 @@ const passes = (filter: TypeFilter, type: string, reach: string) => * The SQL of a filter by type and reach over `e`. Types are worked out and kept first; a query-only open that finds * some not worked out works those out in memory, so a filtered list is never short. */ -export const typeWhere = (database: CacheDatabase, filter: TypeFilter): { sql: string[]; params: string[] } => { +export const typeWhere = (database: CacheDatabase, filter: TypeFilter): { sql: string[]; params: string[] } => + filter.types === undefined && filter.reaches === undefined + ? { sql: [], params: [] } + : typeCondition(database, filter, storeMailTypes(database)) + +/** + * The same filter, without writing: inside a read, the mail not typed yet is worked out in memory. `check` runs + * between batches, so a search's time limit still stops it. + */ +export const typeCondition = ( + database: CacheDatabase, + filter: TypeFilter, + current = typesCurrent(database), + check: () => void = () => {}, +): { sql: string[]; params: string[] } => { if (filter.types === undefined && filter.reaches === undefined) return { sql: [], params: [] } const stored = [ ...(filter.types === undefined ? [] : ["e.mail_type IN (SELECT value FROM json_each(?))"]), @@ -202,7 +216,7 @@ export const typeWhere = (database: CacheDatabase, filter: TypeFilter): { sql: s ...(filter.types === undefined ? [] : [JSON.stringify(filter.types)]), ...(filter.reaches === undefined ? [] : [JSON.stringify(filter.reaches)]), ] - if (storeMailTypes(database)) return { sql: [stored], params } + if (current) return { sql: [stored], params } const pending = read(database, () => { const ids = database .prepare("SELECT id FROM emails WHERE mail_type IS NULL") @@ -210,9 +224,11 @@ export const typeWhere = (database: CacheDatabase, filter: TypeFilter): { sql: s .map((row) => Number(row.id)) const kept: number[] = [] const senders = new Map() - for (let at = 0; at < ids.length; at += BATCH) + for (let at = 0; at < ids.length; at += BATCH) { + check() for (const [id, typed] of typesOf(database, ids.slice(at, at + BATCH), senders)) if (passes(filter, typed.type, typed.reach)) kept.push(id) + } return kept }) return { diff --git a/src/store/sqlite/emails.ts b/src/store/sqlite/emails.ts index 40fd764b2..83223914d 100644 --- a/src/store/sqlite/emails.ts +++ b/src/store/sqlite/emails.ts @@ -794,6 +794,7 @@ const mailFieldsOf = (database: CacheDatabase, email: Email, thread: string, key thread: formatReference({ type: "chat", provider: key.provider, account: key.account, chat: thread }), read: email.read, flagged: email.flagged, + ...(email.mailType === null || email.reach === null ? {} : { mailType: email.mailType, reach: email.reach }), ...(scored === undefined ? {} : { @@ -818,11 +819,15 @@ export const emailHitsByPk = (database: CacheDatabase, pks: number[]): StoredHit FROM emails e JOIN email_threads t ON t.id = e.email_thread_id JOIN accounts a ON a.id = e.account_id WHERE e.id = ?`, ) - return pks.flatMap((pk) => { - const row = read.get(pk) - if (!row) return [] + const rows = pks.map((pk) => read.get(pk)).filter((row) => row !== undefined) + const emails = withTypes( + database, + rows.map((row) => emailOf(database, row)), + ) + return rows.flatMap((row, at) => { + const email = emails[at] + if (!email) return [] const thread = String(row.thread) - const email = emailOf(database, row) const message = messageOfEmail(email, thread) const key = { provider: String(row.provider), account: String(row.account) } return [ diff --git a/src/store/sqlite/lucene-fields.ts b/src/store/sqlite/lucene-fields.ts index 7df4cdc34..f359ca2c8 100644 --- a/src/store/sqlite/lucene-fields.ts +++ b/src/store/sqlite/lucene-fields.ts @@ -12,6 +12,7 @@ import { inSource } from "../../search/query.js" import { START_LETTERS, STEM_SEPARATOR, type Stemmer } from "../../search/stem.js" import type { CacheDatabase, SqlValue } from "../driver.js" import { fold, normalize } from "../normalize.js" +import type { TypeFilter } from "./email-types.js" import { linkMatch } from "./mention-links.js" import { valueMatch } from "./phone-countries.js" import { canonicalTagNamed } from "./tags.js" @@ -167,6 +168,8 @@ export interface FieldScope { everywhere: (node: ResolvedPredicate, fragment: Fragment, start?: string) => Fragment /** Counts the patterns' expanded words against the query's budget. */ expand: (count: number) => number + /** The emails that pass a filter by type and reach, as SQL over `e`; never writes. */ + mailTypes: (filter: TypeFilter) => { sql: string[]; params: string[] } } /** A leaf's condition; a whole `Leaf` is a pattern already expanded by an earlier leaf, taken as it was. */ @@ -739,6 +742,16 @@ const list: FieldCompiler = ({ value }, { mail }) => { ) } +// Mail not typed yet is worked out in memory here: a search never writes, and the fill runs before it. +const mailType = + (key: keyof TypeFilter): FieldCompiler => + ({ value }, scope) => { + if (!scope.mail) return always(bound("0")) + const filter = { [key]: [value.toLowerCase()] } as TypeFilter + const { sql, params } = scope.mailTypes(filter) + return always(bound(`m.id IN (SELECT e.id FROM emails e WHERE ${sql.join(" AND ")})`, ...params)) + } + const is: FieldCompiler = ({ value }, { mail }) => { const state = value.toLowerCase() return always( @@ -850,5 +863,7 @@ export const FIELD_COMPILERS: Readonly> = { label: mailbox, list, is, + type: mailType("types"), + reach: mailType("reaches"), subject, } diff --git a/src/store/sqlite/lucene.ts b/src/store/sqlite/lucene.ts index 47b705f3a..0b4872224 100644 --- a/src/store/sqlite/lucene.ts +++ b/src/store/sqlite/lucene.ts @@ -6,6 +6,7 @@ import type { QueryExecution, ResolvedNode, ResolvedPredicate } from "../../sear import { isStemmed } from "../../search/lucene/resolved.js" import { exhausted, outOfTime, QUERY_LIMITS, searchError, sqliteLimit, tooWideTerm } from "../../search/lucene/types.js" import { type SqlValue, TIME_LIMIT_FUNCTION, TimeLimitReached } from "../driver.js" +import { typeCondition, typesCurrent } from "./email-types.js" import { emailHitsByPk } from "./emails.js" import { placeHits } from "./hit-places.js" import { @@ -136,6 +137,7 @@ const compileQuery = (context: StoreContext, execution: QueryExecution, boundedA elsewhere, } } + let current: boolean | undefined const fields: FieldScope = { database, execution, @@ -153,6 +155,10 @@ const compileQuery = (context: StoreContext, execution: QueryExecution, boundedA expansions += count return expansions }, + mailTypes: (filter) => { + current ??= typesCurrent(database) + return typeCondition(database, filter, current, check) + }, } const createLeaf = (node: ResolvedPredicate): Leaf => { const compiler = isPresence(node) && PRESENCE.has(node.field) ? present : FIELD_COMPILERS[node.field] From 450a6e1729f4ab4ace41ef3a01e1f3ca7fa7aaa3 Mon Sep 17 00:00:00 2001 From: leemour Date: Thu, 26 Nov 2026 00:13:58 +0100 Subject: [PATCH 2/2] chore(api): report MailFields.reach as the mail type's reach Co-Authored-By: Claude Opus 5.5 --- api/index.api.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/index.api.txt b/api/index.api.txt index 1ebd67203..dedc6b024 100644 --- a/api/index.api.txt +++ b/api/index.api.txt @@ -402,7 +402,7 @@ MailFields · interface · thread: string; MailFields · interface · read: boolean | null; MailFields · interface · flagged: boolean | null; MailFields · interface · mailType?: MailType; -MailFields · interface · reach?: Reach; +MailFields · interface · reach?: MailTypeOf["reach"]; MailFields · interface · senderScore?: { MailFields · interface · score: number; MailFields · interface · signals: string[];