Skip to content

Commit 67dc607

Browse files
authored
fix(tui): preserve run and session ownership across async events (#130147)
* fix(tui): preserve run and session ownership across async events * test: stabilize filesystem mocks and gateway restart completion
1 parent 29c81cf commit 67dc607

5 files changed

Lines changed: 203 additions & 28 deletions

File tree

‎src/gateway/server-methods/system-agent.test.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -918,14 +918,12 @@ describe("openclaw.chat", () => {
918918
} finally {
919919
releaseApproval.resolve();
920920
}
921-
await vi.waitFor(() => {
922-
expect(resolveOperatorApproval).toHaveBeenCalledWith("allow-once", proposalHash);
923-
expect(runGatewayRestart).toHaveBeenCalledOnce();
924-
expect(systemAgentLane().activeCount).toBe(0);
925-
});
921+
expect(resolveOperatorApproval).toHaveBeenCalledWith("allow-once", proposalHash);
922+
expect(runGatewayRestart).toHaveBeenCalledOnce();
926923
await expect(resolveOperatorApproval.mock.results[0]?.value).resolves.toMatchObject({
927924
text: expect.stringContaining("[openclaw] done: gateway.restart"),
928925
});
926+
await vi.waitFor(() => expect(systemAgentLane().activeCount).toBe(0));
929927
expect(readLastSystemAgentAuditEntry()).toMatchObject({
930928
operation: "gateway.restart",
931929
summary: "Scheduled Gateway restart",

‎src/tui/tui-command-handlers.test.ts‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1401,6 +1401,42 @@ describe("tui command handlers", () => {
14011401
expect(loadHistory).toHaveBeenCalledTimes(1);
14021402
});
14031403

1404+
it.each(["error", "timeout", "ok"])(
1405+
"ignores a terminal %s ACK after its history reload switches sessions",
1406+
async (status) => {
1407+
const history = createDeferred();
1408+
const harness = createHarness({
1409+
currentAgentId: "research",
1410+
currentSessionKey: "agent:research:private",
1411+
currentSessionId: "private-session",
1412+
sendChat: vi.fn(async ({ runId }: { runId: string }) => ({ runId, status })),
1413+
loadHistory: vi.fn(() => history.promise) as LoadHistoryMock,
1414+
});
1415+
const pending = harness.handleCommand("private provider request");
1416+
await vi.waitFor(() => expect(harness.loadHistory).toHaveBeenCalledTimes(1));
1417+
harness.addSystem.mockClear();
1418+
harness.setActivityStatus.mockClear();
1419+
harness.requestRender.mockClear();
1420+
harness.state.currentAgentId = "ops";
1421+
harness.state.currentSessionKey = "agent:ops:public";
1422+
harness.state.currentSessionId = "public-session";
1423+
harness.state.activeChatRunId = "public-run";
1424+
harness.state.pendingSubmit = {
1425+
phase: "accepted",
1426+
runId: "public-run",
1427+
draftText: null,
1428+
};
1429+
1430+
history.resolve();
1431+
await pending;
1432+
1433+
expect(harness.addSystem).not.toHaveBeenCalled();
1434+
expect(harness.setActivityStatus).not.toHaveBeenCalled();
1435+
expect(harness.state.activeChatRunId).toBe("public-run");
1436+
expect(harness.state.pendingSubmit?.runId).toBe("public-run");
1437+
},
1438+
);
1439+
14041440
it("removes the accepted canonical pending turn after a re-keyed terminal failure", async () => {
14051441
const sendChat = vi.fn().mockResolvedValue({
14061442
runId: "accepted-failed-run",
@@ -2212,6 +2248,86 @@ describe("tui command handlers", () => {
22122248
expect(harness.addSystem).not.toHaveBeenCalled();
22132249
});
22142250

2251+
it.each(["/model openai/gpt-5.6-luna", "/usage reset"])(
2252+
"does not apply a stale %s result after a nested patch handoff",
2253+
async (command) => {
2254+
const appliedAgents: string[] = [];
2255+
const displayedAgents: string[] = [];
2256+
const patchSession = vi.fn(() => {
2257+
queueMicrotask(() => {
2258+
queueMicrotask(() => {
2259+
harness.state.currentAgentId = "ops";
2260+
harness.state.currentSessionKey = "agent:ops:public";
2261+
harness.state.currentSessionId = "public-session";
2262+
harness.state.sessionGeneration += 1;
2263+
harness.state.sessionInfo = {
2264+
responseUsage: "tokens",
2265+
effectiveResponseUsage: "tokens",
2266+
};
2267+
});
2268+
});
2269+
return Promise.resolve({
2270+
ok: true as const,
2271+
path: "/sessions/patch",
2272+
key: "agent:research:private",
2273+
entry: { model: "private-sensitive-model" },
2274+
});
2275+
});
2276+
const harness = createHarness({
2277+
currentAgentId: "research",
2278+
currentSessionKey: "agent:research:private",
2279+
currentSessionId: "private-session",
2280+
sessionGeneration: 2,
2281+
sessionInfo: { responseUsage: "tokens", effectiveResponseUsage: "tokens" },
2282+
patchSession,
2283+
applySessionInfoFromPatch: vi.fn(() => appliedAgents.push(harness.state.currentAgentId)),
2284+
});
2285+
harness.addSystem.mockImplementation(() =>
2286+
displayedAgents.push(harness.state.currentAgentId),
2287+
);
2288+
2289+
await harness.handleCommand(command);
2290+
2291+
expect(harness.state.currentAgentId).toBe("ops");
2292+
expect(harness.state.sessionInfo.responseUsage).toBe("tokens");
2293+
expect(appliedAgents).toEqual(["research"]);
2294+
expect(displayedAgents).toEqual(["research"]);
2295+
},
2296+
);
2297+
2298+
it.each([
2299+
{ command: "/model openai/gpt-5.6-luna", hook: "refresh" },
2300+
{ command: "/think high", hook: "refresh" },
2301+
{ command: "/verbose full", hook: "history" },
2302+
{ command: "/usage reset", hook: "refresh" },
2303+
])(
2304+
"hides a stale $command failure after its post-patch $hook rejects",
2305+
async ({ command, hook }) => {
2306+
const followup = createDeferred();
2307+
const harness = createHarness({
2308+
currentAgentId: "research",
2309+
currentSessionKey: "agent:research:private",
2310+
currentSessionId: "private-session",
2311+
...(hook === "history"
2312+
? { loadHistory: vi.fn(() => followup.promise) as LoadHistoryMock }
2313+
: { refreshSessionInfo: vi.fn(() => followup.promise) }),
2314+
});
2315+
const pending = harness.handleCommand(command);
2316+
const followupCall = hook === "history" ? harness.loadHistory : harness.refreshSessionInfo;
2317+
await vi.waitFor(() => expect(followupCall).toHaveBeenCalledTimes(1));
2318+
harness.addSystem.mockClear();
2319+
harness.state.currentAgentId = "ops";
2320+
harness.state.currentSessionKey = "agent:ops:public";
2321+
harness.state.currentSessionId = "public-session";
2322+
2323+
followup.reject(new Error("private provider account rejected research tenant"));
2324+
await pending;
2325+
2326+
expect(harness.addSystem).not.toHaveBeenCalled();
2327+
expect(harness.state.currentAgentId).toBe("ops");
2328+
},
2329+
);
2330+
22152331
it.each(["/model openai/gpt-5.6-luna", "/usage reset"])(
22162332
"ignores a stale global-agent %s result",
22172333
async (command) => {

‎src/tui/tui-command-handlers.ts‎

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -281,34 +281,20 @@ export function createCommandHandlers(context: CommandHandlerContext) {
281281
};
282282
};
283283

284-
const patchCurrentSession = async (
284+
const applySessionSetting = async (
285285
patch: Omit<Parameters<TuiBackend["patchSession"]>[0], "key" | "agentId">,
286-
): Promise<SessionsPatchResult | null> => {
286+
success: string | ((result: SessionsPatchResult) => string),
287+
failure: string,
288+
after?: (result: SessionsPatchResult) => void | Promise<void>,
289+
) => {
287290
const { selection, isCurrent } = captureSessionIncarnation();
288291
try {
289292
const result = await client.patchSession({
290293
key: selection.sessionKey,
291294
...(!parseAgentSessionKey(selection.sessionKey) ? { agentId: selection.agentId } : {}),
292295
...patch,
293296
});
294-
return isCurrent() ? result : null;
295-
} catch (err) {
296297
if (!isCurrent()) {
297-
return null;
298-
}
299-
throw err;
300-
}
301-
};
302-
303-
const applySessionSetting = async (
304-
patch: Omit<Parameters<TuiBackend["patchSession"]>[0], "key" | "agentId">,
305-
success: string | ((result: SessionsPatchResult) => string),
306-
failure: string,
307-
after?: (result: SessionsPatchResult) => void | Promise<void>,
308-
) => {
309-
try {
310-
const result = await patchCurrentSession(patch);
311-
if (!result) {
312298
return;
313299
}
314300
chatLog.addSystem(typeof success === "function" ? success(result) : success);
@@ -319,7 +305,9 @@ export function createCommandHandlers(context: CommandHandlerContext) {
319305
await refreshSessionInfo();
320306
}
321307
} catch (err) {
322-
chatLog.addSystem(`${failure}: ${formatTuiErrorMessage(err)}`);
308+
if (isCurrent()) {
309+
chatLog.addSystem(`${failure}: ${formatTuiErrorMessage(err)}`);
310+
}
323311
}
324312
};
325313

@@ -1034,6 +1022,9 @@ export function createCommandHandlers(context: CommandHandlerContext) {
10341022
state.activeChatRunId = null;
10351023
}
10361024
await loadHistory();
1025+
if (!isCurrentSendViewport()) {
1026+
return;
1027+
}
10371028
if (terminalAckFailure) {
10381029
chatLog.addSystem(`send failed: ${TERMINAL_CHAT_SEND_FAILURE_MESSAGE}`);
10391030
setActivityStatus("error");

‎src/tui/tui-event-handlers.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2723,6 +2723,73 @@ describe("tui-event-handlers: handleAgentEvent", () => {
27232723
expect(chatLog.addSystem).toHaveBeenCalledWith(`run error: ${backendError}`);
27242724
});
27252725

2726+
it.each(["error", "final"] as const)(
2727+
"accepts an owned local %s event before its submit is acknowledged",
2728+
(terminalState) => {
2729+
const { state, chatLog, handleAgentEvent, handleChatEvent, noteLocalRunId } =
2730+
createHandlersHarness({
2731+
localMode: true,
2732+
state: { activeChatRunId: null, sessionInfo: { modelProvider: "xai" } },
2733+
});
2734+
2735+
handleAgentEvent({
2736+
runId: "completed-run",
2737+
sessionKey: state.currentSessionKey,
2738+
data: { phase: "start" },
2739+
});
2740+
handleChatEvent(makeFinalChatEvent(state, "completed-run"));
2741+
state.pendingSubmit = sendingSubmit("next-local-run");
2742+
noteLocalRunId("next-local-run");
2743+
2744+
handleChatEvent({
2745+
runId: "next-local-run",
2746+
state: terminalState,
2747+
...(terminalState === "error"
2748+
? { errorMessage: "monthly spending limit" }
2749+
: { message: { content: [{ type: "text", text: "early local reply" }] } }),
2750+
});
2751+
2752+
expect(state.pendingSubmit).toBeNull();
2753+
if (terminalState === "error") {
2754+
expect(chatLog.addSystem).toHaveBeenCalledWith("run error: monthly spending limit");
2755+
} else {
2756+
expect(chatLog.finalizeAssistant).toHaveBeenCalledWith(
2757+
"early local reply",
2758+
"next-local-run",
2759+
);
2760+
}
2761+
},
2762+
);
2763+
2764+
it.each([
2765+
{ label: "unowned local", localMode: true, owned: false, sessionKey: "agent:main:main" },
2766+
{ label: "remote", localMode: false, owned: true, sessionKey: "agent:main:main" },
2767+
{ label: "foreign session", localMode: true, owned: true, sessionKey: "agent:main:other" },
2768+
])("rejects an unsequenced $label provisional event", ({ localMode, owned, sessionKey }) => {
2769+
const { state, chatLog, handleAgentEvent, handleChatEvent, noteLocalRunId } =
2770+
createHandlersHarness({ localMode, state: { activeChatRunId: null } });
2771+
handleAgentEvent({
2772+
runId: "completed-run",
2773+
sessionKey: state.currentSessionKey,
2774+
data: { phase: "start" },
2775+
});
2776+
handleChatEvent(makeFinalChatEvent(state, "completed-run"));
2777+
state.pendingSubmit = sendingSubmit("untrusted-run");
2778+
if (owned) {
2779+
noteLocalRunId("untrusted-run");
2780+
}
2781+
2782+
handleChatEvent({
2783+
runId: "untrusted-run",
2784+
sessionKey,
2785+
state: "error",
2786+
errorMessage: "foreign private diagnostic",
2787+
});
2788+
2789+
expect(state.pendingSubmit).toEqual(sendingSubmit("untrusted-run"));
2790+
expect(chatLog.addSystem).not.toHaveBeenCalledWith("run error: foreign private diagnostic");
2791+
});
2792+
27262793
it("surfaces a late provider error without replaying a completed assistant reply", () => {
27272794
const { state, chatLog, handleChatEvent } = createHandlersHarness({
27282795
state: { activeChatRunId: "run-source-reply" },

‎src/tui/tui-event-handlers.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -180,9 +180,12 @@ export function createEventHandlers(context: EventHandlerContext) {
180180
return;
181181
}
182182
const isSequencedGatewayEvent = Number.isSafeInteger(evt.seq) && (evt.seq ?? -1) >= 0;
183+
const isOwnedLocalPendingRun =
184+
localMode && state.pendingSubmit?.runId === evt.runId && isLocalRunId?.(evt.runId) === true;
183185
if (
184186
runCoordinator.isRetiredOrphanRun(evt.runId) &&
185187
!isSequencedGatewayEvent &&
188+
!isOwnedLocalPendingRun &&
186189
evt.runId !== getPendingSubmitAcceptedRunId(state)
187190
) {
188191
return;
@@ -247,10 +250,10 @@ export function createEventHandlers(context: EventHandlerContext) {
247250
}
248251
}
249252
}
250-
// Gateway chat envelopes require a non-negative sequence, even when a
251-
// legacy peer omits agent lifecycle starts; orphan deltas have none.
253+
// Gateway events are sequenced; early embedded events are trustworthy only
254+
// when their exact provisional run belongs to the selected local viewport.
252255
acknowledgeChatRun(evt.runId, {
253-
protectStream: isSequencedGatewayEvent,
256+
protectStream: isSequencedGatewayEvent || isOwnedLocalPendingRun,
254257
});
255258
const isPendingChatRun = getPendingSubmitAcceptedRunId(state) === evt.runId;
256259
const isLocalChatRun = isLocalRunId?.(evt.runId) ?? false;

0 commit comments

Comments
 (0)