Skip to content

Commit 7cdda72

Browse files
authored
fix(imessage): avoid loading channel runtime during doctor checks (#132435)
Keep configuration repair and legacy-state detection dependency-light by sharing existing cache contracts and using the narrow account-resolution SDK. Preserve storage keys, limits, TTLs and migration behavior. Independent iMessage follow-up to the CLI startup preparation repair in #131503.
1 parent 9ffd930 commit 7cdda72

13 files changed

Lines changed: 301 additions & 162 deletions

‎extensions/imessage/doctor-contract-api.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,32 @@
11
// Imessage tests cover doctor contract api plugin behavior.
22
import { expectDefined } from "@openclaw/normalization-core";
33
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
4-
import { describe, expect, it } from "vitest";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
55
import { legacyConfigRules, normalizeCompatibilityConfig } from "./doctor-contract-api.js";
66

77
function imessageConfig(entry: Record<string, unknown>): OpenClawConfig {
88
return { channels: { imessage: entry } } as never;
99
}
1010

11+
describe("imessage doctor control plane", () => {
12+
afterEach(() => {
13+
vi.doUnmock("./src/state-migrations.js");
14+
vi.resetModules();
15+
});
16+
17+
it("repairs config without loading state migration implementation", async () => {
18+
vi.resetModules();
19+
vi.doMock("./src/state-migrations.js", () => {
20+
throw new Error("config repair must not load state migration implementation");
21+
});
22+
const doctor = await import("./doctor-contract-api.js");
23+
const result = doctor.normalizeCompatibilityConfig({
24+
cfg: imessageConfig({ chunkMode: "newline" }),
25+
});
26+
expect(result.config.channels?.imessage).toEqual({ streaming: { chunkMode: "newline" } });
27+
});
28+
});
29+
1130
describe("imessage streaming legacy config rules", () => {
1231
const rootRule = legacyConfigRules.find(
1332
(rule) => rule.path.join(".") === "channels.imessage" && rule.message.includes("chunkMode"),

‎extensions/imessage/doctor-contract-api.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import {
99
definePluginDoctorMigrationFromPlans,
1010
} from "openclaw/plugin-sdk/runtime-doctor-migrations";
1111
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
12-
import { detectIMessageLegacyStateMigrations } from "./src/state-migrations.js";
1312

1413
// Disabled `channels.imessage.catchup` blocks are retired. Enabled blocks stay
1514
// as a compatibility contract: older configs that opted into replay still get
@@ -111,6 +110,11 @@ export const stateMigrations = [
111110
definePluginDoctorMigrationFromPlans({
112111
id: "imessage-legacy-state",
113112
label: "iMessage legacy state",
114-
resolvePlans: detectIMessageLegacyStateMigrations,
113+
// Config repair enumerates this artifact too; load the detector only when
114+
// detection or migration resolves plans.
115+
resolvePlans: async (params) => {
116+
const { detectIMessageLegacyStateMigrations } = await import("./src/state-migrations.js");
117+
return detectIMessageLegacyStateMigrations(params);
118+
},
115119
}),
116120
];

‎extensions/imessage/src/accounts.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ import { statSync } from "node:fs";
22
import path from "node:path";
33
import { createAccountListHelpers } from "openclaw/plugin-sdk/account-helpers";
44
import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk/account-id";
5-
import { normalizeAccountId, type OpenClawConfig } from "openclaw/plugin-sdk/account-resolution";
6-
// Imessage plugin module implements accounts behavior.
5+
import {
6+
normalizeAccountId,
7+
resolveAccountEntry,
8+
type OpenClawConfig,
9+
} from "openclaw/plugin-sdk/account-resolution";
710
import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
8-
import { resolveAccountEntry } from "openclaw/plugin-sdk/routing";
911
import {
1012
asOptionalRecord,
1113
normalizeOptionalString,

‎extensions/imessage/src/monitor-reply-cache.ts‎

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
// Imessage plugin module implements monitor reply cache behavior.
2-
import { createHash } from "node:crypto";
31
import type { PluginStateSyncKeyedStore } from "openclaw/plugin-sdk/plugin-state-runtime";
42
import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
53
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
@@ -9,15 +7,18 @@ import {
97
type IMessageChatContext,
108
} from "./chat-context.js";
119
import { getIMessageRuntime } from "./runtime.js";
10+
import {
11+
IMESSAGE_REPLY_CACHE_NAMESPACE,
12+
IMESSAGE_REPLY_CACHE_MAX_ENTRIES,
13+
IMESSAGE_REPLY_CACHE_COUNTER_NAMESPACE,
14+
IMESSAGE_REPLY_CACHE_COUNTER_MAX_ENTRIES,
15+
IMESSAGE_REPLY_CACHE_COUNTER_KEY,
16+
IMESSAGE_REPLY_CACHE_TTL_MS,
17+
resolveIMessageReplyCacheEntryKey,
18+
} from "./state-contract.js";
1219

1320
export type { IMessageChatContext } from "./chat-context.js";
1421

15-
export const IMESSAGE_REPLY_CACHE_NAMESPACE = "imessage.reply-cache";
16-
export const IMESSAGE_REPLY_CACHE_MAX_ENTRIES = 2000;
17-
export const IMESSAGE_REPLY_CACHE_COUNTER_NAMESPACE = "imessage.reply-cache-counter";
18-
export const IMESSAGE_REPLY_CACHE_COUNTER_MAX_ENTRIES = 1;
19-
export const IMESSAGE_REPLY_CACHE_COUNTER_KEY = "short-id-counter";
20-
const REPLY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
2122
/** Recency window for the "react to the latest message" fallback. */
2223
const LATEST_FALLBACK_MS = 10 * 60 * 1000;
2324
let persistenceFailureLogged = false;
@@ -60,10 +61,6 @@ const imessageShortIdToUuid = new Map<string, string>();
6061
const imessageUuidToShortId = new Map<string, string>();
6162
let imessageShortIdCounter = 0;
6263

63-
export function resolveIMessageReplyCacheEntryKey(messageId: string): string {
64-
return createHash("sha256").update(messageId, "utf8").digest("hex").slice(0, 32);
65-
}
66-
6764
function openReplyCacheStore(): IMessageReplyCacheStore {
6865
return getIMessageRuntime().state.openSyncKeyedStore<IMessageReplyCacheEntry>({
6966
namespace: IMESSAGE_REPLY_CACHE_NAMESPACE,
@@ -79,7 +76,7 @@ function openReplyCacheCounterStore(): PluginStateSyncKeyedStore<IMessageReplyCa
7976
}
8077

8178
function remainingTtlMs(timestamp: number): number | undefined {
82-
const remaining = REPLY_CACHE_TTL_MS - Math.max(0, Date.now() - timestamp);
79+
const remaining = IMESSAGE_REPLY_CACHE_TTL_MS - Math.max(0, Date.now() - timestamp);
8380
return remaining > 0 ? remaining : undefined;
8481
}
8582

@@ -89,7 +86,7 @@ function hydrateFromStoreOnce(): void {
8986
return;
9087
}
9188
hydrated = true;
92-
const cutoff = Date.now() - REPLY_CACHE_TTL_MS;
89+
const cutoff = Date.now() - IMESSAGE_REPLY_CACHE_TTL_MS;
9390
let entries: IMessageReplyCacheEntry[];
9491
try {
9592
const counter = openReplyCacheCounterStore().lookup(IMESSAGE_REPLY_CACHE_COUNTER_KEY);
@@ -198,7 +195,7 @@ export function rememberIMessageReplyCache(
198195
imessageReplyCacheByMessageId.delete(messageId);
199196
imessageReplyCacheByMessageId.set(messageId, fullEntry);
200197

201-
const cutoff = Date.now() - REPLY_CACHE_TTL_MS;
198+
const cutoff = Date.now() - IMESSAGE_REPLY_CACHE_TTL_MS;
202199
let evicted = false;
203200
const deletedMessageIds: string[] = [];
204201
for (const [key, value] of imessageReplyCacheByMessageId) {
@@ -446,7 +443,7 @@ export function resolveIMessageCachedResourceBinding(
446443
if (!entry) {
447444
return "unknown";
448445
}
449-
if (Date.now() - entry.timestamp > REPLY_CACHE_TTL_MS) {
446+
if (Date.now() - entry.timestamp > IMESSAGE_REPLY_CACHE_TTL_MS) {
450447
return "unknown";
451448
}
452449
if (entry.accountId !== ctx.accountId) {

‎extensions/imessage/src/monitor/catchup-bridge.test-support.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
// Imessage test support covers catchup bridge plugin behavior.
22
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
33
import { getIMessageRuntime } from "../runtime.js";
4-
import { installIMessageStateRuntimeForTest } from "../test-support/runtime.js";
5-
import { runIMessageCatchup } from "./catchup-bridge.js";
64
import {
75
IMESSAGE_CATCHUP_CURSOR_MAX_ENTRIES,
86
IMESSAGE_CATCHUP_CURSOR_NAMESPACE,
9-
resolveCatchupConfig,
107
resolveIMessageCatchupCursorKey,
118
type IMessageCatchupCursor,
12-
} from "./catchup.js";
9+
} from "../state-contract.js";
10+
import { installIMessageStateRuntimeForTest } from "../test-support/runtime.js";
11+
import { runIMessageCatchup } from "./catchup-bridge.js";
12+
import { resolveCatchupConfig } from "./catchup.js";
1313
import type { IMessagePayload } from "./types.js";
1414

1515
type RpcCall = {

‎extensions/imessage/src/monitor/catchup.test-support.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
11
// Imessage tests cover catchup plugin behavior.
22
import { beforeEach, describe, expect, it, vi } from "vitest";
33
import { getIMessageRuntime } from "../runtime.js";
4-
import { installIMessageStateRuntimeForTest } from "../test-support/runtime.js";
54
import {
6-
advanceIMessageCatchupCursor,
75
capFailureRetriesMap,
86
IMESSAGE_CATCHUP_CURSOR_MAX_ENTRIES,
97
IMESSAGE_CATCHUP_CURSOR_NAMESPACE,
8+
resolveIMessageCatchupCursorKey,
9+
type IMessageCatchupCursor,
10+
} from "../state-contract.js";
11+
import { installIMessageStateRuntimeForTest } from "../test-support/runtime.js";
12+
import {
13+
advanceIMessageCatchupCursor,
1014
performIMessageCatchup,
1115
resolveCatchupConfig,
12-
resolveIMessageCatchupCursorKey,
1316
type CatchupDispatchFn,
1417
type CatchupFetchFn,
15-
type IMessageCatchupCursor,
1618
type IMessageCatchupRow,
1719
} from "./catchup.js";
1820

‎extensions/imessage/src/monitor/catchup.ts‎

Lines changed: 7 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1-
// Imessage plugin module implements catchup behavior.
2-
import { createHash } from "node:crypto";
31
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
42
import { resolveIntegerOption } from "openclaw/plugin-sdk/number-runtime";
53
import type { PluginStateSyncKeyedStore } from "openclaw/plugin-sdk/plugin-state-runtime";
64
import { getIMessageRuntime } from "../runtime.js";
5+
import {
6+
IMESSAGE_CATCHUP_CURSOR_NAMESPACE,
7+
IMESSAGE_CATCHUP_CURSOR_MAX_ENTRIES,
8+
resolveIMessageCatchupCursorKey,
9+
capFailureRetriesMap,
10+
type IMessageCatchupCursor,
11+
} from "../state-contract.js";
712

813
// iMessage inbound catchup. When the gateway is offline (crash, restart, mac
914
// sleep, machine off), `imsg watch` resumes from current state and ignores
@@ -24,13 +29,6 @@ const MAX_PER_RUN_LIMIT = 500;
2429
const DEFAULT_FIRST_RUN_LOOKBACK_MINUTES = 30;
2530
const DEFAULT_MAX_FAILURE_RETRIES = 10;
2631
const MAX_MAX_FAILURE_RETRIES = 1_000;
27-
// Defense-in-depth bound on the retry map. The cursor is one plugin-state
28-
// value, so keep the retry payload well below the 64KB store limit.
29-
const MAX_FAILURE_RETRY_MAP_SIZE = 512;
30-
const MAX_FAILURE_RETRY_MAP_JSON_BYTES = 48_000;
31-
const textEncoder = new TextEncoder();
32-
export const IMESSAGE_CATCHUP_CURSOR_NAMESPACE = "imessage.catchup-cursors";
33-
export const IMESSAGE_CATCHUP_CURSOR_MAX_ENTRIES = 256;
3432
const cursorWriteQueue = new KeyedAsyncQueue();
3533

3634
type IMessageCatchupConfig = {
@@ -41,28 +39,6 @@ type IMessageCatchupConfig = {
4139
maxFailureRetries?: number;
4240
};
4341

44-
export type IMessageCatchupCursor = {
45-
/** Timestamp (ms since epoch) of the highest-watermark message we processed. */
46-
lastSeenMs: number;
47-
/** ROWID of the highest-watermark processed message. Monotonic in chat.db. */
48-
lastSeenRowid: number;
49-
/** UTC ms timestamp of the most recent cursor write. */
50-
updatedAt: number;
51-
/**
52-
* Per-GUID failure counter, preserved across runs. Two states:
53-
* - `1 <= count < maxFailureRetries`: the GUID is still retrying and
54-
* continues to hold the cursor back.
55-
* - `count >= maxFailureRetries`: catchup has given up on the GUID. The
56-
* message is skipped on sight (no dispatch attempt) and the cursor no
57-
* longer waits on it. Entry stays in the map until the cursor naturally
58-
* advances past the message's timestamp.
59-
*
60-
* A successful dispatch removes the entry. Optional on the persisted shape
61-
* so older cursor files without this field load cleanly.
62-
*/
63-
failureRetries?: Record<string, number>;
64-
};
65-
6642
export type IMessageCatchupRow = {
6743
guid: string;
6844
rowid: number;
@@ -97,10 +73,6 @@ export type IMessageCatchupSummary = {
9773
windowEndMs: number;
9874
};
9975

100-
export function resolveIMessageCatchupCursorKey(accountId: string): string {
101-
return createHash("sha256").update(accountId, "utf8").digest("hex").slice(0, 32);
102-
}
103-
10476
function openCatchupCursorStore(): PluginStateSyncKeyedStore<IMessageCatchupCursor> {
10577
return getIMessageRuntime().state.openSyncKeyedStore<IMessageCatchupCursor>({
10678
namespace: IMESSAGE_CATCHUP_CURSOR_NAMESPACE,
@@ -209,35 +181,6 @@ async function saveIMessageCatchupCursor(
209181
});
210182
}
211183

212-
/**
213-
* Bound the retry map so a pathological storm of unique failing GUIDs
214-
* cannot grow the cursor file without limit. Keeps the `maxSize` entries
215-
* with the highest counts (closest to give-up) when over the bound.
216-
*/
217-
export function capFailureRetriesMap(
218-
map: Record<string, number>,
219-
maxSize: number = MAX_FAILURE_RETRY_MAP_SIZE,
220-
maxBytes: number = MAX_FAILURE_RETRY_MAP_JSON_BYTES,
221-
): Record<string, number> {
222-
const entries = Object.entries(map);
223-
if (entries.length <= maxSize && textEncoder.encode(JSON.stringify(map)).byteLength <= maxBytes) {
224-
return map;
225-
}
226-
// Sort by count desc; stable tiebreak on guid string so the retained set
227-
// is deterministic across runs (important for cursor-file diffing during
228-
// debugging).
229-
entries.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
230-
const capped: Record<string, number> = {};
231-
for (const [guid, count] of entries.slice(0, maxSize)) {
232-
capped[guid] = count;
233-
if (textEncoder.encode(JSON.stringify(capped)).byteLength > maxBytes) {
234-
delete capped[guid];
235-
break;
236-
}
237-
}
238-
return capped;
239-
}
240-
241184
export type ResolvedCatchupConfig = {
242185
enabled: boolean;
243186
maxAgeMinutes: number;

‎extensions/imessage/src/monitor/echo-cache.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import type { MediaPlaceholderTextFact } from "openclaw/plugin-sdk/channel-inbound";
2+
import { resolveIMessageEchoMediaKey } from "../state-contract.js";
23
// Imessage plugin module implements echo cache behavior.
34
import { stripLeadingEchoTextCorruptionMarkers } from "./echo-text-corruption.js";
4-
import { hasPersistedIMessageEcho, resolveIMessageEchoMediaKey } from "./persisted-echo-cache.js";
5+
import { hasPersistedIMessageEcho } from "./persisted-echo-cache.js";
56

67
type SentMessageLookup = {
78
text?: string;

‎extensions/imessage/src/monitor/monitor-provider.echo-cache.test-support.ts‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
// Imessage test support covers monitor provider.echo cache plugin behavior.
22
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import {
4+
IMESSAGE_SENT_ECHOES_MAX_ENTRIES,
5+
IMESSAGE_SENT_ECHOES_NAMESPACE,
6+
IMESSAGE_SENT_ECHOES_TTL_MS,
7+
resolveIMessageSentEchoEntryKey,
8+
} from "../state-contract.js";
39
import {
410
createIMessagePluginStateSyncStoreForTest,
511
installIMessageFailingStateRuntimeForTest,
612
installIMessageStateRuntimeForTest,
713
} from "../test-support/runtime.js";
814
import { createSentMessageCache } from "./echo-cache.js";
9-
import {
10-
IMESSAGE_SENT_ECHOES_MAX_ENTRIES,
11-
IMESSAGE_SENT_ECHOES_NAMESPACE,
12-
IMESSAGE_SENT_ECHOES_TTL_MS,
13-
hasPersistedIMessageEcho,
14-
rememberPersistedIMessageEcho,
15-
resolveIMessageSentEchoEntryKey,
16-
} from "./persisted-echo-cache.js";
15+
import { hasPersistedIMessageEcho, rememberPersistedIMessageEcho } from "./persisted-echo-cache.js";
1716

1817
describe("iMessage sent-message echo cache", () => {
1918
beforeEach(() => {

0 commit comments

Comments
 (0)