@wirecat/cli-core 0.751.0 → 0.753.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/cli/messenger/backfill-command.js +3 -1
  3. package/dist/crm/index.d.ts +1 -1
  4. package/dist/crm/index.js +1 -1
  5. package/dist/crm/manifest/writer.d.ts +23 -4
  6. package/dist/crm/manifest/writer.js +46 -8
  7. package/dist/crm/writer.d.ts +3 -2
  8. package/dist/crm/writer.js +9 -3
  9. package/dist/crm/writes.d.ts +2 -0
  10. package/dist/crm/writes.js +7 -4
  11. package/dist/domain/addresses.d.ts +8 -3
  12. package/dist/domain/addresses.js +24 -6
  13. package/dist/domain/person-kinds.d.ts +1 -1
  14. package/dist/errors/reasons.js +1 -0
  15. package/dist/mail/email-input.d.ts +1 -1
  16. package/dist/mail/email-input.js +3 -2
  17. package/dist/mail/folders.d.ts +6 -1
  18. package/dist/mail/folders.js +10 -5
  19. package/dist/mail/headers.d.ts +9 -5
  20. package/dist/mail/headers.js +63 -5
  21. package/dist/mail/own.d.ts +15 -0
  22. package/dist/mail/own.js +35 -0
  23. package/dist/mail/partial.js +4 -1
  24. package/dist/mail/server-search.js +3 -1
  25. package/dist/mail/source.d.ts +5 -1
  26. package/dist/mail/sync-types.d.ts +2 -0
  27. package/dist/mail/sync.js +16 -4
  28. package/dist/mail/testing/fake.d.ts +4 -0
  29. package/dist/mail/testing/fake.js +3 -1
  30. package/dist/mail/whole.js +3 -1
  31. package/dist/store/index.d.ts +1 -0
  32. package/dist/store/index.js +1 -0
  33. package/dist/store/messages.js +1 -0
  34. package/dist/store/sqlite/email-activity.d.ts +1 -1
  35. package/dist/store/sqlite/email-activity.js +4 -1
  36. package/dist/store/sqlite/email-state.d.ts +8 -0
  37. package/dist/store/sqlite/email-state.js +23 -0
  38. package/dist/store/sqlite/emails.d.ts +9 -0
  39. package/dist/store/sqlite/emails.js +2 -1
  40. package/dist/store/sqlite/messages.d.ts +5 -0
  41. package/dist/store/sqlite/messages.js +13 -3
  42. package/dist/store/sqlite/own-identities.d.ts +2 -0
  43. package/dist/store/sqlite/own-identities.js +24 -1
  44. package/dist/store/sqlite/people-list.d.ts +12 -0
  45. package/dist/store/sqlite/people-list.js +31 -7
  46. package/dist/store/sqlite/person-match-scan.js +34 -4
  47. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  48. package/dist/store/sqlite/sender-signals.d.ts +42 -0
  49. package/dist/store/sqlite/sender-signals.js +106 -0
  50. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { decodeWords } from "postal-mime";
2
+ import { registrableOf } from "./score.js";
2
3
  /**
3
4
  * The header fields memo reads at list time: enough to group mail by sender, apply the owner's rules and keep
4
5
  * an envelope of the mail a rule records without its text.
@@ -8,11 +9,13 @@ export const unfold = (text) => text.replace(/\r?\n[ \t]+/g, " ");
8
9
  export const field = (unfolded, name) => new RegExp(`^${name}:[ \\t]*(.*?)\\r?$`, "im").exec(unfolded)?.[1];
9
10
  const fieldsOf = (unfolded, name) => [...unfolded.matchAll(new RegExp(`^${name}:[ \\t]*(.*?)\\r?$`, "gim"))].map(([, value]) => value);
10
11
  /**
11
- * The verdicts in Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender
12
- * can add one under any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
12
+ * Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender can add one under
13
+ * any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
13
14
  */
