From bde7ecf2bdf12fe70a097ccd81b8fb8e2e33fdd6 Mon Sep 17 00:00:00 2001 From: Jason Alexander Date: Thu, 12 Nov 2026 17:39:29 -0700 Subject: [PATCH 1/2] fix(send): a DM sends on what its own messages say, not the chat label The Mac still labelled one RCS contact's chat as iMessage, so Blip sent every message to them as iMessage, and every one failed with error 22. Another contact's chat was labelled SMS, so they got plain SMS, which the Mac logged as error 4 (Not Delivered). The iPhone delivered those anyway: each row had the contact's read receipt 1 to 6 seconds later. Found on a macOS 27.2 gateway, 2026-11-12. `imsg chats` reports the chat row's service_name. With one row per conversation, that label follows the Mac's own last send, Blip's included. So letting it override the window's evidence loops. #97, #147 and #151 each guarded one direction of that loop. The rule "only when the newest row is inbound" did not hold either, because the label is not the newest row's service. - mergeChats keeps sendServiceForMessages' answer for every DM the window has rows for. The label names only quiet DMs. - thread.ts reports `service` from the opened conversation's own rows. BlipView prefers it for text and file sends, through the new SendState.sendServiceArg (built into SendState.mjs). - After a failed iMessage to a phone, the next send goes the way they last texted us when that was RCS or SMS. Otherwise it is SMS, as before. - sendFailed(): a read receipt outranks message.error. This applies to the bubble, the receipt line, the failure toast and the service rules. Invariant added to CLAUDE.md. All 892 tests pass. Each change was checked by mutation: undoing it makes its tests fail. Not yet run: a live send to an RCS contact through the Mac's RCS service. Co-Authored-By: Claude Opus 5.5 --- BlipView.qml | 20 +++++++++--- CLAUDE.md | 10 ++++++ README.md | 3 +- SendState.mjs | 9 +++++- collector.test.ts | 58 ++++++++++++++++++++++++++++++++-- collector.ts | 78 +++++++++++++++++++++++++++------------------- send-state.test.ts | 29 ++++++++++++++++- send-state.ts | 18 +++++++++++ thread.test.ts | 42 +++++++++++++++++++++++++ thread.ts | 21 +++++++++++-- ui.test.ts | 20 ++++++++++++ 11 files changed, 263 insertions(+), 45 deletions(-) diff --git a/BlipView.qml b/BlipView.qml index 35c5008c..c503072f 100644 --- a/BlipView.qml +++ b/BlipView.qml @@ -456,6 +456,12 @@ FocusScope { // root.active can change under a multi-part send, and a later part must not // go out on a different service from the first (war room #2). property string sendService: "" + // What the open conversation's own rows say to send on (thread.ts `service`) + // and the chat they were loaded for. SendState.sendServiceArg prefers it over + // the list row's service, which is the Mac's chat label and goes stale when a + // contact moves to Android. + property string threadSendService: "" + property string threadSendServiceChat: "" // Sends the Mac has not written a row for yet, {chat, text, ts}. Every // thread reload carries them to thread.ts (--pending-stdin, never argv), // which keeps their bubbles until the real row lands. Memory only. @@ -1704,8 +1710,8 @@ FocusScope { // strictly one at a time — pumpFileSend() starts the next as each lands. root.fileQueue = root.attachDrafts.map(function(d) { return d.path }) root.sendCaption = trimmed - var svc = String(root.active.service || "") - root.sendService = /^(SMS|RCS)$/i.test(svc) ? svc.toUpperCase() : "" + root.sendService = SendState.sendServiceArg(root.sendChat, root.activeIsGroup, + String(root.active.service || ""), root.threadSendServiceChat, root.threadSendService) pumpFileSend() return } @@ -1718,9 +1724,11 @@ FocusScope { var target = root.activeIsGroup ? ["--chat-id", String(root.active.guid)] : ["--to", chat] - // green-bubble (SMS/RCS) threads send on their own service (war room #2) - var svc = String(root.active.service || "") - if (!root.activeIsGroup && /^(SMS|RCS)$/i.test(svc)) target = target.concat(["--service", svc.toUpperCase()]) + // green-bubble (SMS/RCS) threads send on their own service (war room #2), + // read from the conversation's own rows once they have loaded + var svc = SendState.sendServiceArg(chat, root.activeIsGroup, + String(root.active.service || ""), root.threadSendServiceChat, root.threadSendService) + if (svc !== "") target = target.concat(["--service", svc]) var localId = String(++root.nextSendId) root.pendingRevision++ root.pendingSends = root.pendingSends.concat([{ chat: chat, text: text, ts: stamp, localId: localId }]) @@ -1901,6 +1909,8 @@ FocusScope { var d = JSON.parse(text.trim()) if (d.ok === true) { var list = Array.isArray(d.bubbles) ? d.bubbles : [] + root.threadSendServiceChat = root.threadRunningChat + root.threadSendService = String(d.service || "") root.pendingTapback = TapbackActions.pendingAfterLoad(root.pendingTapback, root.threadRunningChat, list, root.threadTapbackDone) // the tool is done but chat.db does not show it yet (a self-thread's echo lags): look again if (root.threadTapbackDone && root.pendingTapback && root.pendingTapback.chat === root.threadRunningChat) { diff --git a/CLAUDE.md b/CLAUDE.md index 5b612567..bbecab4a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,6 +118,16 @@ what it is handed. Keep it that way. bubble until a real from-me row with the same text lands, resolving one send per row. The read watermark (`--seen`) skips pending bubbles: their ts is THIS machine's clock. A failed send retains its bubble with a failure reason in memory. Never go back to "wait 1.5 s, then reload". +- **A DM sends on what its own messages say, never on the Mac's chat label.** `imsg chats` reports the + chat row's `service_name`. On macOS 26 and later, one row holds the whole conversation, and that label + follows the Mac's OWN last send, Blip's included, so trusting it loops. On 2026-11-12, a contact + texting on RCS stayed labelled iMessage and every send failed with error 22. Another stayed labelled SMS + and got plain SMS. `sendServiceForMessages` decides from rows in two places. In the collector it reads + the preview window: `mergeChats` keeps that answer for every DM the window has rows for, and the label + names only quiet ones. In `thread.ts` it reads the opened conversation and reports it as `service`, + which BlipView prefers through `SendState.sendServiceArg`. #97, #147 and #151 each guarded one + direction of this same loop. A read receipt outranks `error` (`sendFailed`). The Mac logs error 4 on + plain SMS it relays to an RCS contact, and the iPhone delivers it anyway. - **A Mac that is signed out READS fine and cannot SEND.** Reads are sqlite over ssh and need no login; a send needs Messages, and Launch Services starts an app only inside a GUI session, so at the login window every send dies with -10810 (`friendlySendError` says it in plain words). `imsg session` is the read-only probe diff --git a/README.md b/README.md index 5b475d42..79f37ad2 100644 --- a/README.md +++ b/README.md @@ -521,7 +521,8 @@ prefer_imessage=on A thread with a successful iMessage in the loaded window then stays iMessage. A never-iMessage RCS/SMS thread stays green. A failed iMessage to -a phone still flips to SMS so the send does not stick. Groups are unchanged +a phone still flips the next send to RCS, if that is how they last texted +you, or to SMS, so the send does not stick. Groups are unchanged (they send by chat id). Default is off. **Tapbacks (experimental).** Right-click a message, or select it diff --git a/SendState.mjs b/SendState.mjs index 62e3779c..ea3f30c6 100644 --- a/SendState.mjs +++ b/SendState.mjs @@ -4,10 +4,17 @@ function markSendFailed(items, id, reason, fallback) { const current = fallback && !items.some((item) => item.localId === id) ? items.concat([fallback]) : items; return current.map((item) => item.localId === id ? Object.assign({}, item, { failed: true, failureReason: safeReason }) : item); } +function sendServiceArg(chat, group, listService, loadedChat, loadedService) { + if (group) + return ""; + const svc = loadedChat === chat && loadedService !== "" ? loadedService : listService; + return /^(SMS|RCS)$/i.test(svc) ? svc.toUpperCase() : ""; +} function friendlySendError(raw) { return /(^|[^\d])-10810(\D|$)/.test(raw) ? "Messages can't start on the Mac: nobody is logged in there. Log in on the Mac, then send again." : raw; } export { friendlySendError, - markSendFailed + markSendFailed, + sendServiceArg }; diff --git a/collector.test.ts b/collector.test.ts index bf157636..65336a45 100644 --- a/collector.test.ts +++ b/collector.test.ts @@ -1280,6 +1280,11 @@ describe("failed-delivery detection", () => { expect(selectFailures([mine({ error: 25, ts: "2026-08-31T19:00:00Z" })], [], now).length).toBe(0); }); + test("a row the recipient has read is no failure, whatever error the Mac logged", () => { + expect(selectFailures([mine({ service: "SMS", error: 4, read_at: "2026-08-31T20:25:06Z" })], [], now).length).toBe(0); + expect(selectFailures([mine({ service: "SMS", error: 4 })], [], now).length).toBe(1); + }); + test("dedupes through the toasted ring — interrupts exactly once", () => { const first = selectFailures([mine({ error: 25 })], [], now); const again = selectFailures([mine({ error: 25 })], first.map((f) => f.key), now); @@ -1517,9 +1522,32 @@ describe("complete conversation list (mergeChats)", () => { expect(mergeChats([green], [chats[2]!], {}, {})[0]!.service).toBe("SMS"); }); - test("the list may still move a DM the other way, onto iMessage", () => { + // Live shapes (2026-11-12, a macOS 27.2 gateway). Two Android contacts, both + // texting on RCS, so the window says RCS. One chat row's label said + // iMessage, so with their reply the newest row, every send went out as + // iMessage and failed with error 22. The other's label said SMS, so every + // send went out as plain SMS, which the Mac logged as error 4. The label + // follows the Mac's own last send, so it never corrected itself. + test("an RCS contact whose chat row still says iMessage is sent RCS", () => { + const rcs = { ...windowThread, service: "RCS" }; + const label = { ...chats[0]!, service: "iMessage", last_from_me: false }; + expect(mergeChats([rcs], [label], {}, {})[0]!.service).toBe("RCS"); + }); + + test("an RCS contact whose chat row says SMS is sent RCS", () => { + const rcs = { ...windowThread, service: "RCS" }; + const label = { ...chats[0]!, service: "SMS" }; + expect(mergeChats([rcs], [label], {}, {})[0]!.service).toBe("RCS"); + }); + + test("the label cannot move a DM with rows onto iMessage either", () => { const green = { ...windowThread, service: "SMS" }; - expect(mergeChats([green], [chats[0]!], {}, {})[0]!.service).toBe("iMessage"); + expect(mergeChats([green], [chats[0]!], {}, {})[0]!.service).toBe("SMS"); + }); + + test("a quiet DM the window has no rows for still takes the list's service", () => { + const out = mergeChats([windowThread], chats, {}, {}); + expect(out.find((t) => t.chat === "+15559990000")!.service).toBe("SMS"); }); // Live shape: a contact who moved from iPhone to Android, every recent @@ -1825,6 +1853,32 @@ describe("which service a DM sends on (@lukejmorrison, PR #4)", () => { ])).toBe("iMessage"); }); + test("after a failed iMessage, a contact who texts us on RCS is sent RCS, not SMS", () => { + // SMS to an RCS contact is what the Mac logged error 4 on (2026-11-12) + expect(sendServiceForMessages([ + at(0, { from_me: false, service: "RCS" }), + at(1, { from_me: true, service: "iMessage", error: 22 }), + ])).toBe("RCS"); + expect(sendServiceForMessages([ + at(0, { from_me: false, service: "SMS" }), + at(1, { from_me: true, service: "iMessage", error: 22 }), + ])).toBe("SMS"); + }); + + test("a sent row with a read receipt is not a failure, whatever error the Mac logged", () => { + const { sendFailed } = require("./collector") as typeof import("./collector"); + expect(sendFailed(at(0, { from_me: true, service: "SMS", error: 4 }))).toBe(true); + expect(sendFailed(at(0, { from_me: true, service: "SMS", error: 4, read_at: "2026-09-03T10:00:06Z" }))).toBe(false); + expect(sendFailed(at(0, { from_me: true, service: "SMS", error: 0 }))).toBe(false); + expect(sendFailed(at(0, { from_me: true, service: "SMS" }))).toBe(false); + expect(sendFailed(at(0, { from_me: false, service: "SMS", error: 4 }))).toBe(false); + // a read iMessage was delivered, so it is no sign they left iMessage + expect(sendServiceForMessages([ + at(0, { from_me: false, service: "iMessage" }), + at(1, { from_me: true, service: "iMessage", error: 22, read_at: "2026-09-03T11:00:05Z" }), + ])).toBe("iMessage"); + }); + test("our failed iMessage to a phone, newest, means they are not on iMessage", () => { // the case that made a thread stick: retrying iMessage forever expect(sendServiceForMessages([ diff --git a/collector.ts b/collector.ts index e90cd53b..627a2ac5 100644 --- a/collector.ts +++ b/collector.ts @@ -654,6 +654,20 @@ export function groupName(chat: string, info: GroupInfo | undefined, byHandle: M export type SendService = "iMessage" | "SMS" | "RCS"; +/** + * One of OUR rows that did not get through. chat.db's `error` is the Mac's + * verdict, and for a text the iPhone relays it can be wrong: an SMS the Mac + * hands over for a contact on RCS is often logged error 4 while the iPhone + * delivers it as RCS. On 2026-11-12 every such row carried the recipient's read + * receipt 1 to 6 seconds after it was sent. A read receipt is the recipient's + * own device saying the message arrived, so it outranks the error. Carrier SMS + * has no receipts, so this clears only a row that provably got through. + * `read_at` comes with `--rich` fetches; a plain fetch keeps the old rule. + */ +export function sendFailed(m: ImsgMessage): boolean { + return m.from_me === true && typeof m.error === "number" && m.error !== 0 && !m.read_at; +} + /** Map a chat.db service string onto what `imsg-send --service` accepts. */ export function normalizeSendService(raw: string | undefined | null): SendService { const s = String(raw ?? "").trim().toLowerCase(); @@ -672,8 +686,11 @@ export function normalizeSendService(raw: string | undefined | null): SendServic * * Order matters: * 1. the newest row is a FAILED iMessage of ours to a phone → they are not - * on iMessage; send SMS. (AppleScript does not fall back the way the - * Messages GUI does — the send just dies with error 22.) + * on iMessage. Send the way they last texted us when that was RCS or + * SMS, otherwise SMS. (AppleScript does not fall back the way the + * Messages GUI does — the send just dies with error 22.) An Android + * contact on RCS sent plain SMS is often logged error 4, even though the + * iPhone delivers it as RCS (2026-11-12). * 2. `prefer_imessage=on` in bridge.conf: a successful iMessage anywhere in * the loaded window (in or out) → iMessage. Last-inbound RCS/SMS in a * mixed 1:1 otherwise makes the next send green, and the Mac records SMS @@ -687,25 +704,27 @@ export function normalizeSendService(raw: string | undefined | null): SendServic export function sendServiceForMessages(msgs: ImsgMessage[], preferImessage = false): SendService { if (!msgs.length) return "iMessage"; const sorted = [...msgs].sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0)); - const failed = (m: ImsgMessage) => typeof m.error === "number" && m.error !== 0; + let lastInbound: ImsgMessage | undefined; + for (let i = sorted.length - 1; i >= 0 && !lastInbound; i--) { + if (!sorted[i]!.from_me) lastInbound = sorted[i]; + } const newest = sorted[sorted.length - 1]!; const chat = chatKey(newest); - if (newest.from_me && failed(newest) + if (newest.from_me && sendFailed(newest) && normalizeSendService(newest.service) === "iMessage" && /^\+?[0-9]{3,15}$/.test(chat)) { - return "SMS"; + const theirs = lastInbound ? normalizeSendService(lastInbound.service) : "iMessage"; + return theirs === "iMessage" ? "SMS" : theirs; } if (preferImessage) { for (const m of sorted) { - if (!failed(m) && normalizeSendService(m.service) === "iMessage") return "iMessage"; + if (!sendFailed(m) && normalizeSendService(m.service) === "iMessage") return "iMessage"; } } + if (lastInbound) return normalizeSendService(lastInbound.service); for (let i = sorted.length - 1; i >= 0; i--) { - if (!sorted[i]!.from_me) return normalizeSendService(sorted[i]!.service); - } - for (let i = sorted.length - 1; i >= 0; i--) { - if (!failed(sorted[i]!)) return normalizeSendService(sorted[i]!.service); + if (!sendFailed(sorted[i]!)) return normalizeSendService(sorted[i]!.service); } return "iMessage"; } @@ -1338,7 +1357,7 @@ export function selectFailures( const out: Toast[] = []; const cutoff = nowTs(new Date(Date.parse(now) - FAILURE_TOAST_WINDOW_MS)); for (const m of msgs) { - if (!m.from_me || typeof m.error !== "number" || m.error === 0) continue; + if (!sendFailed(m)) continue; if (m.ts < cutoff) continue; const key = "fail:" + toastKey(m); if (seen.has(key)) continue; @@ -2183,27 +2202,22 @@ export function mergeChats( const knownParticipantNames = new Map( (thread.participants ?? []).map((person) => [person.handle, person.name]), ); - // The window's rule (PR #4) reads the last INBOUND row: the service the - // other person's device actually used. `imsg chats` reports the CLUSTER's - // newest row instead — Blip's own sends included, and for a merged 1:1 - // (an email iMessage row and a phone SMS row under one group_id) the phone - // alias counts too. Letting that turn a blue DM green is self-reinforcing: - // one green send becomes the list row's service, which makes the next send - // green, and the conversation never comes back on its own. Refuse that one - // direction; the list still names the service everywhere else. (#97, Ian) - // The opposite direction loops just the same: one failed iMessage (error - // 22) to an SMS-only number becomes the cluster's newest row, the list - // calls the DM blue, and every later send fails as iMessage too. - // So the list may only move a green DM onto iMessage when its newest row - // is INBOUND: they reached us on iMessage. Our own send proves nothing. + // A DM the window has rows for sends on what those rows say: PR #4's + // rule, which reads the service the other person's device last used + // (`sendServiceForMessages`). `imsg chats` reports the chat row's + // `service_name`. That is a label, not a message. On a Mac where one chat + // row holds every service, it follows the Mac's OWN last send, Blip's + // included, so trusting it loops. One green send kept a blue DM green + // (#97, #147). One failed iMessage (error 22) kept an Android contact on + // iMessage (#151). The rule "only when the newest row is inbound" did not + // hold either, because the label is not the newest row's service. A + // contact texting on RCS stayed labelled iMessage, and every send failed + // with error 22. Another stayed labelled SMS and got plain SMS, logged + // error 4 (2026-11-12). The label now names a DM only when the window has + // no rows for it (the quiet rows below), and BlipView replaces even that + // with the opened conversation's own rows (thread.ts `service`). A group + // sends by chat id, so the label stays its name. const listService = info.service || thread.service; - const greenDowngrade = !group - && normalizeSendService(thread.service) === "iMessage" - && normalizeSendService(listService) !== "iMessage"; - const blueUpgrade = !group - && normalizeSendService(thread.service) !== "iMessage" - && normalizeSendService(listService) === "iMessage" - && info.last_from_me === true; return { ...thread, aliases, @@ -2215,7 +2229,7 @@ export function mergeChats( ? groupName(thread.chat, groupInfo, knownParticipantNames) : namedGroup(thread.name, thread.chat, aliases) || thread.chat)) : (info.last_name || info.name || thread.name || thread.chat), - service: greenDowngrade || blueUpgrade ? thread.service : listService, + service: group ? listService : thread.service, last_text: info.last === thread.last_ts ? info.last_text : messagePreview(thread.last_text), pinned, pin_order, diff --git a/send-state.test.ts b/send-state.test.ts index 67601a3c..80290006 100644 --- a/send-state.test.ts +++ b/send-state.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { markSendFailed, friendlySendError } from "./send-state"; +import { markSendFailed, friendlySendError, sendServiceArg } from "./send-state"; import { pendingBubble, withPendingSends, DEFAULT_FORMATS } from "./thread"; test("failure targets one of two sends in the same second and keeps the original immutable", () => { @@ -111,3 +111,30 @@ test("a failed attempt of OTHER words is untouched by a delivered retry of diffe [failedSend("1", "hello", "2026-11-10 12:40:00"), keep], "2026-11-10", DEFAULT_FORMATS, Date.parse("2026-11-10T12:50:00")); expect(out.pending).toEqual([keep]); }); + +// 2026-11-12: a contact texting on RCS whose chat row was still labelled iMessage. Every send left as +// iMessage and failed with error 22, because the send read the list row's service (the Mac's label). +test("a send uses the opened conversation's own service over the list label", () => { + const chat = "+15551234567"; + expect(sendServiceArg(chat, false, "iMessage", chat, "RCS")).toBe("RCS"); + expect(sendServiceArg(chat, false, "SMS", chat, "RCS")).toBe("RCS"); + expect(sendServiceArg(chat, false, "RCS", chat, "iMessage")).toBe(""); + // rows loaded for ANOTHER conversation never decide this one + expect(sendServiceArg(chat, false, "SMS", "+15550000000", "RCS")).toBe("SMS"); + // before the rows load, the list row is all there is + expect(sendServiceArg(chat, false, "sms", chat, "")).toBe("SMS"); + expect(sendServiceArg(chat, false, "iMessage", "", "")).toBe(""); +}); + +test("a group never carries --service: it sends by chat id", () => { + const id = "abcdef0123456789abcdef0123456789"; + expect(sendServiceArg(id, true, "RCS", id, "RCS")).toBe(""); +}); + +test("the deployed QML module picks the same service as the TypeScript", async () => { + const runtime = await import("./SendState.mjs"); + for (const args of [ + ["+1", false, "iMessage", "+1", "RCS"], ["+1", false, "SMS", "+2", "RCS"], + ["+1", true, "SMS", "+1", "SMS"], ["+1", false, "rcs", "", ""], + ] as const) expect(runtime.sendServiceArg(...args)).toBe(sendServiceArg(...args)); +}); diff --git a/send-state.ts b/send-state.ts index 0b31e8ef..5a38e1a3 100644 --- a/send-state.ts +++ b/send-state.ts @@ -14,6 +14,24 @@ export function markSendFailed(items: T[], id: string, reas ? Object.assign({}, item, { failed: true, failureReason: safeReason }) : item); } +/** The `--service` a send in this conversation carries, or "" for none: iMessage + * is imsg-send's default, and a group sends by chat id and never carries one. + * The opened conversation's own rows (thread.ts `service`, kept with the chat + * they were loaded for) outrank the list row's service. That is the Mac's chat + * label, which follows the Mac's own last send and stayed "iMessage" for a + * contact texting on RCS, so every send failed with error 22 (2026-11-12). */ +export function sendServiceArg( + chat: string, + group: boolean, + listService: string, + loadedChat: string, + loadedService: string, +): string { + if (group) return ""; + const svc = loadedChat === chat && loadedService !== "" ? loadedService : listService; + return /^(SMS|RCS)$/i.test(svc) ? svc.toUpperCase() : ""; +} + /** Say what a send failure MEANS when the Mac's own words are only a number. * -10810 is Launch Services failing to start Messages for `tell application "Messages"`; seen * 2026-11-10 when the gateway's WindowServer died and loginwindow logged the user out, which leaves no diff --git a/thread.test.ts b/thread.test.ts index 851b2314..4ceb5601 100644 --- a/thread.test.ts +++ b/thread.test.ts @@ -396,6 +396,27 @@ describe("loadThread", () => { expect(r.ok).toBe(false); expect(r.error).toBe("nope"); }); + + // 2026-11-12: a contact texting on RCS whose chat row still said iMessage. + // The conversation's own rows are the evidence the send path needs. + test("a DM reports the service its own rows say to send on", () => { + const rows = [ + msg({ ts: "2026-08-30T12:00:00Z", service: "RCS" }), + msg({ ts: "2026-08-30T12:01:00Z", from_me: true, service: "iMessage", error: 22 }), + ]; + const r = loadThread("+15551234567", 10, "2026-08-30", DEFAULT_FORMATS, + fake({ status: 0, stdout: JSON.stringify(rows) }), false); + expect(r.ok).toBe(true); + expect(r.service).toBe("RCS"); + }); + + test("a group reports no service: it sends by chat id", () => { + const id = "abcdef0123456789abcdef0123456789"; + const r = loadThread(id, 10, "2026-08-30", DEFAULT_FORMATS, + fake({ status: 0, stdout: JSON.stringify([msg({ chat: id, service: "RCS" })]) }), false); + expect(r.ok).toBe(true); + expect(r.service).toBeUndefined(); + }); }); describe("localToday", () => { @@ -540,6 +561,27 @@ describe("rich decoration", () => { expect(out.map((b) => b.receipt)).toEqual(["", "", "", ""]); }); + // 2026-11-12: plain SMS that the Mac relayed to a contact on RCS, logged + // error 4. Each one carried the contact's read receipt seconds later. The + // bubble said Not Delivered under a message that had been read. + test("a sent message with a read receipt is not failed, whatever error the Mac logged", () => { + const out = decorate( + [ + msg({ ts: "2026-08-31T10:00:00Z", from_me: true, service: "SMS", error: 4 }), + msg({ ts: "2026-08-31T10:01:00Z", from_me: true, service: "SMS", error: 4, read_at: "2026-08-31T10:01:06Z" }), + ], + today, + ); + expect(out.map((b) => b.failed)).toEqual([true, false]); + expect(out[1]!.receipt).toBe("Read 10:01 AM"); + }); + + test("a failed newest message still owns no receipt", () => { + const out = decorate([msg({ ts: "2026-08-31T10:00:00Z", from_me: true, service: "SMS", error: 4 })], today); + expect(out[0]!.failed).toBe(true); + expect(out[0]!.receipt).toBe(""); + }); + test("receipt from an earlier day carries the day label", () => { expect(receiptLabel("2026-08-30T21:03:00Z", today)).toBe("Read Yesterday 9:03 PM"); expect(receiptLabel("2026-08-31T16:42:00Z", today)).toBe("Read 4:42 PM"); diff --git a/thread.ts b/thread.ts index 40fb5c37..ea63813b 100644 --- a/thread.ts +++ b/thread.ts @@ -23,9 +23,13 @@ import { loadState, mergeTapbacks, normalizeMsgStamps, + preferImessagePolicy, + sendFailed, + sendServiceForMessages, type AttachmentMeta, type ImsgMessage, type LinkCard, + type SendService, type Tapback, } from "./collector"; export { dedupeSelfEcho }; @@ -125,6 +129,11 @@ export interface ThreadOutput { bubbles: Bubble[]; /** Sends for this chat the Mac has not written yet (`--pending-stdin`). */ pending?: PendingSend[]; + /** What a DM sends on, decided from THIS conversation's rows + * (`sendServiceForMessages`). The list row's service is the Mac's chat label + * and goes stale when a contact moves to Android, so BlipView prefers this + * once it has loaded. Absent for groups, which send by chat id. */ + service?: SendService; } // ---------------------------------------------------------------- formatting @@ -313,6 +322,8 @@ export function decorate(msgs: ImsgMessage[], today: string, formats = DEFAULT_F !sameSender(m, next) || minutesBetween(m.ts, next.ts) > GROUP_GAP_MINUTES; const stickerState = normalizeStickerOverlays(m.stickers); + // A read receipt outranks the Mac's error code (`sendFailed`). + const failed = sendFailed(m); out.push({ ts: m.ts, @@ -327,7 +338,7 @@ export function decorate(msgs: ImsgMessage[], today: string, formats = DEFAULT_F groupStart, groupEnd, time: groupEnd ? clockLabel(m.ts, formats.time) : "", - receipt: i === receiptIdx && !(m.error ?? 0) ? (m.read_at ? receiptLabel(m.read_at, today, formats) : m.delivered ? "Delivered" : "") : "", + receipt: i === receiptIdx && !failed ? (m.read_at ? receiptLabel(m.read_at, today, formats) : m.delivered ? "Delivered" : "") : "", tapbacks: m.tapbacks ?? [], // Belt to imsg 1.5.1's suspenders: link-preview payloads are not files. attachments: (m.attachments ?? []).filter( @@ -343,7 +354,7 @@ export function decorate(msgs: ImsgMessage[], today: string, formats = DEFAULT_F effect: m.effect ?? "", audio: m.audio === true, html: linkify((m.text ?? "").replace(//g, "").trim()), - failed: m.from_me && typeof m.error === "number" && m.error !== 0, + failed, ...(m.scheduled === true ? { scheduled: true, scheduledFor: `${dayLabel(m.ts, today, formats)} ${clockLabel(m.ts, formats.time)}` } : {}), @@ -586,6 +597,7 @@ export function loadThread( today: string, formats = DEFAULT_FORMATS, runner = spawnSync, + preferImessage?: boolean, ): ThreadOutput { // Groups load by EXACT chat id (imsg ≥1.8.0 `thread --chat`). The old // recent-window scan cost ~20× the rows and missed anything older than @@ -614,7 +626,10 @@ export function loadThread( const msgs = selectThread( rows, chat, group, limit, state.selfChats, state.chatAliases, ); - return { ok: true, online: true, error: "", bubbles: decorate(msgs, today, formats) }; + return { + ok: true, online: true, error: "", bubbles: decorate(msgs, today, formats), + ...(group ? {} : { service: sendServiceForMessages(msgs, preferImessage ?? preferImessagePolicy()) }), + }; } catch (e) { return { ok: false, online: true, error: `bad JSON from imsg: ${e}`, bubbles: [] }; } diff --git a/ui.test.ts b/ui.test.ts index be7cbae8..fde3ab20 100644 --- a/ui.test.ts +++ b/ui.test.ts @@ -1162,6 +1162,26 @@ describe("a message can carry several files (multi-file drafts)", () => { }); }); +describe("a DM sends on its own rows, not the Mac's chat label", () => { + // 2026-11-12: root.active.service is the list row's service, the Mac's label + // for the chat. It stayed "iMessage" for a contact texting on RCS. + test("the loader keeps thread.ts's service with the chat it was loaded for", () => { + const load = panel.slice(panel.indexOf("id: threadProc"), panel.indexOf("onExited", panel.indexOf("id: threadProc"))); + expect(load).toContain("root.threadSendServiceChat = root.threadRunningChat"); + expect(load).toContain('root.threadSendService = String(d.service || "")'); + // set before the unchanged-snapshot early return, which skips the rest + expect(load.indexOf("root.threadSendService =")).toBeLessThan(load.indexOf("if (j === root.bubblesJson)")); + }); + + test("text and file sends both ask SendState.sendServiceArg", () => { + const send = panel.slice(panel.indexOf("function send()"), panel.indexOf("function wireStamp")); + expect(send.match(/SendState\.sendServiceArg\(/g)?.length).toBe(2); + // ...and both hand it the rows' service, or the label decides again + expect(send.match(/root\.threadSendServiceChat, root\.threadSendService\)/g)?.length).toBe(2); + expect(send).not.toMatch(/test\(svc\)/); + }); +}); + describe("a multi-part send is pinned to the thread it started in", () => { test("the service is captured once, not re-read per part", () => { // root.active can change under a batch; a later part must not go out on a From 3a13a2755433fe824a80365f0e8a456e9ec9f231 Mon Sep 17 00:00:00 2001 From: Jason Alexander Date: Sat, 14 Nov 2026 14:58:44 -0700 Subject: [PATCH 2/2] fix(send): only the send target's rows decide its service (#165 review) Blocker: a merged phone + email conversation could send SMS to the email, and never recover. loadThread decided the service from every row in the cluster, but the send goes to the canonical id. The mirror case sent iMessage to an Android number after they last wrote from the email. - sendServiceForMessages(msgs, prefer, target) uses only rows under `target`. thread.ts asks threadSendService(), which returns no answer when the target has no rows of its own, so the label stands instead of "iMessage" (should-fix 4). foldThreadAliases keeps the canonical's own service, never an alias's. mergeChats falls back to the label when that is "". - Guard: an address that is not a phone number never gets SMS, in the rule and in SendState.sendServiceArg. It gets RCS only after texting us on RCS, as RCS business agents (name@rbm.goog) do. Their chats send RCS on main today. - Should-fix 1: if the newest of our sends that provably arrived (delivered or read) is an iMessage newer than their last text, the DM is iMessage. That keeps a quiet blue DM blue when their last text is an old SMS. An error-22 row is never delivered, so the #151 loop stays closed. - Should-fix 3: a read receipt clears the error only on SMS/RCS rows in a 1:1. An iMessage row or a group row keeps the Mac's verdict. - Should-fix 2: the collector's `recent` rows are not --rich, so the failure toast still fires for a relayed SMS. The comments now say so. - Nits: the CLAUDE.md wording is "observed on macOS 27.2". The test that passed trivially is replaced by the label fallback. BlipView's wiring moved into noteThreadService/sendServiceFor, and scripts/test-send-service-ui.py runs those shipping functions under QtTest against the real SendState.mjs (added to CI). Ignoring which chat the rows were loaded for now fails there. All 901 tests pass, and so do the four QtTest scripts. qmllint reports nothing new. Eleven mutations each fail a test: the target filter (rule, thread, fold), the email guard (rule, SendState, view), the label fallback, the receipt scope, the proven-iMessage rule, the empty-load answer, and ignoring the loaded chat. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 + BlipView.qml | 23 ++++++-- CLAUDE.md | 27 ++++++--- SendState.mjs | 6 +- collector.test.ts | 101 +++++++++++++++++++++++++++++--- collector.ts | 85 ++++++++++++++++++++++----- scripts/test-send-service-ui.py | 101 ++++++++++++++++++++++++++++++++ send-state.test.ts | 11 ++++ send-state.ts | 10 +++- thread.test.ts | 36 +++++++++++- thread.ts | 23 ++++++-- ui.test.ts | 19 +++--- 12 files changed, 386 insertions(+), 58 deletions(-) create mode 100755 scripts/test-send-service-ui.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8b7f0ea3..b9507182 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,8 @@ jobs: sudo apt-get update -qq sudo apt-get install -y -q qt6-declarative-dev-tools qml6-module-qttest qml6-module-qtquick qml6-module-qtquick-window qml6-module-qtqml-workerscript python3 scripts/test-read-ui.py + - name: Send service wiring (synthetic QtTest, real BlipView functions) + run: python3 scripts/test-send-service-ui.py - name: Composer emoji keyboard regression run: | sudo apt-get install -y -q qml6-module-qtquick-controls qml6-module-qtquick-templates diff --git a/BlipView.qml b/BlipView.qml index c503072f..40db8d48 100644 --- a/BlipView.qml +++ b/BlipView.qml @@ -462,6 +462,20 @@ FocusScope { // contact moves to Android. property string threadSendService: "" property string threadSendServiceChat: "" + + /** Keep thread.ts's `service` with the chat it was loaded for. It is "" when + * the rows named none: a group, or no rows under the id we send to. */ + function noteThreadService(chat, service) { + root.threadSendServiceChat = String(chat || "") + root.threadSendService = String(service || "") + } + + /** The --service a send to `chat` carries, through SendState.sendServiceArg: + * the loaded rows' answer when they belong to `chat`, else the list label. */ + function sendServiceFor(chat) { + return SendState.sendServiceArg(String(chat), root.activeIsGroup, + String(root.active.service || ""), root.threadSendServiceChat, root.threadSendService) + } // Sends the Mac has not written a row for yet, {chat, text, ts}. Every // thread reload carries them to thread.ts (--pending-stdin, never argv), // which keeps their bubbles until the real row lands. Memory only. @@ -1710,8 +1724,7 @@ FocusScope { // strictly one at a time — pumpFileSend() starts the next as each lands. root.fileQueue = root.attachDrafts.map(function(d) { return d.path }) root.sendCaption = trimmed - root.sendService = SendState.sendServiceArg(root.sendChat, root.activeIsGroup, - String(root.active.service || ""), root.threadSendServiceChat, root.threadSendService) + root.sendService = root.sendServiceFor(root.sendChat) pumpFileSend() return } @@ -1726,8 +1739,7 @@ FocusScope { : ["--to", chat] // green-bubble (SMS/RCS) threads send on their own service (war room #2), // read from the conversation's own rows once they have loaded - var svc = SendState.sendServiceArg(chat, root.activeIsGroup, - String(root.active.service || ""), root.threadSendServiceChat, root.threadSendService) + var svc = root.sendServiceFor(chat) if (svc !== "") target = target.concat(["--service", svc]) var localId = String(++root.nextSendId) root.pendingRevision++ @@ -1909,8 +1921,7 @@ FocusScope { var d = JSON.parse(text.trim()) if (d.ok === true) { var list = Array.isArray(d.bubbles) ? d.bubbles : [] - root.threadSendServiceChat = root.threadRunningChat - root.threadSendService = String(d.service || "") + root.noteThreadService(root.threadRunningChat, d.service) root.pendingTapback = TapbackActions.pendingAfterLoad(root.pendingTapback, root.threadRunningChat, list, root.threadTapbackDone) // the tool is done but chat.db does not show it yet (a self-thread's echo lags): look again if (root.threadTapbackDone && root.pendingTapback && root.pendingTapback.chat === root.threadRunningChat) { diff --git a/CLAUDE.md b/CLAUDE.md index bbecab4a..819cbb2e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -119,15 +119,24 @@ what it is handed. Keep it that way. send per row. The read watermark (`--seen`) skips pending bubbles: their ts is THIS machine's clock. A failed send retains its bubble with a failure reason in memory. Never go back to "wait 1.5 s, then reload". - **A DM sends on what its own messages say, never on the Mac's chat label.** `imsg chats` reports the - chat row's `service_name`. On macOS 26 and later, one row holds the whole conversation, and that label - follows the Mac's OWN last send, Blip's included, so trusting it loops. On 2026-11-12, a contact - texting on RCS stayed labelled iMessage and every send failed with error 22. Another stayed labelled SMS - and got plain SMS. `sendServiceForMessages` decides from rows in two places. In the collector it reads - the preview window: `mergeChats` keeps that answer for every DM the window has rows for, and the label - names only quiet ones. In `thread.ts` it reads the opened conversation and reports it as `service`, - which BlipView prefers through `SendState.sendServiceArg`. #97, #147 and #151 each guarded one - direction of this same loop. A read receipt outranks `error` (`sendFailed`). The Mac logs error 4 on - plain SMS it relays to an RCS contact, and the iPhone delivers it anyway. + chat row's `service_name`. On a gateway where one row holds the whole conversation (observed on macOS + 27.2), that label follows the Mac's OWN last send, Blip's included, so trusting it loops. On 2026-11-12, a + contact texting on RCS stayed labelled iMessage and every send failed with error 22. Another stayed + labelled SMS and got plain SMS. `sendServiceForMessages` decides from rows in two places. In the + collector it reads the preview window: `mergeChats` keeps that answer for every DM with rows under its + own id, and the label names only the rest. In `thread.ts` it reads the opened conversation + (`threadSendService`) and reports it as `service`, which BlipView prefers through + `SendState.sendServiceArg`. #97, #147 and #151 each guarded one direction of this same loop. + **Only rows under the id the send goes `--to` count** (`target`; `foldThreadAliases` keeps the + canonical's own service). A merged phone + email conversation carries both handles' rows. Deciding from + all of them sent SMS to the email, and iMessage to an Android number after they last wrote from the + email (#165 review). No own rows means no answer, and the label stands. An address that is not a phone + number never gets SMS. It gets RCS only after texting us on RCS, as `name@rbm.goog` business agents do. + Our iMessage that provably arrived (delivered or read) after their last text keeps a quiet blue DM + blue. A read receipt outranks `error` (`sendFailed`) only for SMS and RCS in a 1:1, because the Mac + logs error 4 on plain SMS it relays to an RCS contact and the iPhone delivers it anyway. Thread loads + are `--rich` and carry the receipt. The collector's `recent` rows are not, so its failure toast still + fires for that SMS. - **A Mac that is signed out READS fine and cannot SEND.** Reads are sqlite over ssh and need no login; a send needs Messages, and Launch Services starts an app only inside a GUI session, so at the login window every send dies with -10810 (`friendlySendError` says it in plain words). `imsg session` is the read-only probe diff --git a/SendState.mjs b/SendState.mjs index ea3f30c6..4d4c31b9 100644 --- a/SendState.mjs +++ b/SendState.mjs @@ -7,8 +7,10 @@ function markSendFailed(items, id, reason, fallback) { function sendServiceArg(chat, group, listService, loadedChat, loadedService) { if (group) return ""; - const svc = loadedChat === chat && loadedService !== "" ? loadedService : listService; - return /^(SMS|RCS)$/i.test(svc) ? svc.toUpperCase() : ""; + const svc = (loadedChat === chat && loadedService !== "" ? loadedService : listService).toUpperCase(); + if (svc === "RCS") + return svc; + return svc === "SMS" && /^\+?[0-9]{3,15}$/.test(chat) ? svc : ""; } function friendlySendError(raw) { return /(^|[^\d])-10810(\D|$)/.test(raw) ? "Messages can't start on the Mac: nobody is logged in there. Log in on the Mac, then send again." : raw; diff --git a/collector.test.ts b/collector.test.ts index 65336a45..c78442ae 100644 --- a/collector.test.ts +++ b/collector.test.ts @@ -1414,6 +1414,22 @@ describe("a re-keyed group is ONE conversation", () => { expect(out).toHaveLength(1); expect(out[0]).toMatchObject({ chat: email, last_ts: "2026-09-05T17:24:01Z", unread: 1 }); }); + + // #165 review: a DM sends `--to `, so an alias's service, the + // other handle of a merged phone + email conversation, must not ride along. + test("a merged DM keeps the canonical's own service, never the alias's", () => { + const phone = "+15550100001"; + const email = "pat@example.com"; + const sms = (c: string, ts: string) => ({ ...(thread(c, ts, 1, 0) as object), service: "SMS" }) as never; + const newerAlias = foldThreadAliases( + [thread(email, "2026-09-04T21:32:29Z", 3, 0), sms(phone, "2026-09-05T17:24:01Z")], + { [phone]: email }, + ); + expect(newerAlias[0]).toMatchObject({ chat: email, service: "iMessage" }); + // the canonical has no rows in the window: unknown, so the label decides + const aliasOnly = foldThreadAliases([sms(phone, "2026-09-05T17:24:01Z")], { [phone]: email }); + expect(aliasOnly[0]).toMatchObject({ chat: email, service: "" }); + }); }); describe("complete conversation list (mergeChats)", () => { @@ -1517,9 +1533,10 @@ describe("complete conversation list (mergeChats)", () => { expect(mergeChats([windowThread], [unified], {}, {})[0]!.service).toBe("iMessage"); }); - test("a genuinely green DM still takes its service from the list", () => { - const green = { ...windowThread, chat: "+15559990000", service: "SMS" }; - expect(mergeChats([green], [chats[2]!], {}, {})[0]!.service).toBe("SMS"); + test("a DM whose own id has no rows in the window takes the label", () => { + // what foldThreadAliases leaves when only an alias had rows + const unknown = { ...windowThread, service: "" }; + expect(mergeChats([unknown], [{ ...chats[0]!, service: "SMS" }], {}, {})[0]!.service).toBe("SMS"); }); // Live shapes (2026-11-12, a macOS 27.2 gateway). Two Android contacts, both @@ -1865,18 +1882,84 @@ describe("which service a DM sends on (@lukejmorrison, PR #4)", () => { ])).toBe("SMS"); }); - test("a sent row with a read receipt is not a failure, whatever error the Mac logged", () => { + test("a read receipt clears a relayed SMS or RCS in a 1:1, and nothing else", () => { const { sendFailed } = require("./collector") as typeof import("./collector"); + const read = "2026-09-03T10:00:06Z"; expect(sendFailed(at(0, { from_me: true, service: "SMS", error: 4 }))).toBe(true); - expect(sendFailed(at(0, { from_me: true, service: "SMS", error: 4, read_at: "2026-09-03T10:00:06Z" }))).toBe(false); + expect(sendFailed(at(0, { from_me: true, service: "SMS", error: 4, read_at: read }))).toBe(false); + expect(sendFailed(at(0, { from_me: true, service: "RCS", error: 4, read_at: read }))).toBe(false); expect(sendFailed(at(0, { from_me: true, service: "SMS", error: 0 }))).toBe(false); expect(sendFailed(at(0, { from_me: true, service: "SMS" }))).toBe(false); expect(sendFailed(at(0, { from_me: false, service: "SMS", error: 4 }))).toBe(false); - // a read iMessage was delivered, so it is no sign they left iMessage + // #165 review: an iMessage keeps the Mac's verdict (a failed edit of a read + // message carries both), and so does a group, where one receipt is one member + expect(sendFailed(at(0, { from_me: true, service: "iMessage", error: 22, read_at: read }))).toBe(true); + expect(sendFailed(at(0, { chat: "chat900001", from_me: true, service: "SMS", error: 4, read_at: read }))).toBe(true); + }); + + // #165 review blocker: a merged phone + email conversation. The send goes + // `--to `, so only the target's own rows decide. + test("only the target's own rows decide: an email is never sent SMS", () => { + const email = "pat@example.com"; + const phone = "+15551234567"; + const cluster = [ + at(0, { chat: phone, handle: phone, from_me: false, service: "SMS" }), + at(1, { chat: email, handle: email, from_me: true, service: "iMessage", delivered: true, + read_at: "2026-09-03T11:00:09Z" }), + ]; + expect(sendServiceForMessages(cluster, false, email)).toBe("iMessage"); + // after a failed SMS the old rule saw the same inbound SMS again and looped expect(sendServiceForMessages([ - at(0, { from_me: false, service: "iMessage" }), - at(1, { from_me: true, service: "iMessage", error: 22, read_at: "2026-09-03T11:00:05Z" }), - ])).toBe("iMessage"); + ...cluster, at(2, { chat: email, handle: email, from_me: true, service: "SMS", error: 4 }), + ], false, email)).toBe("iMessage"); + }); + + test("...and a phone whose person last wrote from their email is not sent iMessage", () => { + const email = "pat@example.com"; + const phone = "+15551234567"; + expect(sendServiceForMessages([ + at(0, { chat: phone, handle: phone, from_me: false, service: "SMS" }), + at(1, { chat: email, handle: email, from_me: false, service: "iMessage" }), + ], false, phone)).toBe("SMS"); + }); + + test("an address that is not a number gets SMS never, and RCS only if it texted us on RCS", () => { + const email = "pat@example.com"; + expect(sendServiceForMessages([at(0, { chat: email, handle: email, from_me: false, service: "SMS" })], false, email)) + .toBe("iMessage"); + expect(sendServiceForMessages([at(0, { chat: email, handle: email, from_me: true, service: "RCS" })], false, email)) + .toBe("iMessage"); + // an RCS business agent replies from an address and is answered on RCS + const agent = "verify_agent@rbm.goog"; + expect(sendServiceForMessages([at(0, { chat: agent, handle: agent, from_me: false, service: "RCS" })], false, agent)) + .toBe("RCS"); + }); + + // #165 review should-fix 1: a quiet blue DM whose last inbound is an old SMS. + test("our iMessage that reached them after their last text keeps a DM on iMessage", () => { + const blue = [ + msg({ ts: "2025-03-01T10:00:00Z", from_me: false, service: "SMS" }), + msg({ ts: "2026-11-01T10:00:00Z", from_me: true, service: "iMessage", delivered: true }), + msg({ ts: "2026-11-02T10:00:00Z", from_me: true, service: "iMessage", read_at: "2026-11-02T10:01:00Z" }), + msg({ ts: "2026-11-03T10:00:00Z", from_me: true, service: "iMessage", delivered: true, read_at: "2026-11-03T10:00:30Z" }), + ]; + expect(sendServiceForMessages(blue)).toBe("iMessage"); + // an error-22 send is never delivered, so the #151 loop stays closed + expect(sendServiceForMessages([ + msg({ ts: "2025-03-01T10:00:00Z", from_me: false, service: "SMS" }), + msg({ ts: "2026-11-01T10:00:00Z", from_me: true, service: "iMessage", error: 22 }), + ])).toBe("SMS"); + // proof older than their last text is not proof of now: they moved to RCS since + expect(sendServiceForMessages([ + msg({ ts: "2026-10-01T10:00:00Z", from_me: true, service: "iMessage", delivered: true }), + msg({ ts: "2026-11-01T10:00:00Z", from_me: false, service: "RCS" }), + ])).toBe("RCS"); + // only our NEWEST proven send counts: an RCS that arrived after a read iMessage + expect(sendServiceForMessages([ + msg({ ts: "2026-10-01T10:00:00Z", from_me: false, service: "RCS" }), + msg({ ts: "2026-10-02T10:00:00Z", from_me: true, service: "iMessage", delivered: true }), + msg({ ts: "2026-10-03T10:00:00Z", from_me: true, service: "RCS", delivered: true }), + ])).toBe("RCS"); }); test("our failed iMessage to a phone, newest, means they are not on iMessage", () => { diff --git a/collector.ts b/collector.ts index 627a2ac5..fafc69b8 100644 --- a/collector.ts +++ b/collector.ts @@ -662,10 +662,18 @@ export type SendService = "iMessage" | "SMS" | "RCS"; * receipt 1 to 6 seconds after it was sent. A read receipt is the recipient's * own device saying the message arrived, so it outranks the error. Carrier SMS * has no receipts, so this clears only a row that provably got through. - * `read_at` comes with `--rich` fetches; a plain fetch keeps the old rule. + * + * The exception is exactly that case: an SMS or RCS row in a 1:1. An iMessage + * row keeps the Mac's verdict, because a failed edit of a message already read + * carries both an error and a receipt. So does any group row, because one + * member's receipt says nothing about the others. `read_at` comes only with + * `--rich` fetches. The collector's plain `recent` rows never carry it, so its + * failure toast still fires for a relayed SMS (`selectFailures`). */ export function sendFailed(m: ImsgMessage): boolean { - return m.from_me === true && typeof m.error === "number" && m.error !== 0 && !m.read_at; + if (m.from_me !== true || typeof m.error !== "number" || m.error === 0) return false; + const relayed = !isGroupChat(chatKey(m)) && normalizeSendService(m.service) !== "iMessage"; + return !(relayed && m.read_at); } /** Map a chat.db service string onto what `imsg-send --service` accepts. */ @@ -695,22 +703,47 @@ export function normalizeSendService(raw: string | undefined | null): SendServic * the loaded window (in or out) → iMessage. Last-inbound RCS/SMS in a * mixed 1:1 otherwise makes the next send green, and the Mac records SMS * error 4 while the iPhone still delivers. Off by default. - * 3. otherwise the last INBOUND service: that is what they actually reach + * 3. the newest of our sends that provably reached them (delivered, or + * read) is an iMessage newer than anything they sent → iMessage. Their + * last text can be an SMS from long ago in a quiet DM that is blue now. + * Only iMessage and RCS rows get `delivered`, and an error-22 row is + * never delivered, so this cannot reopen the #151 loop. It needs + * `--rich` rows (thread loads). The collector's window never qualifies. + * 4. otherwise the last INBOUND service: that is what they actually reach * us on, and a failed outbound must never override it. - * 4. no inbound at all → the last outbound that SUCCEEDED. - * 5. nothing to go on → iMessage, like a fresh conversation. + * 5. no inbound at all → the last outbound that SUCCEEDED. + * 6. nothing to go on → iMessage, like a fresh conversation. * Groups send `--chat-id` and ignore all of this. + * + * `target` is the id the send goes `--to`. Only rows under that id decide. + * A merged phone + email conversation carries both handles' rows, and the + * phone's SMS once sent SMS to the email (#165 review). An address that is + * not a phone number never gets SMS. It gets RCS only when that same address + * reached us on RCS, as a business agent (`name@rbm.goog`) does. */ -export function sendServiceForMessages(msgs: ImsgMessage[], preferImessage = false): SendService { - if (!msgs.length) return "iMessage"; - const sorted = [...msgs].sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0)); +export function sendServiceForMessages( + msgs: ImsgMessage[], + preferImessage = false, + target?: string, +): SendService { + const rows = target === undefined ? msgs : msgs.filter((m) => chatKey(m) === target); + if (!rows.length) return "iMessage"; + const sorted = [...rows].sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0)); + const chat = target ?? chatKey(sorted[sorted.length - 1]); + const svc = decideSendService(sorted, preferImessage, chat); + if (svc === "iMessage" || /^\+?[0-9]{3,15}$/.test(chat)) return svc; + const theyUseRcs = sorted.some((m) => !m.from_me && chatKey(m) === chat && normalizeSendService(m.service) === "RCS"); + return svc === "RCS" && theyUseRcs ? "RCS" : "iMessage"; +} + +/** The rules above over one handle's rows, sorted oldest first. */ +function decideSendService(sorted: ImsgMessage[], preferImessage: boolean, chat: string): SendService { let lastInbound: ImsgMessage | undefined; for (let i = sorted.length - 1; i >= 0 && !lastInbound; i--) { if (!sorted[i]!.from_me) lastInbound = sorted[i]; } const newest = sorted[sorted.length - 1]!; - const chat = chatKey(newest); if (newest.from_me && sendFailed(newest) && normalizeSendService(newest.service) === "iMessage" && /^\+?[0-9]{3,15}$/.test(chat)) { @@ -722,6 +755,13 @@ export function sendServiceForMessages(msgs: ImsgMessage[], preferImessage = fal if (!sendFailed(m) && normalizeSendService(m.service) === "iMessage") return "iMessage"; } } + for (let i = sorted.length - 1; i >= 0; i--) { + const m = sorted[i]!; + if (lastInbound && m.ts <= lastInbound.ts) break; + if (!m.from_me || sendFailed(m) || !(m.delivered === true || m.read_at)) continue; + if (normalizeSendService(m.service) === "iMessage") return "iMessage"; + break; + } if (lastInbound) return normalizeSendService(lastInbound.service); for (let i = sorted.length - 1; i >= 0; i--) { if (!sendFailed(sorted[i]!)) return normalizeSendService(sorted[i]!.service); @@ -782,7 +822,7 @@ export function buildThreads( guid: isGroupChat(chat) ? groups[chat]?.guid ?? "" : "", name: isGroupChat(chat) ? groupName(chat, groups[chat], byHandle) : displayName(sorted), handle: String(last.handle || chat), - service: isGroupChat(chat) ? last.service : sendServiceForMessages(sorted, preferImessage), + service: isGroupChat(chat) ? last.service : sendServiceForMessages(sorted, preferImessage, chat), last_ts: last.ts, last_text: messagePreview(last.text, last.attachments?.[0]), last_from_me: last.from_me, @@ -1357,6 +1397,9 @@ export function selectFailures( const out: Toast[] = []; const cutoff = nowTs(new Date(Date.parse(now) - FAILURE_TOAST_WINDOW_MS)); for (const m of msgs) { + // A read receipt clears a relayed SMS (`sendFailed`), but these rows come + // from a plain `recent` fetch, which carries no `read_at`. So this toast + // still fires for an SMS the iPhone delivered anyway. if (!sendFailed(m)) continue; if (m.ts < cutoff) continue; const key = "fail:" + toastKey(m); @@ -2126,8 +2169,15 @@ export function foldThreadAliases(threads: Thread[], aliases: Record(); + // A DM sends `--to `, so only the canonical's own rows may name + // its service. An alias's rows belong to the other handle of a merged + // phone + email conversation and say nothing about this one (#165 review). + // With no rows of its own, the service is "", and mergeChats falls back to + // the list's label. + const own = new Map(); for (const t of threads) { const canon = aliases[t.chat] ?? t.chat; + if (t.chat === canon) own.set(canon, t.service); const seen = at.get(canon); if (seen === undefined) { at.set(canon, out.length); @@ -2144,7 +2194,11 @@ export function foldThreadAliases(threads: Thread[], aliases: Record { + if (isGroupChat(t.chat)) return t; + const service = own.get(t.chat) ?? ""; + return service === t.service ? t : { ...t, service }; + }); } /** Same fold for a per-chat ledger (unread counts, oldest-unread stamps). */ @@ -2214,9 +2268,10 @@ export function mergeChats( // contact texting on RCS stayed labelled iMessage, and every send failed // with error 22. Another stayed labelled SMS and got plain SMS, logged // error 4 (2026-11-12). The label now names a DM only when the window has - // no rows for it (the quiet rows below), and BlipView replaces even that - // with the opened conversation's own rows (thread.ts `service`). A group - // sends by chat id, so the label stays its name. + // no rows under its own id (the quiet rows below, or a merged conversation + // whose rows are all the alias's, left "" by foldThreadAliases). BlipView + // replaces even that with the opened conversation's own rows (thread.ts + // `service`). A group sends by chat id, so the label stays its name. const listService = info.service || thread.service; return { ...thread, @@ -2229,7 +2284,7 @@ export function mergeChats( ? groupName(thread.chat, groupInfo, knownParticipantNames) : namedGroup(thread.name, thread.chat, aliases) || thread.chat)) : (info.last_name || info.name || thread.name || thread.chat), - service: group ? listService : thread.service, + service: group ? listService : thread.service || listService, last_text: info.last === thread.last_ts ? info.last_text : messagePreview(thread.last_text), pinned, pin_order, diff --git a/scripts/test-send-service-ui.py b/scripts/test-send-service-ui.py new file mode 100755 index 00000000..97fa266d --- /dev/null +++ b/scripts/test-send-service-ui.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Run BlipView's shipping send-service wiring under QtTest, without Blip or a Mac. + +BlipView keeps thread.ts's `service` with the chat it was loaded for +(noteThreadService) and asks SendState.sendServiceArg what a send carries +(sendServiceFor). Both functions are cut out of the real BlipView.qml and run +against the real SendState.mjs, so a change that drops the chat check or reads +the list row's label first fails here, not only in a text match (#165 review). + +Requires Qt 6's qmltestrunner and the QtQuick/QtTest QML modules. An optional +argument runs the same checks against another BlipView.qml. +""" +from pathlib import Path +import os +import shutil +import subprocess +import sys +import tempfile + + +def harness(source): + def function(name): + start = source.index(f" function {name}(") + end = source.index("\n }", start) + len("\n }") + return source[start:end] + + return '''import QtQuick +import QtTest +import "SendState.mjs" as SendState +Item { + id: root + property var active: ({chat: "", service: ""}) + property bool activeIsGroup: false + property string threadSendService: "" + property string threadSendServiceChat: "" + @FUNCTIONS@ + TestCase { + name: "BlipSendService" + function init() { + root.active = {chat: "+15551234567", service: "iMessage"} + root.activeIsGroup = false + root.noteThreadService("", "") + } + // 2026-11-12: a contact texting on RCS whose chat row still said iMessage. + function test_loaded_rows_beat_the_label() { + root.noteThreadService("+15551234567", "RCS") + compare(root.sendServiceFor("+15551234567"), "RCS") + } + function test_rows_loaded_for_another_chat_never_decide() { + root.noteThreadService("+15550000000", "RCS") + root.active = {chat: "+15551234567", service: "SMS"} + compare(root.sendServiceFor("+15551234567"), "SMS") + } + function test_a_load_that_named_no_service_leaves_the_label() { + root.noteThreadService("+15551234567", undefined) + root.active = {chat: "+15551234567", service: "SMS"} + compare(root.sendServiceFor("+15551234567"), "SMS") + } + function test_imessage_carries_no_service() { + root.noteThreadService("+15551234567", "iMessage") + root.active = {chat: "+15551234567", service: "SMS"} + compare(root.sendServiceFor("+15551234567"), "") + } + function test_a_group_never_carries_a_service() { + root.activeIsGroup = true + root.active = {chat: "abcdef0123456789abcdef0123456789", service: "RCS"} + root.noteThreadService("abcdef0123456789abcdef0123456789", "RCS") + compare(root.sendServiceFor("abcdef0123456789abcdef0123456789"), "") + } + function test_an_email_never_carries_sms() { + root.active = {chat: "pat@example.com", service: "SMS"} + compare(root.sendServiceFor("pat@example.com"), "") + } + } +} +'''.replace("@FUNCTIONS@", "\n".join(function(name) for name in ("noteThreadService", "sendServiceFor"))) + + +def main(): + repo = Path(__file__).resolve().parents[1] + source = Path(sys.argv[1]) if len(sys.argv) > 1 else repo / "BlipView.qml" + runner = os.environ.get("QMLTESTRUNNER") or shutil.which("qmltestrunner") + if not runner: + runner = next((str(path) for path in ( + Path("/usr/lib/qt6/bin/qmltestrunner"), + Path("/usr/lib/qt6/libexec/qmltestrunner")) if path.is_file()), None) + if not runner: + sys.exit("Qt 6 qmltestrunner not found; set QMLTESTRUNNER to its path") + with tempfile.TemporaryDirectory(prefix="blip-send-service-ui-") as directory: + dest = Path(directory) + shutil.copyfile(repo / "SendState.mjs", dest / "SendState.mjs") + (dest / "tst_send_service.qml").write_text(harness(source.read_text())) + result = subprocess.run( + [runner, "-input", directory, "-platform", "offscreen"], + env={**os.environ, "QT_QPA_PLATFORM": "offscreen", + "QT_QPA_PLATFORMTHEME": "generic"}, check=False, timeout=60) + return result.returncode + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/send-state.test.ts b/send-state.test.ts index 80290006..b7f5b3bd 100644 --- a/send-state.test.ts +++ b/send-state.test.ts @@ -126,6 +126,16 @@ test("a send uses the opened conversation's own service over the list label", () expect(sendServiceArg(chat, false, "iMessage", "", "")).toBe(""); }); +// #165 review: a merged phone + email conversation could hand an email address SMS. +test("an address that is not a phone number never carries SMS", () => { + expect(sendServiceArg("pat@example.com", false, "SMS", "", "")).toBe(""); + expect(sendServiceArg("pat@example.com", false, "iMessage", "pat@example.com", "SMS")).toBe(""); + // an RCS business agent texts from an address, and its label says RCS + expect(sendServiceArg("verify_agent@rbm.goog", false, "RCS", "", "")).toBe("RCS"); + // short codes are numbers + expect(sendServiceArg("99123", false, "SMS", "", "")).toBe("SMS"); +}); + test("a group never carries --service: it sends by chat id", () => { const id = "abcdef0123456789abcdef0123456789"; expect(sendServiceArg(id, true, "RCS", id, "RCS")).toBe(""); @@ -136,5 +146,6 @@ test("the deployed QML module picks the same service as the TypeScript", async ( for (const args of [ ["+1", false, "iMessage", "+1", "RCS"], ["+1", false, "SMS", "+2", "RCS"], ["+1", true, "SMS", "+1", "SMS"], ["+1", false, "rcs", "", ""], + ["pat@example.com", false, "SMS", "", ""], ["a@rbm.goog", false, "RCS", "", ""], ] as const) expect(runtime.sendServiceArg(...args)).toBe(sendServiceArg(...args)); }); diff --git a/send-state.ts b/send-state.ts index 5a38e1a3..79bd187d 100644 --- a/send-state.ts +++ b/send-state.ts @@ -19,7 +19,10 @@ export function markSendFailed(items: T[], id: string, reas * The opened conversation's own rows (thread.ts `service`, kept with the chat * they were loaded for) outrank the list row's service. That is the Mac's chat * label, which follows the Mac's own last send and stayed "iMessage" for a - * contact texting on RCS, so every send failed with error 22 (2026-11-12). */ + * contact texting on RCS, so every send failed with error 22 (2026-11-12). + * An address that is not a phone number never carries SMS, whatever the label + * says (#165 review). RCS stays open to it: business agents text from + * `name@rbm.goog`, and their labels say RCS. */ export function sendServiceArg( chat: string, group: boolean, @@ -28,8 +31,9 @@ export function sendServiceArg( loadedService: string, ): string { if (group) return ""; - const svc = loadedChat === chat && loadedService !== "" ? loadedService : listService; - return /^(SMS|RCS)$/i.test(svc) ? svc.toUpperCase() : ""; + const svc = (loadedChat === chat && loadedService !== "" ? loadedService : listService).toUpperCase(); + if (svc === "RCS") return svc; + return svc === "SMS" && /^\+?[0-9]{3,15}$/.test(chat) ? svc : ""; } /** Say what a send failure MEANS when the Mac's own words are only a number. diff --git a/thread.test.ts b/thread.test.ts index 4ceb5601..0b78a661 100644 --- a/thread.test.ts +++ b/thread.test.ts @@ -20,7 +20,7 @@ import { withPendingSends, } from "./thread"; import type { Bubble, PendingSend } from "./thread"; -import { cliChatArg } from "./thread"; +import { cliChatArg, threadSendService } from "./thread"; function msg(over: Partial = {}): ImsgMessage { return { @@ -410,6 +410,32 @@ describe("loadThread", () => { expect(r.service).toBe("RCS"); }); + // #165 review blocker, through the function loadThread uses: a merged + // phone + email conversation shows both handles' rows. + test("only rows under the id we send to decide the service", () => { + const email = "pat@example.com"; + const phone = "+15551234567"; + const rows = [ + msg({ ts: "2026-08-30T12:00:00Z", chat: phone, handle: phone, service: "SMS" }), + msg({ ts: "2026-08-30T12:05:00Z", chat: email, handle: email, from_me: true, service: "iMessage", + delivered: true, read_at: "2026-08-30T12:05:09Z" }), + ]; + expect(threadSendService(rows, email)).toBe("iMessage"); + expect(threadSendService([ + msg({ ts: "2026-08-30T12:00:00Z", chat: phone, handle: phone, service: "SMS" }), + msg({ ts: "2026-08-30T12:05:00Z", chat: email, handle: email, service: "iMessage" }), + ], phone)).toBe("SMS"); + }); + + // #165 review should-fix 4: "iMessage" for an empty list must not replace the label. + test("no rows under the id we send to: no service, so the label stands", () => { + expect(threadSendService([msg({ chat: "+15550000000", handle: "+15550000000" })], "+15551234567")).toBeUndefined(); + const r = loadThread("+15551234567", 10, "2026-08-30", DEFAULT_FORMATS, + fake({ status: 0, stdout: "[]" }), false); + expect(r.ok).toBe(true); + expect(r).not.toHaveProperty("service"); + }); + test("a group reports no service: it sends by chat id", () => { const id = "abcdef0123456789abcdef0123456789"; const r = loadThread(id, 10, "2026-08-30", DEFAULT_FORMATS, @@ -576,6 +602,14 @@ describe("rich decoration", () => { expect(out[1]!.receipt).toBe("Read 10:01 AM"); }); + test("a read receipt does not clear a failed iMessage", () => { + // #165 review: a failed edit of a message already read carries both + const out = decorate([msg({ ts: "2026-08-31T10:00:00Z", from_me: true, service: "iMessage", error: 22, + read_at: "2026-08-31T10:00:06Z" })], today); + expect(out[0]!.failed).toBe(true); + expect(out[0]!.receipt).toBe(""); + }); + test("a failed newest message still owns no receipt", () => { const out = decorate([msg({ ts: "2026-08-31T10:00:00Z", from_me: true, service: "SMS", error: 4 })], today); expect(out[0]!.failed).toBe(true); diff --git a/thread.ts b/thread.ts index ea63813b..01bf06a7 100644 --- a/thread.ts +++ b/thread.ts @@ -129,10 +129,11 @@ export interface ThreadOutput { bubbles: Bubble[]; /** Sends for this chat the Mac has not written yet (`--pending-stdin`). */ pending?: PendingSend[]; - /** What a DM sends on, decided from THIS conversation's rows - * (`sendServiceForMessages`). The list row's service is the Mac's chat label + /** What a DM sends on, decided from the rows of the id it sends to + * (`threadSendService`). The list row's service is the Mac's chat label * and goes stale when a contact moves to Android, so BlipView prefers this - * once it has loaded. Absent for groups, which send by chat id. */ + * once it has loaded. Absent for groups, which send by chat id, and for a + * DM with no rows under its own id, where the label has to stand. */ service?: SendService; } @@ -589,6 +590,19 @@ export function selectThread( return msgs.length > limit ? msgs.slice(msgs.length - limit) : msgs; } +/** + * What a DM in this conversation sends on, from the rows of the id it sends + * `--to` and no others. A merged phone + email conversation shows both + * handles' rows. Deciding from all of them sent SMS to an email address, and + * iMessage to an Android number after they last wrote from the email (#165 + * review). No rows of its own → undefined. An empty answer must not stand in + * as "iMessage": the caller keeps the list's label instead. + */ +export function threadSendService(msgs: ImsgMessage[], chat: string, preferImessage = false): SendService | undefined { + const own = msgs.filter((m) => chatKey(m) === chat); + return own.length ? sendServiceForMessages(own, preferImessage, chat) : undefined; +} + // ---------------------------------------------------------------- transport export function loadThread( @@ -626,9 +640,10 @@ export function loadThread( const msgs = selectThread( rows, chat, group, limit, state.selfChats, state.chatAliases, ); + const service = group ? undefined : threadSendService(msgs, chat, preferImessage ?? preferImessagePolicy()); return { ok: true, online: true, error: "", bubbles: decorate(msgs, today, formats), - ...(group ? {} : { service: sendServiceForMessages(msgs, preferImessage ?? preferImessagePolicy()) }), + ...(service ? { service } : {}), }; } catch (e) { return { ok: false, online: true, error: `bad JSON from imsg: ${e}`, bubbles: [] }; diff --git a/ui.test.ts b/ui.test.ts index fde3ab20..edad6eca 100644 --- a/ui.test.ts +++ b/ui.test.ts @@ -1165,19 +1165,20 @@ describe("a message can carry several files (multi-file drafts)", () => { describe("a DM sends on its own rows, not the Mac's chat label", () => { // 2026-11-12: root.active.service is the list row's service, the Mac's label // for the chat. It stayed "iMessage" for a contact texting on RCS. - test("the loader keeps thread.ts's service with the chat it was loaded for", () => { + // What these functions DO is run for real by scripts/test-send-service-ui.py + // (QtTest, the shipping functions, the real SendState.mjs). These checks pin + // only that the loader and send() go through them. + test("the loader hands thread.ts's service to noteThreadService with the chat it loaded", () => { const load = panel.slice(panel.indexOf("id: threadProc"), panel.indexOf("onExited", panel.indexOf("id: threadProc"))); - expect(load).toContain("root.threadSendServiceChat = root.threadRunningChat"); - expect(load).toContain('root.threadSendService = String(d.service || "")'); - // set before the unchanged-snapshot early return, which skips the rest - expect(load.indexOf("root.threadSendService =")).toBeLessThan(load.indexOf("if (j === root.bubblesJson)")); + expect(load).toContain("root.noteThreadService(root.threadRunningChat, d.service)"); + // before the unchanged-snapshot early return, which skips the rest + expect(load.indexOf("root.noteThreadService(")).toBeLessThan(load.indexOf("if (j === root.bubblesJson)")); }); - test("text and file sends both ask SendState.sendServiceArg", () => { + test("text and file sends both ask sendServiceFor, never the label directly", () => { const send = panel.slice(panel.indexOf("function send()"), panel.indexOf("function wireStamp")); - expect(send.match(/SendState\.sendServiceArg\(/g)?.length).toBe(2); - // ...and both hand it the rows' service, or the label decides again - expect(send.match(/root\.threadSendServiceChat, root\.threadSendService\)/g)?.length).toBe(2); + expect(send.match(/root\.sendServiceFor\(/g)?.length).toBe(2); + expect(send).not.toContain("root.active.service"); expect(send).not.toMatch(/test\(svc\)/); }); });