Cotton code
767 lines · 41.9 KB · TypeScriptRaw
/** * `crates/cotton-core/src/import/messages_engine_tests.rs`, case for case, over * a real personal object (test/import-file.ts): the engine is the phone's * own, run as WASM (src/import/driver.ts), so these prove the object's driver * answers it as the phone's file does. The Rust tables are the * object's (`cotton_msg_threads` → `thread`, `cotton_msg_thread_participants` → * `thread_member`, `cotton_msg_reactions` → `message_reaction`, …); a JSON * column is held parsed. The pure helpers (the label key, a label that is a * number) are the engine's and tested there. Skipped: the probe (`probe_import` is not ported), * the owner's self names (not ported) and the workspace-not-found refusal * (one database per object: there is no workspace to miss). */import { describe, expect, it } from "vitest";import type { EnvelopeMedia, EnvelopeMessage, EnvelopeThread, EnvelopeThreadParticipant, ImportBatch } from "../src/import/envelope.ts";import { CONTENT_EXTERNAL_ID_PREFIX, contentFingerprint } from "../src/import/fingerprint.ts";import { groupExternalKey } from "../src/import/group.ts";import { EngineRefusal } from "../src/import/driver.ts";import { MESSAGE_BY_EXTERNAL_ID_SQL } from "../src/import/reader.ts";import { NOW, RESERVED, TestFile, WORKSPACE } from "./import-file.ts";/** `meta.mediaOnly`, the key a source with real ids names a picture-only message's kind under (the engine's `MEDIA_ONLY_META`). */const MEDIA_ONLY_META = "mediaOnly";// ── the fixtures ────────────────────────────────────────────────────────────const envelope = (externalId: string, over: Partial<EnvelopeMessage> = {}): EnvelopeMessage => ({  phone: "919999000011",  displayName: "Ravi",  direction: "in",  body: "hello",  sentAt: "2021-03-04T09:00:00.000Z",  externalId,  ...over,});/** The group form: no phone on the message, a label instead. */const fromLabel = (externalId: string, senderLabel: string, over: Partial<EnvelopeMessage> = {}): EnvelopeMessage => {  const m = envelope(externalId, { senderLabel, ...over });  delete m.phone;  delete m.displayName;  return { ...m, ...over };};/** A counterpart nobody named — the dm-block form. */const anonymous = (externalId: string, body: string, over: Partial<EnvelopeMessage> = {}): EnvelopeMessage => {  const m = envelope(externalId, { body });  delete m.phone;  delete m.displayName;  return { ...m, ...over };};const batch = (messages: EnvelopeMessage[], over: Partial<ImportBatch> = {}): ImportBatch => ({ workspaceId: WORKSPACE, channel: "whatsapp", messages, ...over });const participant = (label: string, phone?: string, over: Partial<EnvelopeThreadParticipant> = {}): EnvelopeThreadParticipant => ({ label, ...(phone ? { phone } : {}), ...over });const groupBlock = (title: string, externalKey: string, participants: EnvelopeThreadParticipant[]): EnvelopeThread => ({ kind: "group", title, externalKey, participants });const media = (key: string, over: Partial<EnvelopeMedia> = {}): EnvelopeMedia => ({ key, contentType: "image/jpeg", ...over });const byExternal = (id: string) => (r: { data: Record<string, unknown> }) => r.data.external_id === id;// ── dm import ───────────────────────────────────────────────────────────────describe("dm import", () => {  it("creates the contact and thread and files the messages as imported", async () => {    const file = await TestFile.open();    const report = await file.import(batch([envelope("wa:1", { body: "first" }), envelope("wa:2", { body: "second", direction: "out" })]));    expect(report.totals).toMatchObject({ chats: 1, inserted: 2, skipped: 0 });    const rows = (await file.rows("message")).map((r) => [r.data.origin, r.data.channel, r.data.external_id]).sort();    expect(rows).toEqual([      ["imported", "whatsapp", "wa:1"],      ["imported", "whatsapp", "wa:2"],    ]);    const [contact] = await file.rows("message_contact");    expect(contact!.data.phone_e164).toBe("919999000011");    expect(contact!.data.auth_user_id ?? null).toBeNull();    expect(contact!.data.person_id ?? null).toBeNull();  });  it("re-running the same export writes zero new rows", async () => {    const file = await TestFile.open();    const again = batch([envelope("wa:1"), envelope("wa:2", { body: "two" })]);    await file.import(again);    const second = await file.import(again);    expect(second.totals.inserted).toBe(0);    expect(second.totals.skipped).toBe(2);    expect(await file.count("message")).toBe(2);  });  it("dedupes within a batch because an export can repeat a line", async () => {    const file = await TestFile.open();    const report = await file.import(batch([envelope("wa:1"), envelope("wa:1")]));    expect(report.totals.inserted).toBe(1);    expect(report.totals.skipped).toBe(1);    expect(await file.count("message")).toBe(1);  });  it("keeps an owner-corrected name over whatever the export says", async () => {    const file = await TestFile.open();    await file.seedContact("c1", "919999000011", "Ravi Kumar");    await file.import(batch([envelope("wa:1", { displayName: "ravi (work)" })]));    expect((await file.one("message_contact", (r) => r.id === "c1"))!.data.display_name).toBe("Ravi Kumar");  });  it("fills a name we never had", async () => {    const file = await TestFile.open();    await file.seedContact("c1", "919999000011", null);    await file.import(batch([envelope("wa:1")]));    expect((await file.one("message_contact", (r) => r.id === "c1"))!.data.display_name).toBe("Ravi");  });  it("reuses an existing dm thread rather than forking the conversation", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("wa:1")]));    await file.import(batch([envelope("wa:2", { body: "later" })]));    expect(await file.count("thread")).toBe(1);    expect(await file.count("message_contact")).toBe(1);  });  it("splits a batch into one thread per person", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("wa:1"), envelope("wa:2", { phone: "919999000022", displayName: "Priya" })]));    expect(await file.count("thread")).toBe(2);    expect(await file.count("message_contact")).toBe(2);  });});// ── the caller's reserved thread id ─────────────────────────────────────────describe("the caller's reserved thread id", () => {  it("creates a dm thread under the id the caller reserved", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("wa:1")], { dm: participant("Ravi", "919999000011"), newThreadId: RESERVED }));    expect(await file.column("thread", "id")).toEqual([RESERVED]);  });  it("mints its own ids where one reserved id cannot serve n threads", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("wa:1"), envelope("wa:2", { phone: "919999000022", displayName: "Asha" })], { newThreadId: RESERVED }));    const ids = await file.column("thread", "id");    expect(ids).toHaveLength(2);    expect(ids).not.toContain(RESERVED);  });  it("creates a group thread under the reserved id too", async () => {    const file = await TestFile.open();    await file.import(batch([fromLabel("wa:g1", "Asha")], { thread: groupBlock("Weekend", "wa:group:weekend", [participant("Asha")]), newThreadId: RESERVED }));    expect(await file.column("thread", "id")).toEqual([RESERVED]);  });  it("the reserved id is ignored when the conversation already exists", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("wa:1")], { dm: participant("Ravi", "919999000011") }));    const existing = await file.column("thread", "id");    await file.import(batch([envelope("wa:2", { body: "again" })], { dm: participant("Ravi", "919999000011"), newThreadId: RESERVED }));    expect(await file.column("thread", "id")).toEqual(existing);  });});// ── the thread denorm ───────────────────────────────────────────────────────describe("the thread denorm", () => {  it("stamps last_message_at and the preview from the newest imported row", async () => {    const file = await TestFile.open();    await file.import(      batch([envelope("wa:1", { sentAt: "2021-03-04T09:00:00.000Z", body: "old line" }), envelope("wa:2", { sentAt: "2023-06-01T10:00:00.000Z", body: "newest line" })]),    );    const [thread] = await file.rows("thread");    expect(thread!.data.last_message_at).toBe("2023-06-01T10:00:00.000Z");    expect(thread!.data.last_message_preview).toBe("newest line");  });  it("never drags a live thread's stamp backwards", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("wa:new", { sentAt: "2026-01-01T00:00:00.000Z", body: "current" })]));    await file.import(batch([envelope("wa:old", { sentAt: "2020-01-01T00:00:00.000Z", body: "ancient" })]));    const [thread] = await file.rows("thread");    expect(thread!.data.last_message_at).toBe("2026-01-01T00:00:00.000Z");    expect(thread!.data.last_message_preview).toBe("current");  });  it("stamps a group thread the same way", async () => {    const file = await TestFile.open();    await file.import(      batch([fromLabel("wa:g1", "Ravi", { sentAt: "2024-02-02T08:00:00.000Z", body: "group word" })], {        thread: groupBlock("Site crew", "wa:group:site-crew", [participant("Ravi", "919999000011")]),      }),    );    const thread = await file.one("thread", (r) => r.data.kind === "group");    expect(thread!.data.last_message_at).toBe("2024-02-02T08:00:00.000Z");    expect(thread!.data.last_message_preview).toBe("group word");  });});// ── replies ─────────────────────────────────────────────────────────────────describe("replies", () => {  it("links a reply to the line it quotes whichever arrives first", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("wa:2", { body: "yes", replyToExternalId: "wa:1" })]));    expect((await file.one("message", byExternal("wa:2")))!.data.reply_to_id ?? null).toBeNull();    await file.import(batch([envelope("wa:1", { body: "are you there?" })]));    const quoted = (await file.one("message", byExternal("wa:1")))!.id;    expect((await file.one("message", byExternal("wa:2")))!.data.reply_to_id).toBe(quoted);  });  it("reports what it still could not link so a truncated export says so", async () => {    const file = await TestFile.open();    const report = await file.import(batch([envelope("wa:2", { body: "yes", replyToExternalId: "wa:never-exported" })]));    expect(report.totals.unresolvedReplies).toBe(1);  });});// ── group import ────────────────────────────────────────────────────────────const cricket = (messages: EnvelopeMessage[], title: string): ImportBatch =>  batch(messages, { thread: groupBlock(title, "wa:group:cricket", [participant("Ravi", "919999000011"), participant("Priya", "919999000022")]) });describe("group import", () => {  it("creates the thread, its members, and attributes each sender", async () => {    const file = await TestFile.open();    const owner = anonymous("wa:3", "me", { direction: "out" });    const report = await file.import(cricket([fromLabel("wa:1", "Ravi"), fromLabel("wa:2", "Priya", { body: "hi" }), owner], "Cricket"));    expect(report.group!.threadCreated).toBe(true);    expect(report.group!.participantCount).toBe(2);    const [thread] = await file.rows("thread");    expect(thread!.data.kind).toBe("group");    expect(thread!.data.contact_id ?? null).toBeNull();    expect(thread!.data.title).toBe("Cricket");    expect(await file.count("thread_member")).toBe(2);    const senders = await file.column("message", "sender_participant_id", "external_id");    expect(senders[0]).not.toBeNull();    expect(senders[1]).not.toBeNull();    expect(senders[0]).not.toBe(senders[1]);    expect(senders[2]).toBeNull();    expect((await file.column("message", "sender_contact_id")).every((v) => v === null)).toBe(true);    const seats = (await file.rows("thread_member")).sort((a, b) => String(a.data.display_name).localeCompare(String(b.data.display_name)));    expect(seats[0]!.data.display_name).toBe("Priya");    expect(seats[0]!.data.contact_id).toBeTruthy();    expect(seats[1]!.data.display_name).toBe("Ravi");    expect(seats[1]!.data.contact_id).toBeTruthy();  });  it("finds the same group again by its key", async () => {    const file = await TestFile.open();    await file.import(cricket([fromLabel("wa:1", "Ravi")], "Cricket"));    const second = await file.import(cricket([fromLabel("wa:2", "Ravi", { body: "more" })], "Cricket"));    expect(second.group!.threadCreated).toBe(false);    expect(await file.count("thread")).toBe(1);  });  it("finds a renamed group by message overlap and inherits the new key", async () => {    const file = await TestFile.open();    await file.import(cricket([fromLabel("wa:1", "Ravi"), fromLabel("wa:2", "Priya", { body: "hi" })], "Cricket"));    const threadId = (await file.column("thread", "id"))[0];    await file.set("thread", "external_key", undefined);    const second = await file.import(      batch([fromLabel("wa:2", "Ravi", { body: "hi" }), fromLabel("wa:9", "Ravi", { body: "new" })], {        thread: groupBlock("Cricket 2026", "wa:group:cricket-2026", [participant("Ravi", "919999000011")]),      }),    );    expect(await file.count("thread")).toBe(1);    expect(second.group!.threadId).toBe(threadId);    expect(second.group!.threadCreated).toBe(false);    expect(await file.column("thread", "external_key")).toEqual(["wa:group:cricket-2026"]);  });  it("never clobbers a title the owner set", async () => {    const file = await TestFile.open();    await file.import(cricket([fromLabel("wa:1", "Ravi")], "Cricket"));    await file.set("thread", "title", "Sunday cricket");    await file.import(cricket([fromLabel("wa:2", "Ravi", { body: "x" })], "Cricket"));    expect(await file.column("thread", "title")).toEqual(["Sunday cricket"]);  });  it("keeps a member who left because they still said what they said", async () => {    const file = await TestFile.open();    await file.import(cricket([fromLabel("wa:1", "Ravi")], "Cricket"));    await file.import(batch([fromLabel("wa:2", "Ravi", { body: "x" })], { thread: groupBlock("Cricket", "wa:group:cricket", [participant("Ravi", "919999000011")]) }));    expect(await file.count("thread_member")).toBe(2);  });});// ── unidentified participants ───────────────────────────────────────────────const tf = (messages: EnvelopeMessage[], participants: EnvelopeThreadParticipant[]): ImportBatch => batch(messages, { thread: groupBlock("TF", "wa:group:tf", participants) });describe("unidentified participants", () => {  it("a label without a contact still gets a participant row", async () => {    const file = await TestFile.open();    await file.seedPerson("person-odo", "Odo Varnish");    await file.import(      tf([fromLabel("x1", "Wrenna"), fromLabel("x2", "Odo Varnish", { body: "yo" })], [participant("Wrenna"), participant("Odo Varnish", "910123462077", { personId: "person-odo" })]),    );    const seats = (await file.rows("thread_member")).sort((a, b) => String(a.data.display_name).localeCompare(String(b.data.display_name)));    expect(seats[0]!.data.display_name).toBe("Odo Varnish");    expect(seats[0]!.data.contact_id).toBeTruthy();    expect(seats[1]!.data.display_name).toBe("Wrenna");    expect(seats[1]!.data.contact_id ?? null).toBeNull();    expect((await file.column("message", "sender_participant_id")).every((v) => v !== null)).toBe(true);    expect(await file.column("message_contact", "person_id")).toEqual(["person-odo"]);  });  it("re-uses the participant row and identifies it when the label gains a number", async () => {    const file = await TestFile.open();    await file.import(tf([fromLabel("x1", "Wrenna")], [participant("Wrenna")]));    await file.import(tf([fromLabel("x1", "Wrenna")], [participant(" wrenna", "919999000099")]));    const seats = await file.rows("thread_member");    expect(seats).toHaveLength(1);    expect(seats[0]!.data.contact_id).toBeTruthy();  });});// ── a dm with an unidentified counterpart ───────────────────────────────────describe("a dm with an unidentified counterpart", () => {  it("an unidentified dm becomes a titled thread found again by overlap (the probe half not ported)", async () => {    const file = await TestFile.open();    const first = await file.import(batch([anonymous("d1", "hello")], { dm: participant("Asha") }));    expect(first.totals.inserted).toBe(1);    const [thread] = await file.rows("thread");    expect(thread!.data.kind).toBe("dm");    expect(thread!.data.contact_id ?? null).toBeNull();    expect(thread!.data.title).toBe("Asha");    expect(await file.count("message_contact")).toBe(0);    const both = [anonymous("d1", "hello"), anonymous("d2", "hi", { direction: "out" })];    await file.import(batch(both, { dm: participant("Asha (renamed)") }));    expect(await file.count("thread")).toBe(1);    expect(await file.count("message")).toBe(2);  });  it("one shared line does not fold a chat into a stranger's thread", async () => {    const file = await TestFile.open();    await file.import(batch(["a1", "a2", "a3", "a4"].map((id) => anonymous(id, id)), { dm: participant("Asha") }));    const priya = await file.import(batch(["a1", "p2", "p3", "p4", "p5"].map((id) => anonymous(id, id)), { dm: participant("Priya") }));    expect(priya.totals.inserted).toBe(5);    expect(priya.totals.skipped).toBe(0);    expect(await file.column("thread", "title", "title")).toEqual(["Asha", "Priya"]);    expect(await file.count("message")).toBe(9);  });  it("a part that overlaps nothing lands in the thread the caller resolved (the probe half not ported)", async () => {    const file = await TestFile.open();    await file.import(batch(["a1", "a2", "a3"].map((id) => anonymous(id, id)), { dm: participant("Asha") }));    const [thread] = await file.rows("thread");    const threadId = thread!.id;    const createdAt = thread!.created_at;    expect(createdAt).toBe(NOW);    await file.seedContact("c-asha", "919999000011", "Asha");    await file.set("thread", "contact_id", "c-asha");    const tail = ["a8", "a9"].map((id) => anonymous(id, id));    const written = await file.import(batch(tail, { dm: participant("Asha"), newThreadId: threadId }));    expect(written.totals.inserted).toBe(2);    expect(written.chats[0]!.threadId).toBe(threadId);    expect(written.chats[0]!.contactId).toBe("c-asha");    const after = await file.rows("thread");    expect(after).toHaveLength(1);    expect(after[0]!.id).toBe(threadId);    expect(after[0]!.data.contact_id).toBe("c-asha");    expect(after[0]!.created_at).toBe(createdAt);    expect(await file.column("message", "thread_id")).toEqual(Array(5).fill(threadId));  });  it("a dm block with a phone behaves like the phone-keyed path", async () => {    const file = await TestFile.open();    await file.seedPerson("person-asha", "Asha");    await file.import(batch([anonymous("d1", "hello")], { dm: participant("Asha", "919999000011", { personId: "person-asha" }) }));    const [contact] = await file.rows("message_contact");    expect(contact!.data.display_name).toBe("Asha");    expect(contact!.data.person_id).toBe("person-asha");    expect(await file.column("thread", "title")).toEqual([null]);  });  it("a number as the label never becomes a display name", async () => {    const file = await TestFile.open();    await file.import(batch([anonymous("d1", "hello")], { dm: participant("+91 99990 00011", "919999000011") }));    expect(await file.column("message_contact", "display_name")).toEqual([null]);  });});// ── imported reactions become rows ──────────────────────────────────────────const reaction = (emoji: string, actor: string, at?: string) => ({ emoji, actor, ...(at ? { at } : {}) });describe("imported reactions become rows", () => {  it("writes one reaction row per entry and leaves the column empty", async () => {    const file = await TestFile.open();    await file.import(      batch([        envelope("txt2:0123456789abcdef0123456789abcdef", {          body: "the tarpaulin arrived",          reactions: [reaction("❤️", "owner", "2021-03-04T09:01:00.000Z"), reaction("👍", "919999000011", "2021-03-04T09:02:00.000Z")],        }),      ]),    );    const [message] = await file.rows("message");    expect(message!.data.external_id).toBe("txt2:0123456789abcdef0123456789abcdef");    expect(message!.data.reactions).toEqual([]);    const messageId = message!.id;    const rows = (await file.rows("message_reaction")).sort((a, b) => (String(a.data.actor) < String(b.data.actor) ? -1 : 1));    expect(rows).toHaveLength(2);    expect(rows[0]!.id).toBe(`react:${messageId}:919999000011`);    expect(rows[0]!.data.emoji).toBe("👍");    expect(rows[0]!.created_at).toBe("2021-03-04T09:02:00.000Z");    expect(rows[1]!.id).toBe(`react:${messageId}:self`);    expect(rows[1]!.data.actor).toBe("self");    expect(rows[1]!.created_at).toBe("2021-03-04T09:01:00.000Z");  });  it("re-importing the same chat adds no second reaction row", async () => {    const file = await TestFile.open();    const again = batch([envelope("txt2:0123456789abcdef0123456789abcdef", { reactions: [reaction("❤️", "owner", "2021-03-04T09:01:00.000Z")] })]);    await file.import(again);    await file.import(again);    expect(await file.count("message")).toBe(1);    expect(await file.count("message_reaction")).toBe(1);  });  it("a reaction with no instant falls back to the message's own", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("txt2:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", { reactions: [reaction("❤️", "owner")] })]));    expect((await file.rows("message_reaction")).map((r) => r.created_at)).toEqual(["2021-03-04T09:00:00.000Z"]);  });  it("drops a reaction whose actor is not a phone rather than minting a broken id", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("txt2:ffffffffffffffffffffffffffffffff", { reactions: [reaction("❤️", "Some Name", "2021-03-04T09:01:00.000Z"), reaction("  ", "owner")] })]));    expect(await file.count("message_reaction")).toBe(0);    expect(await file.count("message")).toBe(1);  });});// ── any channel, and an email as an identity ────────────────────────────────describe("any channel, and an email as an identity", () => {  it("imports on every channel and stamps each row with the one it arrived on", async () => {    const file = await TestFile.open();    for (const channel of ["whatsapp", "imessage", "sms"]) {      const report = await file.import(batch([envelope(`${channel}:1`, { body: `hello over ${channel}` })], { channel }));      expect(report.totals.inserted, channel).toBe(1);    }    const rows = (await file.rows("message")).map((r) => [r.data.channel, r.data.origin]).sort();    expect(rows).toEqual([      ["imessage", "imported"],      ["sms", "imported"],      ["whatsapp", "imported"],    ]);  });  it("makes a contact for an email counterpart, not a nameless thread", async () => {    const file = await TestFile.open();    await file.import(      batch([anonymous("im:1", "on my way", { sentAt: "2026-09-05T09:00:00.000Z" })], { channel: "imessage", dm: participant("Ravi", undefined, { email: "Ravi@iCloud.com" }) }),    );    const [contact] = await file.rows("message_contact");    expect(contact!.data.phone_e164 ?? null).toBeNull();    expect(contact!.data.display_name).toBe("Ravi");    const [handle] = await file.rows("message_contact_handle");    expect(handle!.data).toMatchObject({ kind: "email", value: "ravi@icloud.com", contact_id: contact!.id });    const [thread] = await file.rows("thread");    expect(thread!.data.contact_id).toBe(contact!.id);    expect(thread!.data.title ?? null).toBeNull();  });  it("keeps the label-only path for a counterpart who named no handle", async () => {    const file = await TestFile.open();    await file.import(batch([anonymous("wa:label", "hello")], { dm: participant("Someone from the site") }));    const [thread] = await file.rows("thread");    expect(thread!.data.contact_id ?? null).toBeNull();    expect(thread!.data.title).toBe("Someone from the site");    expect(await file.count("message_contact")).toBe(0);  });  it("records both handles a counterpart named on one contact", async () => {    const file = await TestFile.open();    await file.import(batch([anonymous("im:2", "hi")], { channel: "imessage", dm: participant("Ravi", "919999000011", { email: "ravi@icloud.com" }) }));    expect(await file.count("message_contact")).toBe(1);    const seen = (await file.rows("message_contact_handle")).map((r) => [r.data.kind, r.data.value]).sort();    expect(seen).toEqual([      ["email", "ravi@icloud.com"],      ["phone", "919999000011"],    ]);  });  it("lets meta.source through untouched because provenance is the row's own", async () => {    const file = await TestFile.open();    const source = { service: "iMessage", device: "mac-a", externalId: "guid-1" };    await file.import(batch([envelope("im:3", { meta: { source } })], { channel: "imessage" }));    expect((await file.one("message", byExternal("im:3")))!.data.meta).toEqual({ source });  });});// ── the seams the TypeScript could not have ─────────────────────────────────describe("the seams", () => {  it("a batch naming no counterpart at all refuses in words", async () => {    const file = await TestFile.open();    const refused = await file.tryImport(batch([anonymous("d1", "hello")]));    expect(refused).toBeInstanceOf(EngineRefusal);    expect((refused as EngineRefusal).code).toBe("IMPORT_SHAPE");    expect(refused!.message).toBe("An imported message arrived with no usable phone or email and the batch names no counterpart");    expect(await file.count("message")).toBe(0);  });  it("a media entry rides into the column and names the preview", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("wa:pic", { body: "", media: [media(`${WORKSPACE}/messages/t/${"a".repeat(64)}.jpg`)] })]));    const [message] = await file.rows("message");    expect(message!.data.media).toHaveLength(1);    expect(await file.column("thread", "last_message_preview")).toEqual(["Photo"]);  });});// ── one WhatsApp message, one row, whichever door it came through ──────────/** An export line: no id, keyed by its content fingerprint. */const exported = (body: string, sentAt: string, occurrence: number, over: Partial<EnvelopeMessage> = {}): EnvelopeMessage =>  envelope(contentFingerprint(sentAt, body, occurrence)!, { body, sentAt, ...over });/** An export's caption-less media line: the placeholder body, the empty text it is fingerprinted by, `meta.attachment`. */const exportedMedia = (placeholder: string, name: string | null, sentAt: string, occurrence: number): EnvelopeMessage =>  envelope(contentFingerprint(sentAt, "", occurrence)!, { body: placeholder, sentAt, meta: { attachment: { omitted: name === null, ...(name !== null ? { name } : {}) } } });/** A linked-device message that is a picture (or other media) and no words. */const linkedMedia = (id: string, kind: string, body: string, sentAt: string, over: Partial<EnvelopeMessage> = {}): EnvelopeMessage =>  envelope(id, { body, sentAt, meta: { [MEDIA_ONLY_META]: kind }, ...over });describe("one WhatsApp message, one row", () => {  it("a message with its real id takes over the export row", async () => {    const file = await TestFile.open();    await file.import(batch([exported("on my way", "2021-03-04T09:00:00.000Z", 0), exported("on my way", "2021-03-04T09:00:00.000Z", 1), exported("later", "2021-03-04T09:05:00.000Z", 0)]));    const linked = (id: string, seconds: string) => envelope(id, { body: "on my way", sentAt: `2021-03-04T09:00:${seconds}.000Z` });    const report = await file.import(batch([linked("3EB0A", "12"), linked("3EB0B", "40")]));    expect(report.totals.inserted).toBe(2);    expect((await file.column("message", "external_id", "external_id")).map((id) => String(id).startsWith(CONTENT_EXTERNAL_ID_PREFIX))).toEqual([false, false, true]);    expect(await file.count("message")).toBe(3);    expect((await file.one("message", byExternal("3EB0B")))!.data.sent_at).toBe("2021-03-04T09:00:40.000Z");    const again = await file.import(batch([linked("3EB0A", "12")]));    expect(again.totals.inserted).toBe(0);  });  it("an export after the link writes only what the link lacks", async () => {    const file = await TestFile.open();    const linked = (id: string, body: string, seconds: string) => envelope(id, { body, sentAt: `2021-03-04T09:00:${seconds}.000Z` });    await file.import(batch([linked("3EB0A", "on my way", "12"), linked("3EB0B", "on my  way", "40")]));    const report = await file.import(      batch([        exported("on my way", "2021-03-04T09:00:00.000Z", 0),        exported("on my way", "2021-03-04T09:00:00.000Z", 1),        exported("on my way", "2021-03-04T09:00:00.000Z", 2),        exported("later", "2021-03-04T09:05:00.000Z", 0),      ]),    );    expect(report.totals.inserted).toBe(2);    expect(report.totals.skipped).toBe(2);    expect(await file.count("message")).toBe(4);  });  it("a picture with its real id takes over the export's media line", async () => {    const file = await TestFile.open();    await file.import(      batch([        exportedMedia("[image omitted]", null, "2021-03-04T09:00:00.000Z", 0),        exportedMedia("[attachment: VIDEO-2021-03-04-09-00-00.mp4]", "00000002-VIDEO-2021-03-04-09-00-00.mp4", "2021-03-04T09:00:00.000Z", 1),        exportedMedia("[<Media omitted>]", null, "2021-03-04T09:07:00.000Z", 0),      ]),    );    const report = await file.import(      batch([        linkedMedia("3EB0V", "video", "Video", "2021-03-04T09:00:30.000Z"),        linkedMedia("3EB0P", "image", "", "2021-03-04T09:00:10.000Z", { media: [media("ws/messages/t/abc.jpg")] }),        linkedMedia("3EB0S", "sticker", "Sticker", "2021-03-04T09:07:05.000Z"),        linkedMedia("3EB0Q", "image", "Photo", "2021-03-04T09:00:50.000Z"),      ]),    );    expect(report.totals.inserted).toBe(4);    expect(await file.count("message"), "three taken over, one new").toBe(4);    expect(await file.column("message", "external_id", "external_id")).toEqual(["3EB0P", "3EB0Q", "3EB0S", "3EB0V"]);    expect((await file.one("message", byExternal("3EB0V")))!.data.body, "the video took over the video line, not the image line").toBe("Video");    expect(JSON.stringify((await file.one("message", byExternal("3EB0P")))!.data.media)).toContain("abc.jpg");    const again = await file.import(batch([linkedMedia("3EB0P", "image", "Photo", "2021-03-04T09:00:10.000Z")]));    expect(again.totals.inserted).toBe(0);  });  it("a picture leaves another side's or kind's media line alone", async () => {    const file = await TestFile.open();    const mine = { ...exportedMedia("[image omitted]", null, "2021-03-04T09:00:00.000Z", 0), direction: "out" as const };    const captioned = exported("look at this", "2021-03-04T09:00:00.000Z", 0, { meta: exportedMedia("[image omitted]", null, "2021-03-04T09:00:00.000Z", 0).meta! });    await file.import(batch([mine, exportedMedia("[audio omitted]", null, "2021-03-04T09:00:00.000Z", 1), captioned]));    await file.import(batch([linkedMedia("3EB0P", "image", "Photo", "2021-03-04T09:00:20.000Z")]));    expect(await file.count("message"), "nothing was taken over").toBe(4);  });  it("an export after the link skips the pictures it already holds", async () => {    const file = await TestFile.open();    await file.import(batch([linkedMedia("3EB0P", "image", "Photo", "2021-03-04T09:00:10.000Z"), linkedMedia("3EB0A", "voice", "Voice message", "2021-03-04T09:00:20.000Z")]));    const report = await file.import(      batch([        exportedMedia("[image omitted]", null, "2021-03-04T09:00:00.000Z", 0),        exportedMedia("[audio omitted]", null, "2021-03-04T09:00:00.000Z", 1),        exportedMedia("[image omitted]", null, "2021-03-04T09:00:00.000Z", 2),      ]),    );    expect(report.totals.inserted).toBe(1);    expect(await file.count("message")).toBe(3);  });  it("a group is one thread whether the export or the link came first", async () => {    const jid = "wa:group:120363000000000001@g.us";    let file = await TestFile.open();    await file.import(batch([fromLabel("txt2:aaaa", "Asha")], { thread: groupBlock("Weekend Plans", groupExternalKey("Weekend Plans"), [participant("Asha")]) }));    await file.import(batch([fromLabel("3EB0C", "Asha")], { thread: groupBlock("Weekend Plans", jid, [participant("Asha", "15550001111")]) }));    expect(await file.column("thread", "external_key")).toEqual([jid]);    expect(await file.count("message")).toBe(2);    file = await TestFile.open();    await file.import(batch([fromLabel("3EB0C", "Asha")], { thread: groupBlock("Weekend Plans", jid, [participant("Asha", "15550001111")]) }));    await file.import(batch([fromLabel("txt2:aaaa", "Asha")], { thread: groupBlock("Weekend plans", groupExternalKey("Weekend plans"), [participant("Asha")]) }));    expect(await file.count("thread")).toBe(1);    expect(await file.column("thread", "external_key")).toEqual([jid]);  });  it("an export never guesses between two groups with one title", async () => {    const file = await TestFile.open();    for (const [n, jid] of ["120363000000000001@g.us", "120363000000000002@g.us"].entries()) {      await file.import(batch([fromLabel(`3EB0${n}`, "Asha")], { thread: groupBlock("Family", `wa:group:${jid}`, [participant("Asha")]) }));    }    await file.import(batch([fromLabel("txt2:bbbb", "Asha")], { thread: groupBlock("Family", groupExternalKey("Family"), [participant("Asha")]) }));    expect(await file.count("thread")).toBe(3);  });});// ── changes to messages already held ────────────────────────────────────────describe("changes to messages already held", () => {  it("changes land on the message their id names", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("D1"), envelope("D2")]));    const thread = (await file.one("message", byExternal("D1")))!.data.thread_id;    const at = "2021-03-04T10:00:00.000Z";    const report = await file.messageChanges("whatsapp", [      { kind: "edit", externalId: "D1", body: "hello again", at },      { kind: "reaction", externalId: "D1", actor: "919999000011", emoji: "👍", at },      { kind: "reaction", externalId: "D1", actor: "owner", emoji: "❤️", at },      { kind: "revoke", externalId: "D2", at },      { kind: "edit", externalId: "NOT-HERE", body: "x", at },    ]);    expect(report).toEqual({ edited: 1, revoked: 1, reacted: 2, unreacted: 0, voted: 0, missing: 1 });    const d1 = (await file.one("message", byExternal("D1")))!;    expect(d1.data.body).toBe("hello again");    expect(d1.data.edited_at).toBe(at);    const d2 = (await file.one("message", byExternal("D2")))!;    expect(d2.data.body).toBe("");    expect(d2.data.deleted_at).toBe(at);    expect(await file.count("message"), "no change becomes a message").toBe(2);    expect(await file.count("message_reaction")).toBe(2);    expect([...new Set(await file.column("message_reaction", "thread_id"))]).toEqual([thread]);    const off = await file.messageChanges("whatsapp", [{ kind: "reaction", externalId: "D1", actor: "owner", emoji: "", at }]);    expect(off.unreacted).toBe(1);    expect(await file.count("message_reaction")).toBe(1);  });  it("the change lookup uses the external id index", async () => {    const file = await TestFile.open();    const detail = await file.within((o) =>      o.store        .query<{ detail: string }>(`EXPLAIN QUERY PLAN ${MESSAGE_BY_EXTERNAL_ID_SQL}`, "ABC", "whatsapp")        .map((r) => r.detail)        .join(" | "),    );    expect(detail, `the change lookup does not use the external id index: ${detail}`).toContain("USING INDEX rows_message_external");  });  it("the thread line follows an edit or revoke of its newest message", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("OLD", { body: "first" }), envelope("NEW", { body: "last", sentAt: "2021-03-04T09:05:00.000Z" })]));    const line = async () => (await file.column("thread", "last_message_preview"))[0];    expect(await line()).toBe("last");    const at = "2021-03-04T10:00:00.000Z";    await file.messageChanges("whatsapp", [{ kind: "edit", externalId: "OLD", body: "first, fixed", at }]);    expect(await line(), "an older message's edit is not the thread's line").toBe("last");    await file.messageChanges("whatsapp", [{ kind: "edit", externalId: "NEW", body: "last, fixed", at }]);    expect(await line()).toBe("last, fixed");    await file.messageChanges("whatsapp", [{ kind: "revoke", externalId: "NEW", at }]);    expect(await line()).toBe("This message was deleted");    expect((await file.column("thread", "last_message_at"))[0], "the thread does not move").toBe("2021-03-04T09:05:00.000Z");  });  it("a held message without its picture takes the backup's picture on the same row", async () => {    const file = await TestFile.open();    await file.import(batch([linkedMedia("3EB0P", "image", "Photo", "2021-03-04T09:00:00.000Z")]));    const idBefore = (await file.column("message", "id"))[0];    const fromBackup = envelope("3EB0P", { body: "", sentAt: "2021-03-04T09:00:00.000Z", meta: { [MEDIA_ONLY_META]: "image" }, media: [media("ws/messages/t/abc.jpg", { sizeBytes: 12 })] });    const report = await file.import(batch([fromBackup]));    expect(report.totals.inserted, "the held row took its picture").toBe(1);    const rows = await file.rows("message");    expect(rows, "one message, one row").toHaveLength(1);    expect(rows[0]!.id, "the same row").toBe(idBefore);    expect(rows[0]!.data.media).toHaveLength(1);    expect(rows[0]!.data.body).toBe("");    const again = await file.import(batch([fromBackup]));    expect(again.totals.inserted, "a row that holds media is never touched").toBe(0);  });});// ── site handles ────────────────────────────────────────────────────────────describe("site handles", () => {  it("site handles keep same-named speakers separate", async () => {    const file = await TestFile.open();    const ig = {      workspaceId: WORKSPACE,      channel: "instagram",      newThreadId: RESERVED,      thread: {        kind: "group",        title: "Invented group",        externalKey: "ig:thread:1122",        participants: [          { label: "Invented Speaker", handle: { kind: "instagram", value: "@first.invented" } },          { label: "Invented Speaker", handle: { kind: "instagram", value: "second.invented" } },        ],      },      messages: [        { direction: "in", senderLabel: "Invented Speaker", body: "First speaker", sentAt: NOW, externalId: "ig:111", meta: { source: { senderHandle: { kind: "instagram", value: "first.invented" } } } },        { direction: "in", senderLabel: "Invented Speaker", body: "Second speaker", sentAt: NOW, externalId: "ig:222", meta: { source: { senderHandle: { kind: "instagram", value: "second.invented" } } } },      ],    } as ImportBatch;    expect((await file.import(ig)).totals.inserted).toBe(2);    const handleOf = async (externalId: string): Promise<unknown> => {      const m = (await file.one("message", byExternal(externalId)))!;      const seat = (await file.one("thread_member", (r) => r.id === m.data.sender_participant_id))!;      return (await file.one("message_contact_handle", (r) => r.data.contact_id === seat.data.contact_id && r.data.kind === "instagram"))!.data.value;    };    expect(await handleOf("ig:111")).toBe("first.invented");    expect(await handleOf("ig:222")).toBe("second.invented");    expect((await file.import(ig)).totals.inserted).toBe(0);    expect((await file.rows("thread_member")).filter((r) => r.data.thread_id === RESERVED)).toHaveLength(2);    expect(new Set((await file.rows("message")).filter((r) => r.data.thread_id === RESERVED).map((r) => r.data.sender_participant_id)).size).toBe(2);  });});// ── the owner's region ──────────────────────────────────────────────────────describe("the owner's region", () => {  it("a code-less incoming number is read in the owner's country", async () => {    const file = await TestFile.open();    file.ownerPhone = "919876543210";    await file.seedPerson("person-ravi", "Ravi");    await file.seedPhone("handle-ravi", "person-ravi", "919812345678");    const report = await file.import(batch([envelope("wa:region", { phone: "098123 45678" })]));    expect(report.chats[0]!.phone).toBe("919812345678");    expect(await file.column("message_contact", "phone_e164")).toEqual(["919812345678"]);    expect(await file.column("message_contact", "person_id")).toEqual(["person-ravi"]);  });  it("with no owner number a code-less incoming number stays as typed", async () => {    const file = await TestFile.open();    await file.import(batch([envelope("wa:plain", { phone: "098123 45678" })]));    expect(await file.column("message_contact", "phone_e164")).toEqual(["09812345678"]);  });});