Skip to content

Commit 70265e5

Browse files
ZYV5geocv5
authored andcommitted
fix: preserve new-session models through startup errors
1 parent e29f692 commit 70265e5

4 files changed

Lines changed: 331 additions & 9 deletions

File tree

‎src/gateway/server-methods/chat-history-handler.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
measureDiagnosticsTimelineSpan,
2727
measureDiagnosticsTimelineSpanSync,
2828
} from "../../infra/diagnostics-timeline.js";
29+
import { formatErrorMessage } from "../../infra/errors.js";
2930
import { jsonUtf8Bytes } from "../../infra/json-utf8-bytes.js";
3031
import { normalizeAgentId, scopeLegacySessionKeyToAgent } from "../../routing/session-key.js";
3132
import { listGatewayAgentsBasic } from "../agent-list.js";
@@ -124,13 +125,13 @@ async function buildChatMetadataResult(params: {
124125
import("./models-list-result.js"),
125126
import("./commands-list-result.js"),
126127
]);
127-
const [models, commands] = await Promise.all([
128+
const [modelsResult, commandsResult] = await Promise.allSettled([
128129
buildModelsListResult({
129130
context: params.context,
130131
agentId: params.agentId,
131132
params: { view: "configured" },
132133
}),
133-
Promise.resolve(
134+
Promise.resolve().then(() =>
134135
buildCommandsListResult({
135136
cfg: params.cfg,
136137
agentId: params.agentId,
@@ -139,9 +140,21 @@ async function buildChatMetadataResult(params: {
139140
}),
140141
),
141142
]);
143+
144+
if (modelsResult.status === "rejected") {
145+
throw modelsResult.reason;
146+
}
147+
148+
if (commandsResult.status === "rejected") {
149+
params.context.logGateway.warn(
150+
"chat.metadata continuing without text commands: " +
151+
formatErrorMessage(commandsResult.reason),
152+
);
153+
}
154+
142155
return {
143-
...models,
144-
...commands,
156+
...modelsResult.value,
157+
...(commandsResult.status === "fulfilled" ? commandsResult.value : {}),
145158
swarmEnabled: resolveSwarmConfig(params.cfg, params.agentId).enabled,
146159
};
147160
}

‎src/gateway/server.chat.gateway-server-chat-b.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import type { AgentModelConfig } from "../config/types.agents-shared.js";
2626
import type { OpenClawConfig } from "../config/types.openclaw.js";
2727
import { rotateAgentEventLifecycleGeneration } from "../infra/agent-events.js";
2828
import { onDiagnosticEvent, type DiagnosticPayloadLargeEvent } from "../infra/diagnostic-events.js";
29+
import { ExecApprovalsMigrationRequiredError } from "../infra/exec-approvals-migration-gate.js";
2930
import {
3031
captureCurrentPluginMetadataSnapshotState,
3132
restoreCurrentPluginMetadataSnapshotState,
@@ -1700,6 +1701,80 @@ describe("gateway server chat", () => {
17001701
});
17011702
});
17021703

1704+
test("chat.metadata preserves configured models when text commands require exec approvals migration", async () => {
1705+
await withGatewayChatHarness(async ({ ws }) => {
1706+
await writeGatewayConfig({
1707+
agents: {
1708+
defaults: {
1709+
model: {
1710+
primary: "openai/gpt-main",
1711+
},
1712+
models: {
1713+
"openai/gpt-main": {},
1714+
"openai/gpt-secondary": {},
1715+
},
1716+
},
1717+
entries: {
1718+
main: { default: true },
1719+
},
1720+
},
1721+
models: {
1722+
providers: {
1723+
openai: {
1724+
baseUrl: "https://openai.example.com/v1",
1725+
models: [
1726+
{ id: "gpt-main", name: "GPT Main" },
1727+
{ id: "gpt-secondary", name: "GPT Secondary" },
1728+
],
1729+
},
1730+
},
1731+
},
1732+
});
1733+
await connectOk(ws);
1734+
1735+
const legacyExecApprovalsPath = path.join(
1736+
autoCleanupTempDirs.make("openclaw-chat-metadata-exec-approvals-"),
1737+
"exec-approvals.json",
1738+
);
1739+
const commandsListResult = await import("./server-methods/commands-list-result.js");
1740+
vi.spyOn(commandsListResult, "buildCommandsListResult").mockImplementationOnce(() => {
1741+
throw new ExecApprovalsMigrationRequiredError(legacyExecApprovalsPath);
1742+
});
1743+
1744+
const metadata = await rpcReq<{
1745+
commands?: Array<{ name?: string }>;
1746+
models?: Array<{ id?: string; provider?: string }>;
1747+
}>(ws, "chat.metadata", { agentId: "main" });
1748+
1749+
expect(metadata.ok).toBe(true);
1750+
expect(metadata.payload?.commands).toBeUndefined();
1751+
expect(metadata.payload?.models).toEqual(
1752+
expect.arrayContaining([
1753+
expect.objectContaining({ id: "gpt-main", provider: "openai" }),
1754+
expect.objectContaining({ id: "gpt-secondary", provider: "openai" }),
1755+
]),
1756+
);
1757+
});
1758+
});
1759+
1760+
test("chat.metadata remains unavailable when configured models fail", async () => {
1761+
await withGatewayChatHarness(async ({ ws }) => {
1762+
await connectOk(ws);
1763+
const modelsListResult = await import("./server-methods/models-list-result.js");
1764+
vi.spyOn(modelsListResult, "buildModelsListResult").mockRejectedValueOnce(
1765+
new Error("configured model catalog unavailable"),
1766+
);
1767+
1768+
const metadata = await rpcReq(ws, "chat.metadata", { agentId: "main" });
1769+
1770+
expect(metadata.ok).toBe(false);
1771+
expect(metadata.error).toMatchObject({
1772+
code: "UNAVAILABLE",
1773+
message: expect.stringContaining("configured model catalog unavailable"),
1774+
});
1775+
});
1776+
});
1777+
17031778
test("chat.send returns in_flight when duplicate attachment send wins parsing race", async () => {
17041779
openDirectChatSession();
17051780
const dispatchRelease = createDeferred();

‎ui/src/pages/new-session/model-control.test.ts‎

Lines changed: 150 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import { describe, expect, it, vi } from "vitest";
1+
import {
2+
DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS,
3+
gatewayStartupUnavailableDetails,
4+
} from "@openclaw/gateway-client/browser";
5+
import { afterEach, describe, expect, it, vi } from "vitest";
6+
import { GatewayRequestError } from "../../api/gateway.ts";
27
import type { GatewayAgentRow, ModelCatalogEntry } from "../../api/types.ts";
38
import type { ApplicationContext } from "../../app/context.ts";
49
import { NewSessionModelControl } from "./model-control.ts";
@@ -27,6 +32,20 @@ function contextWith(models: ModelCatalogEntry[], runtime = "openclaw") {
2732
return { context, request };
2833
}
2934

35+
function startupUnavailableError(retryAfterMs = 250): GatewayRequestError {
36+
return new GatewayRequestError({
37+
code: "UNAVAILABLE",
38+
message: "gateway startup sidecars are still initializing",
39+
details: gatewayStartupUnavailableDetails(),
40+
retryable: true,
41+
retryAfterMs,
42+
});
43+
}
44+
45+
afterEach(() => {
46+
vi.useRealTimers();
47+
});
48+
3049
describe("new-session model runtime", () => {
3150
it("restores a browser preference only after the model and thinking level validate", async () => {
3251
const { context } = contextWith([
@@ -163,7 +182,9 @@ describe("new-session model runtime", () => {
163182
expect(request).toHaveBeenCalledWith(
164183
"chat.metadata",
165184
{ agentId: "main" },
166-
{ signal: expect.any(AbortSignal) },
185+
expect.objectContaining({
186+
signal: expect.any(AbortSignal),
187+
}),
167188
),
168189
);
169190
await vi.waitFor(() => {
@@ -204,4 +225,131 @@ describe("new-session model runtime", () => {
204225

205226
await vi.waitFor(() => expect(control.resolveAgentRuntimeId({ context })).toBeUndefined());
206227
});
228+
229+
it("retries canonical startup-sidecars unavailability and restores the catalog", async () => {
230+
vi.useFakeTimers();
231+
const models: ModelCatalogEntry[] = [
232+
{
233+
id: "gpt-5.6-sol",
234+
name: "GPT-5.6 Sol",
235+
provider: "openai",
236+
reasoning: true,
237+
},
238+
{
239+
id: "gpt-5.6-terra",
240+
name: "GPT-5.6 Terra",
241+
provider: "openai",
242+
reasoning: true,
243+
},
244+
];
245+
const { context, request } = contextWith(models);
246+
request.mockReset();
247+
request.mockRejectedValueOnce(startupUnavailableError(250)).mockResolvedValueOnce({ models });
248+
const control = new NewSessionModelControl(() => undefined);
249+
250+
control.load(context, "main", true, {
251+
preference: { model: "openai/gpt-5.6-terra", thinkingLevel: "high" },
252+
});
253+
254+
await vi.advanceTimersByTimeAsync(0);
255+
expect(request).toHaveBeenCalledOnce();
256+
257+
await vi.advanceTimersByTimeAsync(249);
258+
expect(request).toHaveBeenCalledOnce();
259+
260+
await vi.advanceTimersByTimeAsync(1);
261+
expect(request).toHaveBeenCalledTimes(2);
262+
expect(control.selected).toBe("openai/gpt-5.6-terra");
263+
expect(control.thinkingLevel).toBe("high");
264+
expect(control.isRestoringPreference()).toBe(false);
265+
});
266+
267+
it("does not retry other retryable UNAVAILABLE errors", async () => {
268+
vi.useFakeTimers();
269+
const { context, request } = contextWith([]);
270+
request.mockReset();
271+
request.mockRejectedValue(
272+
new GatewayRequestError({
273+
code: "UNAVAILABLE",
274+
message: "database temporarily unavailable",
275+
details: { reason: "database-busy" },
276+
retryable: true,
277+
retryAfterMs: 250,
278+
}),
279+
);
280+
const control = new NewSessionModelControl(() => undefined);
281+
282+
control.load(context, "main", true);
283+
284+
await vi.advanceTimersByTimeAsync(0);
285+
expect(request).toHaveBeenCalledOnce();
286+
expect(vi.getTimerCount()).toBe(0);
287+
288+
await vi.advanceTimersByTimeAsync(2_000);
289+
expect(request).toHaveBeenCalledOnce();
290+
});
291+
292+
it("aborts a pending startup retry when the catalog task is invalidated", async () => {
293+
vi.useFakeTimers();
294+
const { context, request } = contextWith([]);
295+
request.mockReset();
296+
request.mockRejectedValue(startupUnavailableError(2_000));
297+
const control = new NewSessionModelControl(() => undefined);
298+
299+
control.load(context, "main", true);
300+
301+
await vi.advanceTimersByTimeAsync(0);
302+
expect(request).toHaveBeenCalledOnce();
303+
expect(vi.getTimerCount()).toBe(1);
304+
305+
control.invalidate();
306+
await vi.advanceTimersByTimeAsync(0);
307+
308+
expect(vi.getTimerCount()).toBe(0);
309+
await vi.advanceTimersByTimeAsync(2_000);
310+
expect(request).toHaveBeenCalledOnce();
311+
});
312+
313+
it("stops startup-sidecars retries at the 60 second deadline", async () => {
314+
vi.useFakeTimers();
315+
const startedAt = Date.UTC(2026, 7, 2);
316+
vi.setSystemTime(startedAt);
317+
const { context, request } = contextWith([]);
318+
const attemptTimes: number[] = [];
319+
request.mockReset();
320+
request.mockImplementation(() => {
321+
attemptTimes.push(Date.now());
322+
return Promise.reject(startupUnavailableError(2_000));
323+
});
324+
const control = new NewSessionModelControl(() => undefined);
325+
326+
control.load(context, "main", true);
327+
328+
await vi.advanceTimersByTimeAsync(60_000);
329+
330+
expect(attemptTimes).toHaveLength(30);
331+
expect(attemptTimes[0]).toBe(startedAt);
332+
expect(attemptTimes.at(-1)).toBe(startedAt + 58_000);
333+
expect(request).toHaveBeenNthCalledWith(
334+
1,
335+
"chat.metadata",
336+
{ agentId: "main" },
337+
{
338+
signal: expect.any(AbortSignal),
339+
timeoutMs: DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS,
340+
},
341+
);
342+
expect(request).toHaveBeenLastCalledWith(
343+
"chat.metadata",
344+
{ agentId: "main" },
345+
{
346+
signal: expect.any(AbortSignal),
347+
timeoutMs: 2_000,
348+
},
349+
);
350+
expect(vi.getTimerCount()).toBe(0);
351+
352+
await vi.advanceTimersByTimeAsync(10_000);
353+
expect(request).toHaveBeenCalledTimes(30);
354+
});
207355
});

0 commit comments

Comments
 (0)