15
+ const gmailStampOf = (unfolded) => fieldsOf(unfolded, "Authentication-Results").find((value) => /^mx\.google\.com\s*;/i.test(value));
16
+ /** The verdicts in Gmail's own Authentication-Results. */
14
17
  export const authOf = (unfolded) => {
15
- const stamped = fieldsOf(unfolded, "Authentication-Results").find((value) => /^mx\.google\.com\s*;/i.test(value));
18
+ const stamped = gmailStampOf(unfolded);
16
19
  if (stamped === undefined)
17
20
  return undefined;
18
21
  const results = [...stamped.matchAll(/\b(spf|dkim|dmarc)=([a-z]+)/gi)].map(([, method, result]) => [
@@ -28,6 +31,58 @@ export const authOf = (unfolded) => {
28
31
  }
29
32
  return Object.keys(verdicts).length ? verdicts : undefined;
30
33
  };
34
+ const tagsOf = (value) => new Map(value.split(";").flatMap((tag) => {
35
+ const at = tag.indexOf("=");
36
+ return at === -1 ? [] : [[tag.slice(0, at).trim().toLowerCase(), tag.slice(at + 1).replace(/\s+/g, "")]];
37
+ }));
38
+ /**
39
+ * The header fields a DKIM signature Gmail passed covers, when that signature's domain is the From's own (its
40
+ * registrable domain). A sender writes every header itself; only a signature of its own domain vouches for one.
41
+ * Without Gmail's stamp nothing is trusted: other servers' Authentication-Results may be the sender's own.
42
+ */
43
+ export const signedFieldsOf = (unfolded, from) => {
44
+ const stamped = gmailStampOf(unfolded);
45
+ if (stamped === undefined || from === undefined)
46
+ return new Set();
47
+ const passed = [...stamped.matchAll(/\bdkim=pass\b[^;]*?\bheader\.[id]=([^\s;]+)/gi)].map(([, identity]) => identity.slice(identity.lastIndexOf("@") + 1).toLowerCase());
48
+ const own = registrableOf(from);
49
+ const signed = new Set();
50
+ for (const signature of fieldsOf(unfolded, "DKIM-Signature")) {
51
+ const tags = tagsOf(signature);
52
+ const domain = tags.get("d")?.toLowerCase();
53
+ if (domain === undefined || registrableOf(domain) !== own)
54
+ continue;
55
+ if (!passed.some((one) => one === domain || one.endsWith(`.${domain}`)))
56
+ continue;
57
+ for (const name of (tags.get("h") ?? "").split(":"))
58
+ if (name !== "")
59
+ signed.add(name.toLowerCase());
60
+ }
61
+ return signed;
62
+ };
63
+ /**
64
+ * What says a program or a list sent the mail, each only when DKIM vouches for it (`signedFieldsOf`):
65
+ * `Auto-Submitted` other than `no` (RFC 3834), the one-click unsubscribe of RFC 8058 and Google's `Feedback-ID`.
66
+ * An empty Return-Path is the receiving server's, not the sender's, and marks a program unless it is an auto-reply,
67
+ * which RFC 3834 sends that way too: a person's out-of-office makes no bot.
68
+ */
69
+ const programSignalsOf = (unfolded, from) => {
70
+ const signed = signedFieldsOf(unfolded, from);
71
+ const submitted = field(unfolded, "Auto-Submitted")
72
+ ?.trim()
73
+ .toLowerCase()
74
+ .split(/[\s;(]/)[0];
75
+ const generated = submitted !== undefined && submitted !== "" && submitted !== "no" && submitted !== "auto-replied";
76
+ const oneClick = /list-unsubscribe\s*=\s*one-click/i.test(field(unfolded, "List-Unsubscribe-Post") ?? "");
77
+ return {
78
+ ...(generated && signed.has("auto-submitted") ? { "auto-submitted": submitted } : {}),
79
+ ...(oneClick && signed.has("list-unsubscribe-post") ? { "list-unsubscribe-post": true } : {}),
80
+ ...(field(unfolded, "Feedback-ID") !== undefined && signed.has("feedback-id") ? { "feedback-id": true } : {}),
81
+ ...(/^\s*<\s*>/.test(field(unfolded, "Return-Path") ?? "") && submitted !== "auto-replied"
82
+ ? { "null-return-path": true }
83
+ : {}),
84
+ };
85
+ };
31
86
  export const addressesOf = (value) => {
32
87
  if (value === undefined)
33
88
  return [];
@@ -74,19 +129,22 @@ const headTextOf = (raw) => {
74
129
  /** The header fields of a whole email, as `headersOf` reads them from a listing. */
75
130
  export const headersOfRaw = (raw) => headersOf(headTextOf(raw));
76
131
  /**
77
- * List-Id, the bulk-mail fields, Reply-To and Gmail's SPF, DKIM and DMARC verdicts of a whole email, kept on mail
78
- * stored in full so a rule or a sender score can be worked out from the store later. Names are lower case.
132
+ * List-Id, the bulk-mail fields, Reply-To, Gmail's SPF, DKIM and DMARC verdicts and what marks a program or a list
133
+ * (`programSignalsOf`) of a whole email, kept on mail stored in full so a rule, a sender score or a person's kind can
134
+ * be worked out from the store later. Names are lower case.
79
135
  */
80
136
  export const mailHeadersOf = (raw) => {
81
137
  const unfolded = unfold(headTextOf(raw));
82
138
  const listId = listIdOf(field(unfolded, "List-Id"));
83
139
  const precedence = field(unfolded, "Precedence")?.trim().toLowerCase();
84
140
  const [replyTo] = addressesOf(field(unfolded, "Reply-To"));
141
+ const [from] = addressesOf(field(unfolded, "From"));
85
142
  return {
86
143
  ...(listId ? { "list-id": listId } : {}),
87
144
  ...(replyTo === undefined ? {} : { "reply-to": replyTo }),
88
145
  ...authOf(unfolded),
89
146
  ...(field(unfolded, "List-Unsubscribe") === undefined ? {} : { "list-unsubscribe": true }),
90
147
  ...(precedence ? { precedence } : {}),
148
+ ...programSignalsOf(unfolded, from),
91
149
  };
92
150
  };
@@ -0,0 +1,15 @@
1
+ import type { AccountKey, MessageStore } from "../store/index.js";
2
+ /** Gmail's label on mail the account sent, as `decodedLabelName` gives `\\Sent`. */
3
+ export declare const SENT_LABEL = "Sent";
4
+ /** The mailbox address, the addresses the owner configured, and those the account's sent mail came from. */
5
+ export declare const ownAddresses: (store: MessageStore, key: AccountKey, configured?: readonly string[]) => Promise<Set<string>>;
6
+ /** Mail in the Sent folder or under Gmail's Sent label is the owner's whatever its From; otherwise its From says. */
7
+ export declare const sentByOwner: (from: string | null | undefined, own: ReadonlySet<string>, inSent?: boolean) => boolean | null;
8
+ /**
9
+ * After a sync: the senders of the mail in Sent join the owner's addresses, the account's mail from any of them
10
+ * becomes outgoing, and their identities join the owner as the account's own does.
11
+ */
12
+ export declare const settleOwnMail: (store: MessageStore, key: AccountKey, accountId: number, own: ReadonlySet<string>, mailboxes: readonly string[], { name, now }: {
13
+ name: string;
14
+ now: number;
15
+ }) => Promise<void>;
@@ -0,0 +1,35 @@
1
+ import { OWN_MAIL_ADDRESSES as OWN_ADDRESSES } from "../store/sqlite/own-identities.js";
2
+ /** Gmail's label on mail the account sent, as `decodedLabelName` gives `\\Sent`. */
3
+ export const SENT_LABEL = "Sent";
4
+ const normal = (address) => address.trim().toLowerCase();
5
+ const storedOwn = async (store, key) => {
6
+ const value = (await store.sync.syncState(key, OWN_ADDRESSES))?.value;
7
+ if (value === undefined)
8
+ return [];
9
+ try {
10
+ const parsed = JSON.parse(value);
11
+ return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
12
+ }
13
+ catch {
14
+ return [];
15
+ }
16
+ };
17
+ /** The mailbox address, the addresses the owner configured, and those the account's sent mail came from. */
18
+ export const ownAddresses = async (store, key, configured = []) => new Set([key.account, ...configured, ...(await storedOwn(store, key))].map(normal));
19
+ /** Mail in the Sent folder or under Gmail's Sent label is the owner's whatever its From; otherwise its From says. */
20
+ export const sentByOwner = (from, own, inSent = false) => (inSent ? true : from == null ? null : own.has(normal(from)));
21
+ /**
22
+ * After a sync: the senders of the mail in Sent join the owner's addresses, the account's mail from any of them
23
+ * becomes outgoing, and their identities join the owner as the account's own does.
24
+ */
25
+ export const settleOwnMail = async (store, key, accountId, own, mailboxes, { name, now }) => {
26
+ const before = await storedOwn(store, key);
27
+ const found = await store.mail.markOwnMail(accountId, { addresses: [...own], mailboxes }, now);
28
+ const others = found.filter((address) => address !== normal(key.account));
29
+ if (others.length === 0 && before.length === 0)
30
+ return;
31
+ if (JSON.stringify(others) !== JSON.stringify([...before].sort()))
32
+ await store.sync.setSyncState(key, OWN_ADDRESSES, JSON.stringify(others));
33
+ // Saving the account again is what links its own identities, now with these addresses.
34
+ await store.accounts.saveAccount(key, { name });
35
+ };
@@ -1,6 +1,8 @@
1
+ import { mailAccountKey } from "./account-key.js";
1
2
  import { FETCH_CHUNK, readAttachments } from "./attachments.js";
2
3
  import { parsedEmail } from "./email-input.js";
3
4
  import { mailHeadersOf } from "./headers.js";
5
+ import { ownAddresses, SENT_LABEL } from "./own.js";
4
6
  import { parseMail } from "./parse.js";
5
7
  /** The `emails.metadata` key of an email stored from its first bytes: `{ bytes }` read of its `size`. */
6
8
  export const PARTIAL = "partial";
@@ -19,6 +21,7 @@ export const completePartial = async ({ store, source, accountId, address, folde
19
21
  const { emails, total, stuck } = await store.mail.partialEmails(accountId, PARTIAL_PER_RUN);
20
22
  if (emails.length === 0)
21
23
  return { completed: 0, left: 0, stuck };
24
+ const own = await ownAddresses(store, mailAccountKey(address));
22
25
  let given = 0;
23
26
  // A failed read is counted, so an email the server no longer gives is not read whole on every sync forever.
24
27
  const failed = async (email, forGood = false) => {
@@ -98,7 +101,7 @@ export const completePartial = async ({ store, source, accountId, address, folde
98
101
  now,
99
102
  emails: [
100
103
  {
101
- ...parsedEmail(mail, whole, mailHeadersOf(raw), address),
104
+ ...parsedEmail(mail, whole, mailHeadersOf(raw), own, whole.labels?.includes(SENT_LABEL)),
102
105
  receivedAt: email.receivedAt,
103
106
  size: raw.byteLength,
104
107
  metadata,
@@ -8,6 +8,7 @@ import { bulkBox } from "./bulk.js";
8
8
  import { parsedEmail } from "./email-input.js";
9
9
  import { factsOf } from "./facts.js";
10
10
  import { mailHeadersOf } from "./headers.js";
11
+ import { ownAddresses, SENT_LABEL } from "./own.js";
11
12
  import { parseMail } from "./parse.js";
12
13
  import { PARTIAL } from "./partial.js";
13
14
  import { storedMailRules } from "./rule-stored.js";
@@ -80,6 +81,7 @@ export const searchMailServer = async (store, mailbox, access, request) => {
80
81
  report.failed.push({ chat: call?.folder ?? null, reason });
81
82
  };
82
83
  const accountId = await store.accounts.saveAccount(mailbox, { name: mailbox.account });
84
+ const own = await ownAddresses(store, mailbox);
83
85
  const fresh = [];
84
86
  let rules = [];
85
87
  const ruled = new Map();
@@ -179,7 +181,7 @@ export const searchMailServer = async (store, mailbox, access, request) => {
179
181
  now,
180
182
  emails: [
181
183
  {
182
- ...parsedEmail(mail, item, mailHeadersOf(raw), mailbox.account),
184
+ ...parsedEmail(mail, item, mailHeadersOf(raw), own, item.labels?.includes(SENT_LABEL)),
183
185
  mailboxes: [
184
186
  { externalId: folder, name: folder, kind: null },
185
187
  ...(item.labels ?? []).map((name) => ({ externalId: `label:${name}`, name, kind: "label" })),
@@ -97,10 +97,14 @@ export interface MailSource {
97
97
  moved: string[];
98
98
  missing: string[];
99
99
  }>;
100
- /** All Mail and Trash under the names this account's language gives them. */
100
+ /**
101
+ * All Mail and Trash under the names this account's language gives them, and on IMAP the folder the server marks
102
+ * `\Sent` (RFC 6154), else the one a common name gives when the server marks no folder at all.
103
+ */
101
104
  folders?(): Promise<{
102
105
  all: string;
103
106
  trash: string;
107
+ sent?: string;
104
108
  }>;
105
109
  /** Which of these UIDs `folder` still holds. */
106
110
  present?(uids: readonly string[], folder: string): Promise<string[]>;
@@ -12,6 +12,8 @@ export interface MailAccount {
12
12
  address: string;
13
13
  mode?: "gmail" | "imap" | "mbox";
14
14
  folders?: string[];
15
+ /** The owner's other addresses on this mailbox, such as aliases: mail from them is the owner's. */
16
+ addresses?: string[];
15
17
  rules?: MailRule[];
16
18
  }
17
19
  /** What an index step reports, as memo's embedding does; the sync only passes it on. */
package/dist/mail/sync.js CHANGED
@@ -7,11 +7,12 @@ import { DEFAULT_ATTACHMENT_POLICY, FETCH_CHUNK, MAX_ATTACHMENT_CHARS, readAttac
7
7
  import { BULK, bulkBox } from "./bulk.js";
8
8
  import { parsedEmail } from "./email-input.js";
9
9
  import { factsOf } from "./facts.js";
10
- import { GMAIL_ALL_MAIL, mailFolders } from "./folders.js";
10
+ import { GMAIL_ALL_MAIL, mailFolders, sentFolder } from "./folders.js";
11
11
  import { dropMissing, tooManyGone } from "./gone.js";
12
12
  import { mailHeadersOf } from "./headers.js";
13
13
  import { flagsToRefresh, proveByLocation } from "./locations.js";
14
14
  import { saveMeetingNotes } from "./meeting-notes.js";
15
+ import { ownAddresses, SENT_LABEL, sentByOwner, settleOwnMail } from "./own.js";
15
16
  import { MAX_BODY_CHARS, parseMail } from "./parse.js";
16
17
  import { completePartial } from "./partial.js";
17
18
  import { FETCH_SLICE, keyOf, readQuick } from "./quick.js";
@@ -201,7 +202,12 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
201
202
  const startedAt = now();
202
203
  const key = mailAccountKey(account.address);
203
204
  const accountId = await store.accounts.saveAccount(key, { name: account.address });
204
- const folders = await mailFolders(account, source);
205
+ const list = source.folders?.bind(source);
206
+ let listing;
207
+ const named = list ? { folders: () => (listing ??= list()) } : {};
208
+ const folders = await mailFolders(account, named);
209
+ const sent = await sentFolder(account, named);
210
+ const own = await ownAddresses(store, key, account.addresses);
205
211
  if (folders.length < 1 || folders.length > 50)
206
212
  throw new Error("select 1–50 mail folders");
207
213
  const rules = account.rules ?? [];
@@ -571,6 +577,8 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
571
577
  ...[...(foundFolders.get(item.messageId) ?? [])].map(mailbox),
572
578
  ...(labelsOf.get(item.messageId)?.labels ?? []).map(label),
573
579
  ];
580
+ const inSent = (item) => (sent !== undefined && (foundFolders.get(item.messageId)?.has(sent) ?? false)) ||
581
+ (labelsOf.get(item.messageId)?.labels ?? []).includes(SENT_LABEL);
574
582
  const flagsOf = (item) => {
575
583
  const { seen, flagged } = labelsOf.get(item.messageId) ?? {};
576
584
  return { ...(seen === undefined ? {} : { read: seen }), ...(flagged === undefined ? {} : { flagged }) };
@@ -707,7 +715,7 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
707
715
  receivedAt: Date.parse(item.receivedAt),
708
716
  bodyText: null,
709
717
  size: item.size ?? null,
710
- outgoing: headers?.from === key.account,
718
+ outgoing: sentByOwner(headers?.from, own, inSent(item)) ?? false,
711
719
  mailboxes: [...inMailboxes(item), envelopeBox(rule.match)],
712
720
  ...locationOf(item),
713
721
  ...flagsOf(item),
@@ -788,7 +796,7 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
788
796
  now: startedAt,
789
797
  emails: [
790
798
  {
791
- ...parsedEmail(mail, item, header, key.account),
799
+ ...parsedEmail(mail, item, header, own, inSent(item)),
792
800
  mailboxes: inMailboxes(item),
793
801
  ...locationOf(item),
794
802
  ...flagsOf(item),
@@ -839,6 +847,10 @@ const syncRound = async (source, store, { account, since, max = 200, maxBodyChar
839
847
  await store.sync.setSyncState(key, "mail_folder_scope", scope);
840
848
  if (!snapshot)
841
849
  await store.mail.backfillSentAt(accountId, SENT_AT_BACKFILL_PER_RUN);
850
+ await settleOwnMail(store, key, accountId, own, [...(sent ? [sent] : []), `label:${SENT_LABEL}`], {
851
+ name: account.address,
852
+ now: startedAt,
853
+ });
842
854
  await stopIfAborted();
843
855
  const indexed = await index?.(store, key);
844
856
  const coverage = {
@@ -29,6 +29,8 @@ export interface FakeMail {
29
29
  flagged?: boolean;
30
30
  /** `trash` puts it in the trash folder; otherwise it is in All Mail, which INBOX also shows. */
31
31
  folder?: "trash";
32
+ /** Also in the mailbox's `sent` folder, as an IMAP server files mail the owner sent. */
33
+ sent?: boolean;
32
34
  /** Folders that do not hold it although its `folder` says they do, as a server's delete from one folder leaves it. */
33
35
  absentFrom?: string[];
34
36
  /** Listed without headers even when they are asked for, as a server does when it cannot read them. */
@@ -40,6 +42,8 @@ export interface FakeMailbox {
40
42
  /** All Mail under the account's language, as Gmail names it. */
41
43
  allMail?: string;
42
44
  trash?: string;
45
+ /** An IMAP Sent folder: `folders` names it, and it holds the mail marked `sent`. */
46
+ sent?: string;
43
47
  validity?: number;
44
48
  /** Each answer of `search` and `list` ends in this failure. */
45
49
  searchFails?: string;
@@ -72,6 +72,8 @@ export const fakeMailSource = (mailbox) => {
72
72
  const all = () => mailbox.allMail ?? GMAIL_ALL_MAIL;
73
73
  const trash = () => mailbox.trash ?? TRASH;
74
74
  const inFolder = (folder) => {
75
+ if (folder === mailbox.sent)
76
+ return mailbox.messages.filter((m) => m.sent && !m.absentFrom?.includes(folder));
75
77
  if (![all(), trash(), "INBOX"].includes(folder))
76
78
  throw failure(`Gmail has no such mailbox: ${folder}`);
77
79
  return mailbox.messages.filter((m) => (folder === trash() ? m.folder === "trash" : m.folder !== "trash") && !m.absentFrom?.includes(folder));
@@ -182,7 +184,7 @@ export const fakeMailSource = (mailbox) => {
182
184
  const moved = here.map((m) => m.messageId);
183
185
  return { moved, missing: messageIds.filter((id) => !moved.includes(id)) };
184
186
  },
185
- folders: async () => ({ all: all(), trash: trash() }),
187
+ folders: async () => ({ all: all(), trash: trash(), ...(mailbox.sent ? { sent: mailbox.sent } : {}) }),
186
188
  present: async (uids, folder) => inFolder(folder).flatMap((m) => (uids.includes(m.uid) ? [m.uid] : [])),
187
189
  label: async (messageIds, folder, labels) => {
188
190
  for (const m of inFolder(folder))
@@ -4,6 +4,7 @@ import { mailAccountKey } from "./account-key.js";
4
4
  import { MAX_ATTACHMENT_CHARS, readAttachments } from "./attachments.js";
5
5
  import { parsedEmail } from "./email-input.js";
6
6
  import { mailHeadersOf } from "./headers.js";
7
+ import { ownAddresses, SENT_LABEL } from "./own.js";
7
8
  import { MAX_BODY_CHARS, parseMail } from "./parse.js";
8
9
  import { PARTIAL } from "./partial.js";
9
10
  /**
@@ -42,6 +43,7 @@ export const readEmailWhole = async ({ store, source, address, externalId, folde
42
43
  if (!source.find && source.identify?.(raw, item).messageId !== externalId)
43
44
  throw new CliError("not_found", `the mail server holds another email where ${externalId} was`);
44
45
  const mail = await parseMail(raw, maxBodyChars);
46
+ const own = await ownAddresses(store, mailAccountKey(address));
45
47
  const log = [];
46
48
  const files = await readAttachments(mail, externalId, { loadEngine, maxAttachmentChars, at: now }, log);
47
49
  const { [PARTIAL]: _partial, ...metadata } = stored.metadata ?? {};
@@ -52,7 +54,7 @@ export const readEmailWhole = async ({ store, source, address, externalId, folde
52
54
  now,
53
55
  emails: [
54
56
  {
55
- ...parsedEmail(mail, whole, mailHeadersOf(raw), address),
57
+ ...parsedEmail(mail, whole, mailHeadersOf(raw), own, whole.labels?.includes(SENT_LABEL)),
56
58
  receivedAt: stored.receivedAt,
57
59
  size: raw.byteLength,
58
60
  metadata,
@@ -104,6 +104,7 @@ export type { RelationRole, RelationRoles } from "./sqlite/relation-roles.js";
104
104
  export type { RelationsStore, ReportedIssue, ReportedRelation, ReportedScope, ReportedSync, } from "./sqlite/reported-relations.js";
105
105
  export type { AuthorInfo, Party, Reviewed, Written } from "./sqlite/reviewed.js";
106
106
  export { fillSearchIndex, resetSearchIndex, type SearchIndexFill, type SearchIndexState, searchIndexState, } from "./sqlite/search-index.js";
107
+ export { REACHES, type Reach, type SenderSignal } from "./sqlite/sender-signals.js";
107
108
  export type { ChallengeInput, SourceReviewDecision } from "./sqlite/source-review.js";
108
109
  export type { PriceFilter, PriceInput, Subscription, SubscriptionDetail, SubscriptionFields, SubscriptionFilter, SubscriptionInput, SubscriptionPrice, SubscriptionsStore, SubscriptionUpdate, } from "./sqlite/subscriptions.js";
109
110
  export type { SyncStateSave } from "./sqlite/sync.js";
@@ -52,6 +52,7 @@ export { ALWAYS_SHOWN, PERSON_TIES, SMALL_GROUP_MEMBERS, } from "./sqlite/person
52
52
  export { assertGenericAction, PROPOSAL_STATUSES, proposerOfAction, } from "./sqlite/proposed-actions.js";
53
53
  export { waitingPointer, } from "./sqlite/records.js";
54
54
  export { fillSearchIndex, resetSearchIndex, searchIndexState, } from "./sqlite/search-index.js";
55
+ export { REACHES } from "./sqlite/sender-signals.js";
55
56
  export { PROJECT_TASK_FIELDS, TASK_SORTS, withoutField } from "./sqlite/task-board.js";
56
57
  export { certaintyOf } from "./sqlite/task-close.js";
57
58
  export { TASK_PAIR_DECISIONS } from "./sqlite/task-pairs.js";
@@ -22,6 +22,7 @@ export const accountMessagesOver = (context) => {
22
22
  if (upsertMessage(key, accountKey, chatKey, message, via, seenAt) && countUnread)
23
23
  messageWrites.countUnread(context, chatKey, message);
24
24
  }
25
+ messageWrites.linkThreadChildren(context, chatKey, messages.filter((message) => message.scheduledFor === undefined).map((message) => message.id));
25
26
  for (const { messageId, vote } of votes)
26
27
  messageWrites.saveVote(context, accountKey, key.provider, chatKey, messageId, vote);
27
28
  for (const { messageId, reaction } of reactions)
@@ -6,7 +6,7 @@ export interface NewestEmail {
6
6
  /** ms: when it was received, or sent when that is unknown. */
7
7
  at: number;
8
8
  outgoing: boolean;
9
- /** The mailbox's own address is in To or Cc. */
9
+ /** One of the mailbox's own addresses (its own, an alias in `mail_own_addresses`) is in To or Cc. */
10
10
  addressed: boolean;
11
11
  /** Filed in the mailbox of mail sent to many. */
12
12
  bulk: boolean;
@@ -1,6 +1,7 @@
1
1
  import { contextEvidenceFingerprint } from "../../context/evidence.js";
2
2
  import { formatLocator } from "../../domain/locator.js";
3
3
  import { int, str } from "./events.js";
4
+ import { OWN_MAIL_ADDRESSES } from "./own-identities.js";
4
5
  /** `tasks agenda` fields over `threadActivity`'s threads: an email thread counts as a dialog. */
5
6
  export const MAIL_AGENDA_COLUMNS = { chat_kind: { type: "enum", sql: "'dialog'" } };
6
7
  // The thread's own time is the Date header where sync stored one, so a thread is picked by it; the newest email is
@@ -10,7 +11,9 @@ const ACTIVITY = `
10
11
  e.external_id, coalesce(e.received_at, e.sent_at) AS at,
11
12
  coalesce(e.outgoing, lower(e.from_address) = lower(a.external_id)) AS outgoing,
12
13
  EXISTS (SELECT 1 FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')
13
- AND lower(r.address) = lower(a.external_id)) AS addressed,
14
+ AND (lower(r.address) = lower(a.external_id) OR lower(trim(r.address)) IN (SELECT j.value FROM sync_cursors s,
15
+ json_each(CASE WHEN json_valid(s.value) THEN s.value ELSE '[]' END) j
16
+ WHERE s.account_id = a.id AND s.key = '${OWN_MAIL_ADDRESSES}'))) AS addressed,
14
17
  EXISTS (SELECT 1 FROM email_mailboxes m JOIN mailboxes b ON b.id = m.mailbox_id
15
18
  WHERE m.email_id = e.id AND b.kind = 'bulk') AS bulk,
16
19
  coalesce(json_extract(e.headers, '$."list-id"'), json_extract(e.metadata, '$.listId')) IS NOT NULL AS list,
@@ -8,3 +8,11 @@ export declare const setEmailFlags: (database: CacheDatabase, accountId: number,
8
8
  }>, now: number) => number;
9
9
  export declare const markEmailsDeleted: (database: CacheDatabase, accountId: number, externalIds: string[], now: number) => number;
10
10
  export declare const markEmailsRestored: (database: CacheDatabase, accountId: number, externalIds: string[], now: number) => number;
11
+ /**
12
+ * Takes the senders of the live mail in `mailboxes` as the owner's, beside `addresses`, and marks every email of the
13
+ * account from any of them outgoing. Answers the addresses, lower case.
14
+ */
15
+ export declare const markOwnMail: (database: CacheDatabase, accountId: number, { addresses, mailboxes }: {
16
+ addresses: readonly string[];
17
+ mailboxes: readonly string[];
18
+ }, now: number) => string[];
@@ -51,3 +51,26 @@ export const markEmailsRestored = (database, accountId, externalIds, now) => {
51
51
  recountEmailThread(database, id, now);
52
52
  return threads.length;
53
53
  };
54
+ /**
55
+ * Takes the senders of the live mail in `mailboxes` as the owner's, beside `addresses`, and marks every email of the
56
+ * account from any of them outgoing. Answers the addresses, lower case.
57
+ */
58
+ export const markOwnMail = (database, accountId, { addresses, mailboxes }, now) => {
59
+ const own = new Set(addresses.map((address) => address.trim().toLowerCase()));
60
+ if (mailboxes.length > 0)
61
+ for (const row of database
62
+ .prepare(`SELECT DISTINCT lower(trim(e.from_address)) AS address FROM mailboxes b
63
+ JOIN email_mailboxes m ON m.mailbox_id = b.id JOIN emails e ON e.id = m.email_id
64
+ WHERE b.account_id = ? AND b.external_id IN (SELECT value FROM json_each(?))
65
+ AND e.deleted_at IS NULL AND e.from_address IS NOT NULL`)
66
+ .all(accountId, JSON.stringify(mailboxes)))
67
+ if (typeof row.address === "string" && row.address !== "")
68
+ own.add(row.address);
69
+ if (own.size > 0)
70
+ database
71
+ .prepare(`UPDATE emails SET outgoing = 1, updated_at = ? WHERE account_id = ? AND outgoing IS NOT 1
72
+ AND from_identity_id IN (SELECT id FROM identities WHERE provider = 'email'
73
+ AND external_id IN (SELECT value FROM json_each(?)))`)
74
+ .run(now, accountId, JSON.stringify([...own]));
75
+ return [...own].sort();
76
+ };
@@ -239,6 +239,15 @@ export interface MailStore extends PartialMailStore, MailActivityStore {
239
239
  read?: boolean;
240
240
  flagged?: boolean;
241
241
  }>, now: number): Promise<number>;
242
+ /**
243
+ * Takes the senders of the live mail in `mailboxes` (the Sent folder, Gmail's `label:Sent`) as the owner's, beside
244
+ * `addresses`, and marks the account's mail from any of them outgoing, so mail stored before it was known counts.
245
+ * Answers the addresses, lower case.
246
+ */
247
+ markOwnMail(accountId: number, own: {
248
+ addresses: readonly string[];
249
+ mailboxes: readonly string[];
250
+ }, now: number): Promise<string[]>;
242
251
  /** Gives up to `limit` emails stored without `sent_at` their internal date; answers how many. */
243
252
  backfillSentAt(accountId: number, limit: number): Promise<number>;
244
253
  /** The live emails whose location in `folder` has this UIDVALIDITY, oldest UID first. */
@@ -4,7 +4,7 @@ import { fold, normalize } from "../normalize.js";
4
4
  import { mailActivity, threadEmailIds } from "./email-activity.js";
5
5
  import { chunkAttachments, drainEmailIndex, dropAttachmentChunks, MAIL_PIECES, queueThreads, threadPieces, titleOf, } from "./email-index.js";
6
6
  import { backfillSentAt, folderEmails, forgetLocations, locate, partialMail, setLocations, storedWhole, } from "./email-locations.js";
7
- import { markEmailsDeleted, markEmailsRestored, recountEmailThread as recount, setEmailFlags } from "./email-state.js";
7
+ import { markEmailsDeleted, markEmailsRestored, markOwnMail, recountEmailThread as recount, setEmailFlags, } from "./email-state.js";
8
8
  import { EMAIL_ENRICHMENT, enrichmentText } from "./enrichments.js";
9
9
  import { bool, flag, fromJson, int, page, str, toJson } from "./events.js";
10
10
  import { folded } from "./folded.js";
@@ -560,6 +560,7 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
560
560
  });
561
561
  },
562
562
  setFlags: async (accountId, flags, now) => write(database, () => setEmailFlags(database, accountId, flags, now)),
563
+ markOwnMail: async (accountId, own, at) => write(database, () => markOwnMail(database, accountId, own, at)),
563
564
  backfillSentAt: async (accountId, limit) => write(database, () => backfillSentAt(database, accountId, limit)),
564
565
  folderEmails: async (accountId, folder, uidvalidity) => folderEmails(database, accountId, folder, uidvalidity),
565
566
  setLocations: async (accountId, folder, uidvalidity, found) => write(database, () => setLocations(database, accountId, folder, uidvalidity, found)),
@@ -1,6 +1,11 @@
1
1
  import type { Delivery, Id, Message, PersonReaction, PollVote, Provider, Reactions, Reactor } from "../../domain/models.js";
2
2
  import type { AccountKey, DeletionScope } from "../types.js";
3
3
  import type { StoreContext } from "./open.js";
4
+ /**
5
+ * Points replies saved before their thread's root at it. Run once per page: no index covers `thread_external_id`,
6
+ * so each run reads the whole chat, and once per message made a sync slow down as the chat grew (tg-cli #917).
7
+ */
8
+ export declare const linkThreadChildren: (context: StoreContext, chatKey: number, rootIds: readonly Id[]) => void;
4
9
  export declare const upsertMessage: (context: StoreContext, key: AccountKey, accountKey: number, chatKey: number, received: Message, via: string, seenAt?: number) => boolean;
5
10
  /**
6
11
  * One more unread for a message from someone else that the store first saw now, sent after the messenger's count was
@@ -114,6 +114,19 @@ const fieldsOf = (message, sender) => ({
114
114
  normalizedText: normalize(message.text),
115
115
  normalizerVersion: NORMALIZER_VERSION,
116
116
  });
117
+ /**
118
+ * Points replies saved before their thread's root at it. Run once per page: no index covers `thread_external_id`,
119
+ * so each run reads the whole chat, and once per message made a sync slow down as the chat grew (tg-cli #917).
120
+ */
121
+ export const linkThreadChildren = (context, chatKey, rootIds) => {
122
+ if (rootIds.length === 0)
123
+ return;
124
+ context.database
125
+ .prepare(`UPDATE messages SET thread_root_id=(SELECT root.id FROM messages root
126
+ WHERE root.chat_id=messages.chat_id AND root.external_id=messages.thread_external_id)
127
+ WHERE chat_id=? AND thread_root_id IS NULL AND thread_external_id IN (SELECT value FROM json_each(?))`)
128
+ .run(chatKey, JSON.stringify(rootIds.map(String)));
129
+ };
117
130
  export const upsertMessage = (context, key, accountKey, chatKey, received, via, seenAt) => {
118
131
  const { orm, now } = context;
119
132
  const message = withoutBotTokensIn(received);
@@ -224,9 +237,6 @@ export const upsertMessage = (context, key, accountKey, chatKey, received, via,
224
237
  .prepare("UPDATE messages SET thread_root_id=(SELECT id FROM messages WHERE chat_id=? AND external_id=?) WHERE id=?")
225
238
  .run(chatKey, root, pk);
226
239
  }
227
- context.database
228
- .prepare("UPDATE messages SET thread_root_id=? WHERE chat_id=? AND thread_external_id=? AND thread_root_id IS NULL")
229
- .run(pk, chatKey, message.id);
230
240
  const heardFirst = context.database
231
241
  .prepare("UPDATE message_transcripts SET message_id=? WHERE chat_id=? AND message_external_id=? AND message_id IS NULL")
232
242
  .run(pk, chatKey, message.id).changes;
@@ -1,5 +1,7 @@
1
1
  import type { IdentityRef, PersonRecord } from "../types.js";
2
2
  import type { StoreContext } from "./open.js";
3
+ /** Sync state under a mail account: the owner's other addresses on it, lower case, as a JSON array. */
4
+ export declare const OWN_MAIL_ADDRESSES = "mail_own_addresses";
3
5
  /**
4
6
  * An account's own identity (same provider and id as the account) is usually the owner. Messengers save it like anyone
5
7
  * else's, as a person of its own, so the owner's name counted as a contact's. Links that person to the owner when every
@@ -7,6 +7,8 @@ import { mergePerson, personOf } from "./person-links.js";
7
7
  import { RULE } from "./person-match-scan.js";
8
8
  import { separated } from "./person-separation.js";
9
9
  import { write } from "./transaction.js";
10
+ /** Sync state under a mail account: the owner's other addresses on it, lower case, as a JSON array. */
11
+ export const OWN_MAIL_ADDRESSES = "mail_own_addresses";
10
12
  const ACCOUNT_REASON = "an account you connected, under another name: a mailbox or messenger you read may be someone else's";
11
13
  const ownerNames = ({ database }, owner) => database
12
14
  .prepare("SELECT i.name FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE l.person_id = ?")
@@ -49,7 +51,7 @@ export const linkOwnIdentities = (context) => {
49
51
  own.push({ identity: Number(row.identity), person, name: typeof row.name === "string" ? row.name : null });
50
52
  byPerson.set(person, own);
51
53
  }
52
- if (byPerson.size === 0)
54
+ if (byPerson.size === 0 && aliasPeople(context, owner).length === 0)
53
55
  return 0;
54
56
  return write(context.database, () => {
55
57
  let joined = 0;
@@ -74,9 +76,30 @@ export const linkOwnIdentities = (context) => {
74
76
  reason: ACCOUNT_REASON,
75
77
  });
76
78
  }
79
+ for (const person of aliasPeople(context, owner)) {
80
+ if (separated(context, person, owner))
81
+ continue;
82
+ mergePerson(context, person, owner, { method: "account", by: "rules" });
83
+ joined += 1;
84
+ }
77
85
  return joined;
78
86
  });
79
87
  };
88
+ /**
89
+ * People holding one of a mail account's other own addresses (`OWN_MAIL_ADDRESSES`), once the account's own identity
90
+ * is the owner's: an alias follows the account, whatever name its mail carries. A partner's mailbox keeps its aliases.
91
+ */
92
+ const aliasPeople = ({ database }, owner) => database
93
+ .prepare("SELECT DISTINCT l.person_id AS person FROM sync_cursors s " +
94
+ "JOIN accounts a ON a.id = s.account_id AND a.provider = 'email' " +
95
+ "JOIN json_each(CASE WHEN json_valid(s.value) THEN s.value ELSE '[]' END) j " +
96
+ "JOIN identities i ON i.provider = 'email' AND i.external_id = j.value AND i.bot IS NOT 1 " +
97
+ "JOIN identity_links l ON l.identity_id = i.id " +
98
+ "WHERE s.key = ? AND l.person_id <> ? AND EXISTS (SELECT 1 FROM identities ai " +
99
+ "JOIN identity_links al ON al.identity_id = ai.id " +
100
+ "WHERE ai.provider = a.provider AND ai.external_id = a.external_id AND al.person_id = ?) ORDER BY l.person_id")
101
+ .all(OWN_MAIL_ADDRESSES, owner, owner)
102
+ .map(({ person }) => Number(person));
80
103
  /** `contacts link <person> me`: an identity the account id does not name, a Zoom user for one, is the owner. */
81
104
  export const linkToOwner = (context, ref) => {
82
105
  const owner = ownerPerson(context.database).id;