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
10 changed files with 70 additions and 8 deletions

View File

@@ -17,6 +17,7 @@ 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.
- 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.

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

@@ -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 {
@@ -139,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;
@@ -618,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) };