Skip to content

Commit a872abc

Browse files
authored
fix(ui): preserve startup errors across session navigation (#130593)
1 parent b581ff0 commit a872abc

13 files changed

Lines changed: 257 additions & 53 deletions

‎docs/web/control-ui.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,8 @@ For connections with a durable user profile, the Gateway stores each agent's lat
120120

121121
On the first identified connection, the Control UI uploads existing browser-local new-session preferences only when the Gateway has no such preferences yet. Later changes write to the Gateway first and then update the browser mirror. Connections without a durable identity continue using browser-local preferences and the loaded session roster for recents.
122122

123+
When a remote project session starts before its repository finishes cloning, chat shows workspace preparation progress. If preparation fails, opening or reloading chat restores the session's failure summary. Correct the reported problem, then send a new message in the same session to retry preparation.
124+
123125
## Personal identity
124126

125127
Authenticated people have a durable Gateway profile with a display name, avatar, linked emails, and optional verified GitHub identity. Open **Settings → Profile → Identity** to update the editable fields. The profile follows the authenticated person across browsers; clearing browser site data does not delete it.

‎src/config/sessions/session-transcript-turn-lifecycle.types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ export type SessionTranscriptTurnLifecyclePatch = {
3131
endedAt?: number;
3232
lifecycleRunId?: SessionEntry["lifecycleRunId"];
3333
lastRunId?: SessionEntry["lastRunId"];
34+
lastRunError?: SessionEntry["lastRunError"];
3435
pendingFinalDelivery?: SessionEntry["pendingFinalDelivery"];
3536
mainRestartRecovery?: SessionEntry["mainRestartRecovery"];
3637
restartRecoveryBeforeAgentReplyState?: SessionRestartRecoveryState["restartRecoveryBeforeAgentReplyState"];

‎src/gateway/server-methods/chat-restart-recovery.ts‎

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import { sessionDeliveryChannel } from "../../utils/delivery-context.shared.js";
2929
import { parseInlineDirectives } from "../../utils/directive-tags.js";
3030
import { resolveChatRunOwnerAgentId } from "../chat-run-owner.js";
3131
import type { GatewayRecoveryRuntime } from "../server-instance-runtime.types.js";
32+
import { deriveGatewaySessionLifecycleSnapshot } from "../session-lifecycle-state.js";
3233
import { resolveChatSendActiveScopeKey } from "./chat-origin-routing.js";
3334
import type { GatewayRequestContext } from "./types.js";
3435

@@ -46,6 +47,12 @@ type RestartSafeChatAdmission = {
4647
retryExpectedState?: SessionTranscriptTurnExpectedState;
4748
};
4849

50+
export type RestartSafeChatTerminalState = {
51+
error?: string;
52+
retryable: boolean;
53+
status: "failed" | "killed";
54+
};
55+
4956
type RetryableUnadoptedChatClaim = SessionEntry & {
5057
abortedLastRun?: false;
5158
restartRecoveryDeliveryContext?: undefined;
@@ -377,11 +384,11 @@ export function buildRestartSafeChatTranscriptState(params: {
377384
restartRecoveryBeforeAgentReplyState: undefined,
378385
restartRecoveryDeliveryReceiptState: undefined,
379386
restartRecoveryDeliveryToolCallId: undefined,
380-
status: "running",
387+
...deriveGatewaySessionLifecycleSnapshot({
388+
event: { runId: params.clientRunId, ts: params.startedAt, data: { phase: "start" } },
389+
}),
381390
lifecycleRunId: params.clientRunId,
382391
lastRunId: undefined,
383-
startedAt: params.startedAt,
384-
endedAt: undefined,
385392
restartRecoveryDeliveryContext: undefined,
386393
restartRecoveryDeliveryRequestFingerprint: params.admission.requestFingerprint,
387394
restartRecoveryDeliveryRunId: params.clientRunId,
@@ -394,22 +401,19 @@ export function buildRestartSafeChatTranscriptState(params: {
394401
...(params.admission.priorTerminalSourceRunId
395402
? { restartRecoveryTerminalRunIds: [params.admission.priorTerminalSourceRunId] }
396403
: {}),
397-
runtimeMs: undefined,
398-
abortedLastRun: false,
399-
updatedAt: params.startedAt,
400404
},
401405
};
402406
}
403407

404-
export async function terminalizeRestartSafeChatAdmission(params: {
405-
admittedSessionId: string;
406-
clientRunId: string;
407-
retryable: boolean;
408-
sessionKey: string;
409-
startedAt: number;
410-
status: "failed" | "killed";
411-
storePath: string;
412-
}): Promise<boolean> {
408+
export async function terminalizeRestartSafeChatAdmission(
409+
params: RestartSafeChatTerminalState & {
410+
admittedSessionId: string;
411+
clientRunId: string;
412+
sessionKey: string;
413+
startedAt: number;
414+
storePath: string;
415+
},
416+
): Promise<boolean> {
413417
const endedAt = Date.now();
414418
let terminalized = false;
415419
await patchSessionEntryCore(
@@ -422,21 +426,32 @@ export async function terminalizeRestartSafeChatAdmission(params: {
422426
return null;
423427
}
424428
terminalized = true;
429+
// Commit the diagnostic with claim release; a later lifecycle write could
430+
// race the next admission before a newly mounted chat reads the failure.
425431
return {
432+
...deriveGatewaySessionLifecycleSnapshot({
433+
event: {
434+
runId: params.clientRunId,
435+
ts: endedAt,
436+
data: {
437+
phase: params.status === "failed" ? "error" : "end",
438+
startedAt: params.startedAt,
439+
endedAt,
440+
aborted: params.status === "killed",
441+
error: params.error,
442+
},
443+
},
444+
}),
426445
abortedLastRun: params.retryable ? false : params.status === "killed",
427446
lifecycleRunId: undefined,
428447
lastRunId: params.clientRunId,
429-
endedAt,
430448
...(params.retryable
431449
? {}
432450
: buildRestartRecoveryClaimCleanupPatch({
433451
entry: current,
434452
recordTerminalSource: true,
435453
terminalSourceRunId: current.restartRecoveryDeliverySourceRunId,
436454
})),
437-
runtimeMs: Math.max(0, endedAt - params.startedAt),
438-
status: params.status,
439-
updatedAt: endedAt,
440455
};
441456
},
442457
{ requireWriteSuccess: true, skipMaintenance: true },

‎src/gateway/server-methods/chat-send-agent-dispatch.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { chatRunBelongsToSelectedAgent } from "../chat-run-owner.js";
1818
import type { ChatRunTiming } from "../server-chat-state.js";
1919
import { tryResolveSessionCompatibilityOwnerAgentId } from "../session-request-agent.js";
2020
import { broadcastChatError, broadcastChatFinal } from "./chat-broadcast.js";
21+
import type { RestartSafeChatTerminalState } from "./chat-restart-recovery.js";
2122
import type { AdmittedChatSend } from "./chat-send-admission.js";
2223
import type { prepareChatSendAttachments } from "./chat-send-attachments.js";
2324
import {
@@ -71,10 +72,9 @@ type StartChatDispatchParams = {
7172
};
7273
request: NormalizedChatSendRequest;
7374
session: PreparedChatSendSession;
74-
terminalizeRestartSafeAdmission: (terminalState: {
75-
retryable: boolean;
76-
status: "failed" | "killed";
77-
}) => Promise<boolean>;
75+
terminalizeRestartSafeAdmission: (
76+
terminalState: RestartSafeChatTerminalState,
77+
) => Promise<boolean>;
7878
timing: {
7979
chatSendAckedAtMs: number;
8080
chatSendTiming: ChatRunTiming | undefined;

‎src/gateway/server-methods/chat-send-dispatch-errors.ts‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { tryResolveSessionCompatibilityOwnerAgentId } from "../session-request-a
88
import { formatForLog } from "../ws-log.js";
99
import { buildAbortedChatSendPayload } from "./chat-abort-authorization.js";
1010
import { broadcastChatError, broadcastChatFinal } from "./chat-broadcast.js";
11+
import type { RestartSafeChatTerminalState } from "./chat-restart-recovery.js";
1112
import type { AdmittedChatSend } from "./chat-send-admission.js";
1213
import type { PreparedChatSendSession } from "./chat-send-session.js";
1314
import { hasTrackedActiveSessionRun } from "./session-active-runs.js";
@@ -31,16 +32,14 @@ export async function handleChatSendSetupError(params: {
3132
error: unknown;
3233
respond: RespondFn;
3334
session: Pick<PreparedChatSendSession, "agentId" | "clientRunId" | "sessionKey">;
34-
terminalizeRestartSafeAdmission: (state: {
35-
retryable: boolean;
36-
status: "failed" | "killed";
37-
}) => Promise<boolean>;
35+
terminalizeRestartSafeAdmission: (state: RestartSafeChatTerminalState) => Promise<boolean>;
3836
}): Promise<void> {
3937
const { cleanupAdmittedRun, lifecycleGeneration, restartSafeAdmission } = params.admission;
4038
const { agentId, clientRunId, sessionKey } = params.session;
39+
const errorMessage = String(params.error);
4140
if (restartSafeAdmission) {
4241
const terminalized = await params
43-
.terminalizeRestartSafeAdmission({ retryable: true, status: "failed" })
42+
.terminalizeRestartSafeAdmission({ error: errorMessage, retryable: true, status: "failed" })
4443
.catch((terminalizeError: unknown) => {
4544
params.context.logGateway.warn(
4645
`failed to release restart-safe chat admission after setup error: ${formatForLog(
@@ -60,7 +59,6 @@ export async function handleChatSendSetupError(params: {
6059
cleanupAdmittedRun({ force: true });
6160
clearAgentRunContext(clientRunId, lifecycleGeneration);
6261
params.context.removeChatRun(clientRunId, clientRunId, sessionKey);
63-
const errorMessage = String(params.error);
6462
const error = errorShape(ErrorCodes.UNAVAILABLE, errorMessage);
6563
const payload = { runId: clientRunId, status: "error" as const, summary: errorMessage };
6664
setGatewayDedupeEntry({
@@ -91,10 +89,7 @@ export function createChatSendDispatchErrorLifecycle(params: {
9189
PreparedChatSendSession,
9290
"agentId" | "backingSessionId" | "cfg" | "clientRunId" | "now" | "rawSessionKey" | "sessionKey"
9391
>;
94-
terminalizeRestartSafeAdmission: (state: {
95-
retryable: boolean;
96-
status: "failed" | "killed";
97-
}) => Promise<boolean>;
92+
terminalizeRestartSafeAdmission: (state: RestartSafeChatTerminalState) => Promise<boolean>;
9893
userTurnRecorder: Pick<UserTurnTranscriptRecorder, "hasPersisted" | "isBlocked">;
9994
}) {
10095
const {
@@ -198,6 +193,7 @@ export function createChatSendDispatchErrorLifecycle(params: {
198193
let restartSafeDispatchFailureTerminalized = false;
199194
if (restartSafeAdmission && !agentTerminalPersistenceOwnedAtDispatchReject) {
200195
restartSafeDispatchFailureTerminalized = await terminalizeRestartSafeAdmission({
196+
error: errorMessage,
201197
retryable: true,
202198
status: "failed",
203199
}).catch((terminalizeError: unknown) => {

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ import { emitDiagnosticsTimelineEvent } from "../../infra/diagnostics-timeline.j
66
import type { SkillWorkshopProposalRevisionConstraint } from "../../skills/workshop/types.js";
77
import { discardPreparedInboundMedia } from "../chat-attachments.js";
88
import type { ChatRunTiming } from "../server-chat-state.js";
9-
import { terminalizeRestartSafeChatAdmission } from "./chat-restart-recovery.js";
9+
import {
10+
terminalizeRestartSafeChatAdmission,
11+
type RestartSafeChatTerminalState,
12+
} from "./chat-restart-recovery.js";
1013
import { startChatDispatch } from "./chat-send-agent-dispatch.js";
1114
import { prepareChatSendAttachments } from "./chat-send-attachments.js";
1215
import { handleChatSendSetupError } from "./chat-send-dispatch-errors.js";
@@ -118,10 +121,9 @@ async function handleChatSendWithOptions(
118121
});
119122

120123
const admissionStartedAt = Date.now();
121-
const terminalizeRestartSafeAdmission = async (terminalState: {
122-
retryable: boolean;
123-
status: "failed" | "killed";
124-
}): Promise<boolean> =>
124+
const terminalizeRestartSafeAdmission = async (
125+
terminalState: RestartSafeChatTerminalState,
126+
): Promise<boolean> =>
125127
await terminalizeRestartSafeChatAdmission({
126128
admittedSessionId,
127129
clientRunId,

‎src/gateway/server.sessions.create.projects.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,23 @@ test("sessions.create survives Gateway restart after remote project failure and
299299
);
300300
const entryAfterFailure = loadSessionEntry({ agentId: "main", sessionKey: key, storePath });
301301

302+
// The first chat pane subscribes only after create-and-navigate. Its history
303+
// must recover the failure without receiving the already-emitted chat event.
304+
for (const method of ["chat.startup", "chat.history"] as const) {
305+
const history = await directSessionReq(method, { sessionKey: key }, controlUiClient);
306+
expect(history.ok, JSON.stringify(history.error)).toBe(true);
307+
expect(history.payload).toMatchObject({
308+
sessionInfo: {
309+
sessionId,
310+
status: "failed",
311+
hasActiveRun: false,
312+
lastRunId: runId,
313+
lastRunError: expect.stringContaining(failureMessage),
314+
},
315+
messages: [expect.objectContaining({ role: "user" })],
316+
});
317+
}
318+
302319
const retriedMaterialization = createDeferredCore<typeof project>();
303320
projectCloneMocks.materialize.mockReturnValueOnce(retriedMaterialization.promise);
304321
const restartedContext = { broadcast, chatAbortControllers: new Map(), dedupe: new Map() };
@@ -321,6 +338,9 @@ test("sessions.create survives Gateway restart after remote project failure and
321338
status: "started",
322339
});
323340
await vi.waitFor(() => expect(projectCloneMocks.materialize).toHaveBeenCalledTimes(2));
341+
expect(loadSessionEntry({ agentId: "main", sessionKey: key, storePath })?.lastRunError).toBe(
342+
undefined,
343+
);
324344
expect(dispatchInboundMessageMock).not.toHaveBeenCalled();
325345
expect(entryAfterCreation).toMatchObject({
326346
sessionId,

‎src/gateway/session-lifecycle-state.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ type PersistedLifecycleSessionShape = Pick<
7373
| "lifecycleRunId"
7474
>;
7575

76-
type GatewaySessionLifecycleSnapshot = Partial<LifecycleSessionShape>;
76+
type GatewaySessionLifecycleSnapshot = Partial<Pick<SessionEntry, keyof LifecycleSessionShape>>;
7777

7878
const SESSION_RUN_ERROR_MAX_CHARS = 160;
7979

@@ -176,8 +176,8 @@ function resolveRuntimeMs(params: {
176176
return undefined;
177177
}
178178

179-
function deriveGatewaySessionLifecycleSnapshot(params: {
180-
session?: Partial<LifecycleSessionShape> | null;
179+
export function deriveGatewaySessionLifecycleSnapshot(params: {
180+
session?: GatewaySessionLifecycleSnapshot | null;
181181
event: LifecycleEventLike;
182182
}): GatewaySessionLifecycleSnapshot {
183183
const phase = resolveLifecyclePhase(params.event);

‎ui/src/pages/chat/chat-gateway.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import {
55
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
66
import { isAssistantHeartbeatAckForDisplay } from "../../lib/chat/heartbeat-display.ts";
77
import { extractText } from "../../lib/chat/message-extract.ts";
8-
import { formatUiExternalText } from "../../lib/format-error.ts";
98
// Control UI page module reconciles Chat Gateway events into Chat state.
109
import { isUiGlobalSessionKey, resolveUiDefaultAgentId } from "../../lib/sessions/session-key.ts";
1110
import {
@@ -24,7 +23,7 @@ import {
2423
readChatSessionProjectionScope,
2524
setChatSessionProjection,
2625
} from "./history-merge.ts";
27-
import { reconcileChatRunLifecycle } from "./run-lifecycle.ts";
26+
import { reconcileChatRunLifecycle, setChatRunError } from "./run-lifecycle.ts";
2827
import { appendChatMessageToCache } from "./session-message-cache.ts";
2928
import {
3029
latestStreamBoundaryRunId,
@@ -51,10 +50,6 @@ type AssistantMessageNormalizationOptions = {
5150
allowTextField?: boolean;
5251
};
5352

54-
function setChatRunError(state: ChatState, summary: string) {
55-
state.chatRunError = { summary: formatUiExternalText(summary) };
56-
}
57-
5853
function chatEventSessionMatches(state: ChatState, payload: ChatEventPayload): boolean {
5954
return chatScopedEventSessionMatches(state, payload.sessionKey, payload.agentId);
6055
}

‎ui/src/pages/chat/chat-history-cursor.test.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,20 +118,33 @@ describe("chat history cursor revalidation", () => {
118118
});
119119
});
120120

121-
it("advances the cursor when catch-up is already current", async () => {
121+
it("recovers a missed terminal failure even when cursor catch-up has no new messages", async () => {
122122
const cached = message("user", "cached", "cached-user", 1);
123123
const handler = vi.fn(async (_params?: unknown) => ({
124124
kind: "delta",
125125
messages: [],
126126
deltaCursor: "cursor-2",
127-
sessionInfo: { key: "main", kind: "direct", sessionId: "session-cursor", updatedAt: 2 },
127+
sessionInfo: {
128+
key: "main",
129+
kind: "direct",
130+
sessionId: "session-cursor",
131+
updatedAt: 2,
132+
status: "failed",
133+
hasActiveRun: false,
134+
lastRunId: "run-first",
135+
lastRunError:
136+
"Git clone could not reach GitHub. Check the Gateway network connection and retry.",
137+
},
128138
}));
129139
const state = createState(handler);
130140
const cache = seedCachedHistory(state, [cached], "cursor-1");
131141

132142
await loadChatHistory(state);
133143

134144
expect(state.chatMessages).toEqual([cached]);
145+
expect(state.chatRunError?.summary).toContain(
146+
"Check the Gateway network connection and retry.",
147+
);
135148
expect(
136149
readChatSessionSnapshot(cache, state, { sessionKey: state.sessionKey })?.deltaCursor,
137150
).toBe("cursor-2");

0 commit comments

Comments
 (0)