Skip to content

Commit 3dd3003

Browse files
fix(status): retry status runtime loads and contain render errors (Fixes #94626) (#94806)
1 parent 4d00dc4 commit 3dd3003

4 files changed

Lines changed: 199 additions & 26 deletions

File tree

‎src/auto-reply/reply/commands-status.test.ts‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2329,6 +2329,117 @@ describe("buildStatusReply subagent summary", () => {
23292329
expect(normalizeTestText(text)).toContain("Runtime: OpenAI Codex");
23302330
});
23312331
});
2332+
2333+
describe("buildStatusReply error handling", () => {
2334+
afterEach(() => {
2335+
vi.doUnmock("../../logger.js");
2336+
vi.doUnmock("../../status/status-text.js");
2337+
vi.resetModules();
2338+
vi.restoreAllMocks();
2339+
});
2340+
2341+
async function runStatusReply(fn: typeof buildStatusReply) {
2342+
const commandParams = buildCommandTestParams("/status", baseCfg);
2343+
return await fn({
2344+
cfg: baseCfg,
2345+
command: commandParams.command,
2346+
sessionEntry: commandParams.sessionEntry,
2347+
sessionKey: commandParams.sessionKey,
2348+
parentSessionKey: commandParams.sessionKey,
2349+
sessionScope: commandParams.sessionScope,
2350+
storePath: commandParams.storePath,
2351+
provider: "anthropic",
2352+
model: "claude-opus-4-6",
2353+
contextTokens: 0,
2354+
resolvedThinkLevel: commandParams.resolvedThinkLevel,
2355+
resolvedFastMode: false,
2356+
resolvedVerboseLevel: commandParams.resolvedVerboseLevel,
2357+
resolvedReasoningLevel: commandParams.resolvedReasoningLevel,
2358+
resolvedElevatedLevel: commandParams.resolvedElevatedLevel,
2359+
resolveDefaultThinkingLevel: commandParams.resolveDefaultThinkingLevel,
2360+
isGroup: commandParams.isGroup,
2361+
defaultGroupActivation: commandParams.defaultGroupActivation,
2362+
modelAuthOverride: "api-key",
2363+
activeModelAuthOverride: "api-key",
2364+
});
2365+
}
2366+
2367+
it("delivers a fixed generic reply and logs details when status rendering throws", async () => {
2368+
// commands-status re-exports buildStatusText, so the mock must keep that
2369+
// binding while prod calls buildStatusReplyParts. logError stays mocked so
2370+
// containment diagnostics never leak into test stderr.
2371+
vi.doMock("../../logger.js", async (importOriginal) => ({
2372+
...(await importOriginal<object>()),
2373+
logError: vi.fn(),
2374+
}));
2375+
vi.doMock("../../status/status-text.js", () => ({
2376+
buildStatusReplyParts: vi.fn(() => Promise.reject(new Error("Unexpected rendering error"))),
2377+
buildStatusText: vi.fn(() => Promise.reject(new Error("Unexpected rendering error"))),
2378+
}));
2379+
2380+
vi.resetModules();
2381+
const { buildStatusReply: freshBuildStatusReply } = await import("./commands-status.js");
2382+
const { logError } = await import("../../logger.js");
2383+
const reply = await runStatusReply(freshBuildStatusReply);
2384+
2385+
// Exact object equality also pins that no stale presentation or internal
2386+
// error text reaches the channel; diagnostics belong to the log sink only.
2387+
expect(reply).toEqual({ text: "⚠️ Status: error rendering response" });
2388+
expect(logError).toHaveBeenCalledWith(expect.stringContaining("Unexpected rendering error"));
2389+
});
2390+
2391+
it("keeps the structured rich payload on the success path", async () => {
2392+
const presentation = {
2393+
title: "Status",
2394+
tone: "info" as const,
2395+
blocks: [{ type: "text" as const, text: "plain status" }, { type: "divider" as const }],
2396+
};
2397+
vi.doMock("../../status/status-text.js", () => ({
2398+
buildStatusReplyParts: vi.fn(() => Promise.resolve({ text: "plain status", presentation })),
2399+
buildStatusText: vi.fn(() => Promise.resolve("plain status")),
2400+
}));
2401+
2402+
vi.resetModules();
2403+
const { buildStatusReply: freshBuildStatusReply } = await import("./commands-status.js");
2404+
const reply = await runStatusReply(freshBuildStatusReply);
2405+
2406+
expect(reply).toMatchObject({
2407+
text: "plain status",
2408+
presentation,
2409+
presentationTextMode: "fallback",
2410+
});
2411+
});
2412+
2413+
it("returns a generic reply and logs details when plugin health collection fails", async () => {
2414+
vi.doMock("../../logger.js", async (importOriginal) => ({
2415+
...(await importOriginal<object>()),
2416+
logError: vi.fn(),
2417+
}));
2418+
2419+
vi.resetModules();
2420+
const { buildStatusPluginsReply: freshBuildStatusPluginsReply } =
2421+
await import("./commands-status.js");
2422+
const { logError } = await import("../../logger.js");
2423+
pluginHealthRuntimeMock.collectInstalledPluginHealthSnapshot.mockRejectedValueOnce(
2424+
new Error("Cannot find module 'internal/path'"),
2425+
);
2426+
2427+
const commandParams = buildCommandTestParams("/status plugins", {
2428+
...baseCfg,
2429+
commands: { text: true, plugins: true },
2430+
});
2431+
const reply = await freshBuildStatusPluginsReply({
2432+
cfg: commandParams.cfg,
2433+
command: commandParams.command,
2434+
workspaceDir: commandParams.workspaceDir,
2435+
});
2436+
2437+
expect(reply?.text).toBe("⚠️ Plugins: health unavailable");
2438+
expect(logError).toHaveBeenCalledWith(
2439+
expect.stringContaining("Cannot find module 'internal/path'"),
2440+
);
2441+
});
2442+
});
23322443
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */
23332444

