Compare commits

..

3 Commits

Author SHA1 Message Date
Peter Steinberger
e085433fd0 fix: harden imessage probe timeouts (#8662) (thanks @yudshj) 2026-02-04 03:25:39 -08:00
Yudong Han
09b6ea40f3 fix: address review comments
- Use optional timeoutMs parameter (undefined = use config/default)
- Extract DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS to shared constants.ts
- Import constant in client.ts instead of hardcoding
- Re-export constant from probe.ts for backwards compatibility
2026-02-04 03:19:46 -08:00
Yudong Han
a7e040459b fix(imessage): unify timeout configuration with configurable probeTimeoutMs
- Add probeTimeoutMs config option to channels.imessage
- Export DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS constant (10s) from probe.ts
- Propagate timeout config through all iMessage probe/RPC operations
- Fix hardcoded 2000ms timeouts that were too short for SSH connections

Closes: timeout issues when using SSH wrapper scripts (imsg-ssh)
2026-02-04 03:19:45 -08:00
13 changed files with 74 additions and 163 deletions

View File

@@ -17,8 +17,8 @@ Docs: https://docs.openclaw.ai
### Fixes
- iMessage: add configurable probe timeout and raise defaults for SSH probe/RPC checks. (#8662) Thanks @yudshj.
- Telegram: honor session model overrides in inline model selection. (#8193) Thanks @gildo.
- iMessage: skip echo replies using recent outbound IDs before falling back to text matching. (#8680) Thanks @Iranb.
- Web UI: resolve header logo path when `gateway.controlUi.basePath` is set. (#7178) Thanks @Yeom-JinHo.
- Web UI: apply button styling to the new-messages indicator.
- Security: keep untrusted channel metadata out of system prompts (Slack/Discord). Thanks @KonstantinMirin.

View File

@@ -190,6 +190,7 @@ Notes:
- Ensure the Mac is signed in to Messages, and Remote Login is enabled.
- Use SSH keys so `ssh bot@mac-mini.tailnet-1234.ts.net` works without prompts.
- `remoteHost` should match the SSH target so SCP can fetch attachments.
- If SSH probes time out, set `channels.imessage.probeTimeoutMs` (default: 10000).
Multi-account support: use `channels.imessage.accounts` with per-account config and optional `name`. See [`gateway/configuration`](/gateway/configuration#telegramaccounts--discordaccounts--slackaccounts--signalaccounts--imessageaccounts) for the shared pattern. Don't commit `~/.openclaw/openclaw.json` (it often contains tokens).

View File

@@ -370,6 +370,7 @@ const FIELD_LABELS: Record<string, string> = {
"channels.mattermost.requireMention": "Mattermost Require Mention",
"channels.signal.account": "Signal Account",
"channels.imessage.cliPath": "iMessage CLI Path",
"channels.imessage.probeTimeoutMs": "iMessage Probe Timeout (ms)",
"agents.list[].skills": "Agent Skill Filter",
"agents.list[].identity.avatar": "Agent Avatar",
"discovery.mdns.mode": "mDNS Discovery Mode",
@@ -679,6 +680,8 @@ const FIELD_HELP: Record<string, string> = {
"Allow Signal to write config in response to channel events/commands (default: true).",
"channels.imessage.configWrites":
"Allow iMessage to write config in response to channel events/commands (default: true).",
"channels.imessage.probeTimeoutMs":
"Timeout in ms for iMessage probe/RPC checks (default: 10000).",
"channels.msteams.configWrites":
"Allow Microsoft Teams to write config in response to channel events/commands (default: true).",
"channels.discord.commands.native": 'Override native commands for Discord (bool or "auto").',

View File

@@ -52,6 +52,8 @@ export type IMessageAccountConfig = {
includeAttachments?: boolean;
/** Max outbound media size in MB. */
mediaMaxMb?: number;
/** Timeout for probe/RPC operations in milliseconds (default: 10000). */
probeTimeoutMs?: number;
/** Outbound text chunk size (chars). Default: 4000. */
textChunkLimit?: number;
/** Chunking mode: "length" (default) splits by size; "newline" splits on every newline. */

View File

@@ -623,6 +623,7 @@ export const IMessageAccountSchemaBase = z
cliPath: ExecutableTokenSchema.optional(),
dbPath: z.string().optional(),
remoteHost: z.string().optional(),
probeTimeoutMs: z.number().int().positive().optional(),
service: z.union([z.literal("imessage"), z.literal("sms"), z.literal("auto")]).optional(),
region: z.string().optional(),
dmPolicy: DmPolicySchema.optional().default("pairing"),

View File

@@ -2,6 +2,7 @@ import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { createInterface, type Interface } from "node:readline";
import type { RuntimeEnv } from "../runtime.js";
import { resolveUserPath } from "../utils.js";
import { DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS } from "./constants.js";
export type IMessageRpcError = {
code?: number;
@@ -149,7 +150,7 @@ export class IMessageRpcClient {
params: params ?? {},
};
const line = `${JSON.stringify(payload)}\n`;
const timeoutMs = opts?.timeoutMs ?? 10_000;
const timeoutMs = opts?.timeoutMs ?? DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS;
const response = new Promise<T>((resolve, reject) => {
const key = String(id);

View File

@@ -0,0 +1,2 @@
/** Default timeout for iMessage probe/RPC operations (10 seconds). */
export const DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS = 10_000;

View File

@@ -101,47 +101,6 @@ beforeEach(() => {
});
describe("monitorIMessageProvider", () => {
it("skips echo messages that match recent outbound ids", async () => {
sendMock.mockResolvedValue({ messageId: "123" });
const run = monitorIMessageProvider();
await waitForSubscribe();
notificationHandler?.({
method: "message",
params: {
message: {
id: 1,
sender: "+15550001111",
is_from_me: false,
text: "ping",
is_group: false,
},
},
});
await flush();
notificationHandler?.({
method: "message",
params: {
message: {
id: 123,
sender: "+15550001111",
is_from_me: false,
text: "ok",
is_group: false,
},
},
});
await flush();
closeResolve?.();
await run;
expect(replyMock).toHaveBeenCalledTimes(1);
expect(sendMock).toHaveBeenCalledTimes(1);
});
it("skips group messages without a mention by default", async () => {
const run = monitorIMessageProvider();
await waitForSubscribe();

View File

@@ -6,7 +6,6 @@ import { loadConfig } from "../../config/config.js";
import { resolveMarkdownTableMode } from "../../config/markdown-tables.js";
import { convertMarkdownTables } from "../../markdown/tables.js";
import { sendMessageIMessage } from "../send.js";
import { buildIMessageEchoScope, type SentMessageCache } from "./echo-cache.js";
export async function deliverReplies(params: {
replies: ReplyPayload[];
@@ -16,11 +15,8 @@ export async function deliverReplies(params: {
runtime: RuntimeEnv;
maxBytes: number;
textLimit: number;
sentMessageCache?: SentMessageCache;
}) {
const { replies, target, client, runtime, maxBytes, textLimit, accountId, sentMessageCache } =
params;
const scope = buildIMessageEchoScope({ accountId, target });
const { replies, target, client, runtime, maxBytes, textLimit, accountId } = params;
const cfg = loadConfig();
const tableMode = resolveMarkdownTableMode({
cfg,
@@ -37,29 +33,23 @@ export async function deliverReplies(params: {
}
if (mediaList.length === 0) {
for (const chunk of chunkTextWithMode(text, textLimit, chunkMode)) {
const result = await sendMessageIMessage(target, chunk, {
await sendMessageIMessage(target, chunk, {
maxBytes,
client,
accountId,
});
sentMessageCache?.rememberText(scope, chunk);
sentMessageCache?.rememberId(scope, result.messageId);
}
} else {
let first = true;
for (const url of mediaList) {
const caption = first ? text : "";
first = false;
const result = await sendMessageIMessage(target, caption, {
await sendMessageIMessage(target, caption, {
mediaUrl: url,
maxBytes,
client,
accountId,
});
if (caption) {
sentMessageCache?.rememberText(scope, caption);
}
sentMessageCache?.rememberId(scope, result.messageId);
}
}
runtime.log?.(`imessage: delivered reply to ${target}`);

View File

@@ -1,78 +0,0 @@
export function buildIMessageEchoScope(params: {
accountId?: string | null;
target: string;
}): string {
return `${params.accountId ?? ""}:${params.target}`;
}
type CacheEntry = Map<string, number>;
export class SentMessageCache {
private readonly ttlMs: number;
private readonly textCache: CacheEntry = new Map();
private readonly idCache: CacheEntry = new Map();
constructor(opts: { ttlMs?: number } = {}) {
this.ttlMs = opts.ttlMs ?? 5000;
}
rememberText(scope: string, text: string): void {
const trimmed = text?.trim?.() ?? "";
if (!trimmed) {
return;
}
this.textCache.set(this.buildKey(scope, trimmed), Date.now());
this.cleanup(this.textCache);
}
rememberId(scope: string, id: string | number): void {
const normalized = String(id ?? "").trim();
if (!normalized || normalized === "ok" || normalized === "unknown") {
return;
}
this.idCache.set(this.buildKey(scope, normalized), Date.now());
this.cleanup(this.idCache);
}
hasText(scope: string, text: string): boolean {
const trimmed = text?.trim?.() ?? "";
if (!trimmed) {
return false;
}
return this.has(scope, trimmed, this.textCache);
}
hasId(scope: string, id: string | number): boolean {
const normalized = String(id ?? "").trim();
if (!normalized) {
return false;
}
return this.has(scope, normalized, this.idCache);
}
private has(scope: string, value: string, cache: CacheEntry): boolean {
const key = this.buildKey(scope, value);
const timestamp = cache.get(key);
if (!timestamp) {
return false;
}
if (Date.now() - timestamp > this.ttlMs) {
cache.delete(key);
return false;
}
return true;
}
private buildKey(scope: string, value: string): string {
return `${scope}:${value}`;
}
private cleanup(cache: CacheEntry): void {
const now = Date.now();
for (const [key, timestamp] of cache.entries()) {
if (now - timestamp > this.ttlMs) {
cache.delete(key);
}
}
}
}

View File

@@ -45,6 +45,7 @@ import { resolveAgentRoute } from "../../routing/resolve-route.js";
import { truncateUtf16Safe } from "../../utils.js";
import { resolveIMessageAccount } from "../accounts.js";
import { createIMessageRpcClient } from "../client.js";
import { DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS } from "../constants.js";
import { probeIMessage } from "../probe.js";
import { sendMessageIMessage } from "../send.js";
import {
@@ -53,7 +54,6 @@ import {
normalizeIMessageHandle,
} from "../targets.js";
import { deliverReplies } from "./deliver.js";
import { buildIMessageEchoScope, SentMessageCache } from "./echo-cache.js";
import { normalizeAllowList, resolveRuntime } from "./runtime.js";
/**
@@ -126,7 +126,6 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
DEFAULT_GROUP_HISTORY_LIMIT,
);
const groupHistories = new Map<string, HistoryEntry[]>();
const sentMessageCache = new SentMessageCache();
const textLimit = resolveTextChunkLimit(cfg, "imessage", accountInfo.accountId);
const allowFrom = normalizeAllowList(opts.allowFrom ?? imessageCfg.allowFrom);
const groupAllowFrom = normalizeAllowList(
@@ -141,6 +140,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
const mediaMaxBytes = (opts.mediaMaxMb ?? imessageCfg.mediaMaxMb ?? 16) * 1024 * 1024;
const cliPath = opts.cliPath ?? imessageCfg.cliPath ?? "imsg";
const dbPath = opts.dbPath ?? imessageCfg.dbPath;
const probeTimeoutMs = imessageCfg.probeTimeoutMs ?? DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS;
// Resolve remoteHost: explicit config, or auto-detect from SSH wrapper script
let remoteHost = imessageCfg.remoteHost;
@@ -346,26 +346,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
},
});
const mentionRegexes = buildMentionRegexes(cfg, route.agentId);
const chatTarget = isGroup ? formatIMessageChatTarget(chatId) : undefined;
const messageText = (message.text ?? "").trim();
const messageId = message.id ?? undefined;
const echoScope = buildIMessageEchoScope({
accountId: accountInfo.accountId,
target: chatTarget ?? `imessage:${sender}`,
});
if (messageId !== undefined && sentMessageCache.hasId(echoScope, messageId)) {
logVerbose(
`imessage: skipping echo message (matches recently sent id within 5s): ${String(messageId)}`,
);
return;
}
if (messageText && sentMessageCache.hasText(echoScope, messageText)) {
logVerbose(
`imessage: skipping echo message (matches recently sent text within 5s): "${truncateUtf16Safe(messageText, 50)}"`,
);
return;
}
const attachments = includeAttachments ? (message.attachments ?? []) : [];
// Filter to valid attachments with paths
const validAttachments = attachments.filter((entry) => entry?.original_path && !entry?.missing);
@@ -458,6 +439,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
return;
}
const chatTarget = formatIMessageChatTarget(chatId);
const fromLabel = formatInboundFromLabel({
isGroup,
groupLabel: message.chat_name ?? undefined,
@@ -586,7 +568,6 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
runtime,
maxBytes: mediaMaxBytes,
textLimit,
sentMessageCache,
});
},
onError: (err, info) => {
@@ -639,7 +620,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
abortSignal: opts.abortSignal,
runtime,
check: async () => {
const probe = await probeIMessage(2000, { cliPath, dbPath, runtime });
const probe = await probeIMessage(probeTimeoutMs, { cliPath, dbPath, runtime });
if (probe.ok) {
return { ok: true };
}

View File

@@ -1,14 +1,18 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { probeIMessage } from "./probe.js";
const detectBinaryMock = vi.hoisted(() => vi.fn());
const runCommandWithTimeoutMock = vi.hoisted(() => vi.fn());
const createIMessageRpcClientMock = vi.hoisted(() => vi.fn());
const loadConfigMock = vi.hoisted(() => vi.fn());
vi.mock("../commands/onboard-helpers.js", () => ({
detectBinary: (...args: unknown[]) => detectBinaryMock(...args),
}));
vi.mock("../config/config.js", () => ({
loadConfig: (...args: unknown[]) => loadConfigMock(...args),
}));
vi.mock("../process/exec.js", () => ({
runCommandWithTimeout: (...args: unknown[]) => runCommandWithTimeoutMock(...args),
}));
@@ -18,6 +22,7 @@ vi.mock("./client.js", () => ({
}));
beforeEach(() => {
vi.resetModules();
detectBinaryMock.mockReset().mockResolvedValue(true);
runCommandWithTimeoutMock.mockReset().mockResolvedValue({
stdout: "",
@@ -27,14 +32,45 @@ beforeEach(() => {
killed: false,
});
createIMessageRpcClientMock.mockReset();
loadConfigMock.mockReset().mockReturnValue({});
});
describe("probeIMessage", () => {
it("marks unknown rpc subcommand as fatal", async () => {
const { probeIMessage } = await import("./probe.js");
const result = await probeIMessage(1000, { cliPath: "imsg" });
expect(result.ok).toBe(false);
expect(result.fatal).toBe(true);
expect(result.error).toMatch(/rpc/i);
expect(createIMessageRpcClientMock).not.toHaveBeenCalled();
});
it("uses config probeTimeoutMs when not explicitly provided", async () => {
const requestMock = vi.fn().mockResolvedValue({});
createIMessageRpcClientMock.mockResolvedValue({
request: requestMock,
stop: vi.fn().mockResolvedValue(undefined),
});
runCommandWithTimeoutMock.mockResolvedValue({
stdout: "",
stderr: "",
code: 0,
signal: null,
killed: false,
});
loadConfigMock.mockReturnValue({
channels: {
imessage: {
probeTimeoutMs: 15_000,
},
},
});
const { probeIMessage } = await import("./probe.js");
const result = await probeIMessage();
expect(result.ok).toBe(true);
expect(runCommandWithTimeoutMock).toHaveBeenCalledWith(["imsg", "rpc", "--help"], {
timeoutMs: 15_000,
});
expect(requestMock).toHaveBeenCalledWith("chats.list", { limit: 1 }, { timeoutMs: 15_000 });
});
});

View File

@@ -3,6 +3,10 @@ import { detectBinary } from "../commands/onboard-helpers.js";
import { loadConfig } from "../config/config.js";
import { runCommandWithTimeout } from "../process/exec.js";
import { createIMessageRpcClient } from "./client.js";
import { DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS } from "./constants.js";
// Re-export for backwards compatibility
export { DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS } from "./constants.js";
export type IMessageProbe = {
ok: boolean;
@@ -24,13 +28,13 @@ type RpcSupportResult = {
const rpcSupportCache = new Map<string, RpcSupportResult>();
async function probeRpcSupport(cliPath: string): Promise<RpcSupportResult> {
async function probeRpcSupport(cliPath: string, timeoutMs: number): Promise<RpcSupportResult> {
const cached = rpcSupportCache.get(cliPath);
if (cached) {
return cached;
}
try {
const result = await runCommandWithTimeout([cliPath, "rpc", "--help"], { timeoutMs: 2000 });
const result = await runCommandWithTimeout([cliPath, "rpc", "--help"], { timeoutMs });
const combined = `${result.stdout}\n${result.stderr}`.trim();
const normalized = combined.toLowerCase();
if (normalized.includes("unknown command") && normalized.includes("rpc")) {
@@ -56,19 +60,28 @@ async function probeRpcSupport(cliPath: string): Promise<RpcSupportResult> {
}
}
/**
* Probe iMessage RPC availability.
* @param timeoutMs - Explicit timeout in ms. If undefined, uses config or default.
* @param opts - Additional options (cliPath, dbPath, runtime).
*/
export async function probeIMessage(
timeoutMs = 2000,
timeoutMs?: number,
opts: IMessageProbeOptions = {},
): Promise<IMessageProbe> {
const cfg = opts.cliPath || opts.dbPath ? undefined : loadConfig();
const cliPath = opts.cliPath?.trim() || cfg?.channels?.imessage?.cliPath?.trim() || "imsg";
const dbPath = opts.dbPath?.trim() || cfg?.channels?.imessage?.dbPath?.trim();
// Use explicit timeout if provided, otherwise fall back to config, then default
const effectiveTimeout =
timeoutMs ?? cfg?.channels?.imessage?.probeTimeoutMs ?? DEFAULT_IMESSAGE_PROBE_TIMEOUT_MS;
const detected = await detectBinary(cliPath);
if (!detected) {
return { ok: false, error: `imsg not found (${cliPath})` };
}
const rpcSupport = await probeRpcSupport(cliPath);
const rpcSupport = await probeRpcSupport(cliPath, effectiveTimeout);
if (!rpcSupport.supported) {
return {
ok: false,
@@ -83,7 +96,7 @@ export async function probeIMessage(
runtime: opts.runtime,
});
try {
await client.request("chats.list", { limit: 1 }, { timeoutMs });
await client.request("chats.list", { limit: 1 }, { timeoutMs: effectiveTimeout });
return { ok: true };
} catch (err) {
return { ok: false, error: String(err) };