Skip to content

Commit 3a233c8

Browse files
committed
fix(imessage): scope downtime-recovery cursor to the watched database (#99638)
1 parent f285254 commit 3a233c8

4 files changed

Lines changed: 282 additions & 51 deletions

File tree

‎extensions/imessage/src/monitor.last-route.test.ts‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { monitorIMessageProvider } from "./monitor.js";
1010
import {
1111
advanceIMessageRecoveryCursor,
1212
loadIMessageRecoveryCursor,
13+
resolveIMessageRecoveryCursorDbIdentity,
1314
} from "./monitor/recovery-cursor.js";
1415
import {
1516
clearCachedIMessagePrivateApiStatus,
@@ -1125,7 +1126,11 @@ describe("iMessage monitor last-route updates", () => {
11251126
});
11261127

11271128
it("recovers over a remote cliPath: replays from the cursor even without a local chat.db boundary", async () => {
1128-
advanceIMessageRecoveryCursor("default", 4990);
1129+
advanceIMessageRecoveryCursor(
1130+
"default",
1131+
resolveIMessageRecoveryCursorDbIdentity({ remoteHost: "user@gateway-host" }),
1132+
4990,
1133+
);
11291134
const client = {
11301135
request: vi.fn(async () => ({ subscription: 1 })),
11311136
waitForClose: vi.fn(async () => {}),
@@ -1213,10 +1218,14 @@ describe("iMessage monitor last-route updates", () => {
12131218
});
12141219

12151220
it("recovers downtime messages: replays from the cursor and delivers replay rows older than the live fence", async () => {
1216-
advanceIMessageRecoveryCursor("default", 4990);
12171221
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-imsg-recovery-"));
12181222
tempDirs.push(stateDir);
12191223
const dbPath = path.join(stateDir, "chat.db");
1224+
advanceIMessageRecoveryCursor(
1225+
"default",
1226+
resolveIMessageRecoveryCursorDbIdentity({ dbPath }),
1227+
4990,
1228+
);
12201229
const { DatabaseSync } = await import("node:sqlite");
12211230
const database = new DatabaseSync(dbPath);
12221231
try {
@@ -1445,11 +1454,15 @@ describe("iMessage monitor last-route updates", () => {
14451454
});
14461455

14471456
it("does not advance the recovery cursor past a failed replay row", async () => {
1448-
advanceIMessageRecoveryCursor("default", 4990);
14491457
debouncerControl.holdEntries = true;
14501458
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-imsg-recovery-failed-"));
14511459
tempDirs.push(stateDir);
14521460
const dbPath = path.join(stateDir, "chat.db");
1461+
advanceIMessageRecoveryCursor(
1462+
"default",
1463+
resolveIMessageRecoveryCursorDbIdentity({ dbPath }),
1464+
4990,
1465+
);
14531466
const { DatabaseSync } = await import("node:sqlite");
14541467
const database = new DatabaseSync(dbPath);
14551468
try {
@@ -1516,15 +1529,21 @@ describe("iMessage monitor last-route updates", () => {
15161529
await vi.waitFor(() => {
15171530
expect(dispatchInboundMessageMock).toHaveBeenCalledTimes(2);
15181531
});
1519-
expect(loadIMessageRecoveryCursor("default")).toBe(4994);
1532+
expect(
1533+
loadIMessageRecoveryCursor("default", resolveIMessageRecoveryCursorDbIdentity({ dbPath })),
1534+
).toBe(4994);
15201535
});
15211536

15221537
it("advances the recovery cursor after lower pending replay rows complete", async () => {
1523-
advanceIMessageRecoveryCursor("default", 4990);
15241538
debouncerControl.holdEntries = true;
15251539
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-imsg-recovery-ordered-"));
15261540
tempDirs.push(stateDir);
15271541
const dbPath = path.join(stateDir, "chat.db");
1542+
advanceIMessageRecoveryCursor(
1543+
"default",
1544+
resolveIMessageRecoveryCursorDbIdentity({ dbPath }),
1545+
4990,
1546+
);
15281547
const { DatabaseSync } = await import("node:sqlite");
15291548
const database = new DatabaseSync(dbPath);
15301549
try {
@@ -1584,7 +1603,9 @@ describe("iMessage monitor last-route updates", () => {
15841603
await vi.waitFor(() => {
15851604
expect(dispatchInboundMessageMock).toHaveBeenCalledTimes(2);
15861605
});
1587-
expect(loadIMessageRecoveryCursor("default")).toBe(4996);
1606+
expect(
1607+
loadIMessageRecoveryCursor("default", resolveIMessageRecoveryCursorDbIdentity({ dbPath })),
1608+
).toBe(4996);
15881609
});
15891610

15901611
it("repairs anchorless group watch payloads before routing or cursor updates", async () => {

‎extensions/imessage/src/monitor/monitor-provider.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,11 @@ import { parseIMessageNotification } from "./parse-notification.js";
108108
import { createPollCommentFolder } from "./poll-comment.js";
109109
import { renderIMessagePollBody } from "./poll-render.js";
110110
import { enqueueIMessageReactionSystemEvent } from "./reaction-system-event.js";
111-
import { advanceIMessageRecoveryCursor, loadIMessageRecoveryCursor } from "./recovery-cursor.js";
111+
import {
112+
advanceIMessageRecoveryCursor,
113+
loadIMessageRecoveryCursor,
114+
resolveIMessageRecoveryCursorDbIdentity,
115+
} from "./recovery-cursor.js";
112116
import { normalizeAllowList, resolveRuntime } from "./runtime.js";
113117
import { createSelfChatCache } from "./self-chat-cache.js";
114118
import type { IMessageAttachment, IMessagePayload, MonitorIMessageOpts } from "./types.js";
@@ -542,9 +546,18 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
542546
const recoveryBoundaryRowid = watchSourceDbPath
543547
? await resolveIMessageStartupRowidWatermark(watchSourceDbPath)
544548
: null;
545-
const recoveryCursorRowid = loadIMessageRecoveryCursor(accountInfo.accountId, {
546-
migrateLegacyCatchup: !catchupCfg.enabled,
549+
// Scope the cursor to the resolved database so a dbPath/remoteHost change
550+
// starts from the new DB's watermark instead of a stale high-water (#99638).
551+
const recoveryCursorDbIdentity = resolveIMessageRecoveryCursorDbIdentity({
552+
cliPath,
553+
dbPath,
554+
remoteHost,
547555
});
556+
const recoveryCursorRowid = loadIMessageRecoveryCursor(
557+
accountInfo.accountId,
558+
recoveryCursorDbIdentity,
559+
{ migrateLegacyCatchup: !catchupCfg.enabled },
560+
);
548561
const watchSinceRowid = catchupCfg.enabled
549562
? null
550563
: recoveryCursorRowid !== null
@@ -655,7 +668,11 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
655668
holdFloor !== null && maxHandledRowid >= holdFloor ? holdFloor - 1 : maxHandledRowid;
656669

657670
if (nextCursorRowid >= 0 && nextCursorRowid > latestAdvancedRecoveryCursorRowid) {
658-
advanceIMessageRecoveryCursor(accountInfo.accountId, nextCursorRowid);
671+
advanceIMessageRecoveryCursor(
672+
accountInfo.accountId,
673+
recoveryCursorDbIdentity,
674+
nextCursorRowid,
675+
);
659676
latestAdvancedRecoveryCursorRowid = nextCursorRowid;
660677
for (const rowid of handledRecoveryCursorRowids) {
661678
if (rowid <= nextCursorRowid) {
Lines changed: 116 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,22 @@
11
// Imessage tests cover the downtime-recovery cursor.
22
import { createHash } from "node:crypto";
3+
import os from "node:os";
4+
import path from "node:path";
35
import { beforeEach, describe, expect, it } from "vitest";
46
import { getIMessageRuntime } from "../runtime.js";
57
import { installIMessageStateRuntimeForTest } from "../test-support/runtime.js";
6-
import { advanceIMessageRecoveryCursor, loadIMessageRecoveryCursor } from "./recovery-cursor.js";
8+
import {
9+
advanceIMessageRecoveryCursor,
10+
IMESSAGE_RECOVERY_CURSOR_MAX_ENTRIES,
11+
IMESSAGE_RECOVERY_CURSOR_NAMESPACE,
12+
loadIMessageRecoveryCursor,
13+
resolveIMessageRecoveryCursorDbIdentity,
14+
} from "./recovery-cursor.js";
15+
16+
// Default database identity used by tests that are not exercising the db-scoping
17+
// behavior directly.
18+
const DB = "local:/db-a";
19+
const DB_B = "local:/db-b";
720

821
function writeLegacyCatchupCursor(accountId: string, lastSeenRowid: number): void {
922
const store = getIMessageRuntime().state.openSyncKeyedStore<{
@@ -14,58 +27,140 @@ function writeLegacyCatchupCursor(accountId: string, lastSeenRowid: number): voi
1427
store.register(key, { lastSeenMs: Date.now(), lastSeenRowid });
1528
}
1629

30+
// Writes a pre-database-scoping recovery cursor: keyed by accountId alone, with
31+
// no database identity, as older builds persisted it.
32+
function writeLegacyRecoveryCursor(accountId: string, lastRowid: number): void {
33+
getIMessageRuntime()
34+
.state.openSyncKeyedStore<{ lastRowid: number }>({
35+
namespace: IMESSAGE_RECOVERY_CURSOR_NAMESPACE,
36+
maxEntries: IMESSAGE_RECOVERY_CURSOR_MAX_ENTRIES,
37+
})
38+
.register(accountId, { lastRowid });
39+
}
40+
1741
describe("iMessage recovery cursor", () => {
1842
beforeEach(() => {
1943
installIMessageStateRuntimeForTest();
2044
});
2145

2246
it("returns null before anything is recorded", () => {
23-
expect(loadIMessageRecoveryCursor("default")).toBeNull();
47+
expect(loadIMessageRecoveryCursor("default", DB)).toBeNull();
2448
});
2549

2650
it("persists the last dispatched rowid", () => {
27-
advanceIMessageRecoveryCursor("default", 100);
28-
expect(loadIMessageRecoveryCursor("default")).toBe(100);
51+
advanceIMessageRecoveryCursor("default", DB, 100);
52+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(100);
2953
});
3054

3155
it("advances forward only and never rewinds", () => {
32-
advanceIMessageRecoveryCursor("default", 100);
33-
advanceIMessageRecoveryCursor("default", 50);
34-
expect(loadIMessageRecoveryCursor("default")).toBe(100);
35-
advanceIMessageRecoveryCursor("default", 150);
36-
expect(loadIMessageRecoveryCursor("default")).toBe(150);
56+
advanceIMessageRecoveryCursor("default", DB, 100);
57+
advanceIMessageRecoveryCursor("default", DB, 50);
58+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(100);
59+
advanceIMessageRecoveryCursor("default", DB, 150);
60+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(150);
3761
});
3862

3963
it("scopes the cursor per account", () => {
40-
advanceIMessageRecoveryCursor("work", 10);
41-
advanceIMessageRecoveryCursor("home", 20);
42-
expect(loadIMessageRecoveryCursor("work")).toBe(10);
43-
expect(loadIMessageRecoveryCursor("home")).toBe(20);
64+
advanceIMessageRecoveryCursor("work", DB, 10);
65+
advanceIMessageRecoveryCursor("home", DB, 20);
66+
expect(loadIMessageRecoveryCursor("work", DB)).toBe(10);
67+
expect(loadIMessageRecoveryCursor("home", DB)).toBe(20);
68+
});
69+
70+
it("ignores a cursor recorded against a different database (#99638)", () => {
71+
// A high-water from db-a must not seed since_rowid after repointing to db-b,
72+
// or every lower rowid in db-b is silently suppressed forever.
73+
advanceIMessageRecoveryCursor("default", DB, 12396);
74+
expect(loadIMessageRecoveryCursor("default", DB_B, { migrateLegacyCatchup: false })).toBeNull();
75+
// The original database still reports its cursor.
76+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(12396);
77+
});
78+
79+
it("re-scopes the cursor to the new database on advance", () => {
80+
advanceIMessageRecoveryCursor("default", DB, 12396);
81+
// Advancing on db-b starts fresh (not blocked by db-a's higher monotonic value).
82+
advanceIMessageRecoveryCursor("default", DB_B, 15);
83+
expect(loadIMessageRecoveryCursor("default", DB_B)).toBe(15);
84+
// db-a keeps its own high-water; switching back does not lose it.
85+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(12396);
86+
});
87+
88+
it("adopts a pre-database-scoping cursor once for the active database (#99638)", () => {
89+
writeLegacyRecoveryCursor("default", 12396);
90+
// Upgrade restart: the identity-less cursor is adopted for the active
91+
// database so downtime replay still works (not dropped to the watermark).
92+
expect(loadIMessageRecoveryCursor("default", DB, { migrateLegacyCatchup: false })).toBe(12396);
93+
// It is consumed and re-scoped, so a different database does not inherit it.
94+
expect(loadIMessageRecoveryCursor("default", DB_B, { migrateLegacyCatchup: false })).toBeNull();
95+
// The adopted database keeps it across reloads.
96+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(12396);
4497
});
4598

4699
it("ignores non-finite rowids", () => {
47-
advanceIMessageRecoveryCursor("default", Number.NaN);
48-
expect(loadIMessageRecoveryCursor("default")).toBeNull();
100+
advanceIMessageRecoveryCursor("default", DB, Number.NaN);
101+
expect(loadIMessageRecoveryCursor("default", DB)).toBeNull();
49102
});
50103

51104
it("seeds from the retired catchup cursor once on upgrade, then consumes it", () => {
52105
writeLegacyCatchupCursor("default", 4321);
53106
// First load with no recovery cursor seeds from the legacy catchup cursor.
54-
expect(loadIMessageRecoveryCursor("default")).toBe(4321);
107+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(4321);
55108
// The legacy entry is consumed and the value is now the recovery cursor, so
56109
// a later load still returns it without re-reading the legacy store.
57-
expect(loadIMessageRecoveryCursor("default")).toBe(4321);
110+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(4321);
58111
});
59112

60113
it("can skip legacy catchup cursor migration when compatibility catchup still owns it", () => {
61114
writeLegacyCatchupCursor("default", 4321);
62-
expect(loadIMessageRecoveryCursor("default", { migrateLegacyCatchup: false })).toBeNull();
63-
expect(loadIMessageRecoveryCursor("default")).toBe(4321);
115+
expect(loadIMessageRecoveryCursor("default", DB, { migrateLegacyCatchup: false })).toBeNull();
116+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(4321);
64117
});
65118

66119
it("prefers an existing recovery cursor over the legacy catchup cursor", () => {
67-
advanceIMessageRecoveryCursor("default", 9000);
120+
advanceIMessageRecoveryCursor("default", DB, 9000);
68121
writeLegacyCatchupCursor("default", 10);
69-
expect(loadIMessageRecoveryCursor("default")).toBe(9000);
122+
expect(loadIMessageRecoveryCursor("default", DB)).toBe(9000);
123+
});
124+
125+
it("unifies the implicit default with explicit spellings of the same chat.db (#99638)", () => {
126+
const home = (process.env.HOME || os.homedir()).trim();
127+
const defaultIdentity = `local:${path.resolve(path.join(home, "Library", "Messages", "chat.db"))}`;
128+
129+
// Implicit default (imsg binary, no dbPath) and any explicit spelling of the
130+
// same file resolve to one identity, so switching between them does not drop
131+
// the cursor and skip downtime messages.
132+
expect(resolveIMessageRecoveryCursorDbIdentity({ cliPath: "imsg" })).toBe(defaultIdentity);
133+
expect(resolveIMessageRecoveryCursorDbIdentity({ cliPath: "/opt/homebrew/bin/imsg" })).toBe(
134+
defaultIdentity,
135+
);
136+
expect(
137+
resolveIMessageRecoveryCursorDbIdentity({
138+
dbPath: path.join(home, "Library/Messages/chat.db"),
139+
}),
140+
).toBe(defaultIdentity);
141+
expect(resolveIMessageRecoveryCursorDbIdentity({ dbPath: "~/Library/Messages/chat.db" })).toBe(
142+
defaultIdentity,
143+
);
144+
});
145+
146+
it("keeps distinct databases, wrappers, and remotes on separate identities", () => {
147+
const defaultId = resolveIMessageRecoveryCursorDbIdentity({ cliPath: "imsg" });
148+
const otherDb = resolveIMessageRecoveryCursorDbIdentity({ dbPath: "/Users/other/chat.db" });
149+
// Distinct wrappers with no dbPath/remoteHost must not collapse together.
150+
const wrapperA = resolveIMessageRecoveryCursorDbIdentity({
151+
cliPath: "/usr/local/bin/imsg-a.sh",
152+
});
153+
const wrapperB = resolveIMessageRecoveryCursorDbIdentity({
154+
cliPath: "/usr/local/bin/imsg-b.sh",
155+
});
156+
const remote = resolveIMessageRecoveryCursorDbIdentity({
157+
remoteHost: "bot@host",
158+
dbPath: "/Users/b/chat.db",
159+
});
160+
expect(new Set([defaultId, otherDb, wrapperA, wrapperB, remote]).size).toBe(5);
161+
// Stable for the same inputs.
162+
expect(otherDb).toBe(
163+
resolveIMessageRecoveryCursorDbIdentity({ dbPath: "/Users/other/chat.db" }),
164+
);
70165
});
71166
});

0 commit comments

Comments
 (0)