23342445
async function buildKiraStatusReply(cfg: OpenClawConfig) {

‎src/auto-reply/reply/commands-status.ts‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
/** Builds /status replies using the command's authorized channel context. */
22
import { logVerbose } from "../../globals.js";
3+
import { formatErrorMessage } from "../../infra/errors.js";
4+
import { logError } from "../../logger.js";
35
import { formatDetailedPluginHealth } from "../../status/status-plugin-health.js";
46
import { buildStatusReplyParts } from "../../status/status-text.js";
57
import type { BuildStatusTextParams } from "../../status/status-text.types.js";
@@ -22,14 +24,21 @@ export async function buildStatusReply(
2224
return undefined;
2325
}
2426

25-
const { text, presentation } = await buildStatusReplyParts({
26-
...params,
27-
statusChannel: command.channel,
28-
statusAccountId: command.accountId,
29-
});
30-
// The text body is the authored plain rendering of the same facts; channels
31-
// with native table support render the presentation instead.
32-
return { text, presentation, presentationTextMode: "fallback" };
27+
try {
28+
const { text, presentation } = await buildStatusReplyParts({
29+
...params,
30+
statusChannel: command.channel,
31+
statusAccountId: command.accountId,
32+
});
33+
// The text body is the authored plain rendering of the same facts; channels
34+
// with native table support render the presentation instead.
35+
return { text, presentation, presentationTextMode: "fallback" };
36+
} catch (error) {
37+
// Diagnostics stay in logs only; the channel reply is a fixed generic
38+
// message so internal module paths or runtime details never reach users.
39+
logError(`/status render failed: ${formatErrorMessage(error)}`);
40+
return { text: "⚠️ Status: error rendering response" };
41+
}
3342
}
3443

3544
export async function buildStatusPluginsReply(
@@ -59,8 +68,8 @@ export async function buildStatusPluginsReply(
5968
});
6069
return { text: formatDetailedPluginHealth(snapshot) };
6170
} catch (error) {
62-
return {
63-
text: `⚠️ Plugins: health unavailable (${error instanceof Error ? error.message : String(error)})`,
64-
};
71+
// Match the /status fallback: fixed generic reply, diagnostics in logs only.
72+
logError(`/status plugins render failed: ${formatErrorMessage(error)}`);
73+
return { text: "⚠️ Plugins: health unavailable" };
6574
}
6675
}

‎src/status/status-text.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { beforeEach, describe, expect, it, vi } from "vitest";
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
22
import { formatSqliteSessionFileMarker } from "../config/sessions/legacy-sqlite-marker.js";
33
import { normalizeSessionDeliveryState } from "../utils/delivery-context.shared.js";
44
import { appendSessionCostLine } from "./status-runtime-lines.js";
@@ -353,3 +353,58 @@ describe("buildStatusText thinking facts", () => {
353353
expect(text).not.toMatch(/think\s+off\b/);
354354
});
355355
});
356+
357+
describe("buildStatusText lazy loader retry", () => {
358+
afterEach(() => {
359+
vi.doUnmock("./status-plugin-health.runtime.js");
360+
vi.resetModules();
361+
vi.restoreAllMocks();
362+
});
363+
364+
function retryStatusParams(sessionId: string): Parameters<typeof buildStatusText>[0] {
365+
return {
366+
cfg: {},
367+
sessionEntry: { sessionId, updatedAt: 0 },
368+
sessionKey: "agent:main:main",
369+
statusChannel: "mobilechat",
370+
provider: "openai",
371+
model: "gpt-5.4-mini",
372+
resolvedHarness: "openclaw",
373+
resolvedVerboseLevel: "off",
374+
resolvedReasoningLevel: "off",
375+
resolveDefaultThinkingLevel: async () => undefined,
376+
isGroup: false,
377+
defaultGroupActivation: () => "mention",
378+
taskLineOverride: "",
379+
skipDefaultTaskLookup: true,
380+
primaryModelLabelOverride: "openai/gpt-5.4-mini",
381+
modelAuthOverride: "api-key",
382+
activeModelAuthOverride: "api-key",
383+
includeTranscriptUsage: false,
384+
};
385+
}
386+
387+
it("falls back on import failure and retries in the same module instance", async () => {
388+
vi.doMock("./status-plugin-health.runtime.js", async () => {
389+
throw new Error("Module load failure");
390+
});
391+
vi.resetModules();
392+
393+
const { buildStatusText: firstLoadBuildStatusText } = await import("./status-text.js");
394+
const failed = await firstLoadBuildStatusText(retryStatusParams("retry-failure"));
395+
expect(failed).toContain("Plugins: health unavailable");
396+
397+
vi.doMock("./status-plugin-health.runtime.js", () => ({
398+
collectRuntimePluginHealthSnapshot: () => ({
399+
plugins: [],
400+
diagnostics: [],
401+
contextEngineQuarantines: [],
402+
runtimeToolQuarantines: [],
403+
channelPluginFailures: [],
404+
}),
405+
}));
406+
407+
const recovered = await firstLoadBuildStatusText(retryStatusParams("retry-recovery"));
408+
expect(recovered).not.toContain("Plugins: health unavailable");
409+
});
410+
});

‎src/status/status-text.ts‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ import {
4141
import { resolveActiveProviderThinkingProfile } from "../plugins/provider-thinking-active.js";
4242
import { normalizeAccountId } from "../routing/account-id.js";
4343
import { resolveNormalizedAccountEntry } from "../routing/account-lookup.js";
44-
import { createLazyPromise, createLazyRuntimeModule } from "../shared/lazy-runtime.js";
44+
import { createLazyPromise } from "../shared/lazy-runtime.js";
4545
import {
4646
listTasksForAgentIdForStatus,
4747
listTasksForSessionKeyForStatus,
@@ -108,22 +108,20 @@ function resolveStatusChannelFeatureLine(params: {
108108
: "Telegram rich messages: off · set channels.telegram.richMessages=true for tables/details/rich media";
109109
}
110110

111-
const loadStatusMessageRuntime = createLazyPromise(
112-
() =>
113-
import("./status-message.runtime.js").then((module) => module.loadStatusMessageRuntimeModule()),
114-
{ cacheRejections: true },
115-
);
116-
const loadAgentThinkingRuntime = createLazyRuntimeModule(
117-
() => import("../agents/thinking-runtime.js"),
118-
);
119-
const loadThinkingLevelRuntime = createLazyRuntimeModule(() => import("../auto-reply/thinking.js"));
120-
const loadStatusSubagentsRuntime = createLazyRuntimeModule(
121-
() => import("./status-subagents.runtime.js"),
111+
// Status loaders keep the lazy-promise eviction default: a transient module-load
112+
// failure on one /status request self-heals on the next instead of poisoning
113+
// every reply. Deliberately not createLazyRuntimeModule, whose sticky rejection
114+
// cache would pin the failure for the process lifetime.
115+
const loadStatusMessageRuntime = createLazyPromise(() =>
116+
import("./status-message.runtime.js").then((module) => module.loadStatusMessageRuntimeModule()),
122117
);
118+
const loadAgentThinkingRuntime = createLazyPromise(() => import("../agents/thinking-runtime.js"));
119+
const loadThinkingLevelRuntime = createLazyPromise(() => import("../auto-reply/thinking.js"));
120+
const loadStatusSubagentsRuntime = createLazyPromise(() => import("./status-subagents.runtime.js"));
123121

124-
const loadStatusQueueRuntime = createLazyRuntimeModule(() => import("./status-queue.runtime.js"));
122+
const loadStatusQueueRuntime = createLazyPromise(() => import("./status-queue.runtime.js"));
125123

126-
const loadStatusPluginHealthRuntime = createLazyRuntimeModule(
124+
const loadStatusPluginHealthRuntime = createLazyPromise(
127125
() => import("./status-plugin-health.runtime.js"),
128126
);
129127

0 commit comments

Comments
 (0)