Skip to content

Commit 7a288ed

Browse files
authored
fix(tui): retain reset confirmation after history refresh (#131557)
1 parent 42d4585 commit 7a288ed

7 files changed

Lines changed: 278 additions & 56 deletions

‎docs/web/tui.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,8 @@ Session lifecycle:
136136
- `/settings`
137137
- `/exit` (or `/quit`)
138138

139+
When the current session is reset, the TUI confirms it after refreshing the transcript, including resets initiated by another client.
140+
139141
Local mode only:
140142

141143
- `/auth [provider]` opens the provider auth/login flow inside the TUI.

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

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Covers TUI event handler routing for keyboard and backend events.
22
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import { createDeferred } from "../../test/helpers/promise.js";
34
import * as failoverClassifier from "../agents/failover/classify.js";
45
import { MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "../shared/assistant-error-format.js";
56
import { createEventHandlers } from "./tui-event-handlers.js";
@@ -1735,6 +1736,77 @@ describe("tui-event-handlers: handleAgentEvent", () => {
17351736
expect(chatLog.startTool).not.toHaveBeenCalled();
17361737
});
17371738

1739+
it("reports only the latest reset after all queued history reloads settle", async () => {
1740+
const first = createDeferred<TuiHistoryLoadResult>();
1741+
const second = createDeferred<TuiHistoryLoadResult>();
1742+
const { state, chatLog, loadHistory, handleSessionsChangedEvent, dispose } =
1743+
createHandlersHarness({ state: { activeChatRunId: null } });
1744+
loadHistory.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
1745+
try {
1746+
handleSessionsChangedEvent({ reason: "reset", sessionId: "session-1", updatedAt: 20 });
1747+
handleSessionsChangedEvent({ reason: "reset", sessionId: "session-1", updatedAt: 30 });
1748+
expect(loadHistory).toHaveBeenCalledTimes(1);
1749+
first.resolve({ loaded: true, runOutcome: { state: "completed" } });
1750+
await vi.waitFor(() => expect(loadHistory).toHaveBeenCalledTimes(2));
1751+
expect(chatLog.addSystem).not.toHaveBeenCalled();
1752+
1753+
state.activeChatRunId = "newly-adopted-run";
1754+
second.resolve({ loaded: true, runOutcome: { state: "active", runId: "newly-adopted-run" } });
1755+
await vi.waitFor(() =>
1756+
expect(chatLog.addSystem).toHaveBeenCalledExactlyOnceWith("session agent:main:main reset"),
1757+
);
1758+
expect(state.activeChatRunId).toBe("newly-adopted-run");
1759+
} finally {
1760+
dispose();
1761+
}
1762+
});
1763+
1764+
it.each(["session", "global agent", "new lifecycle", "dispose"])(
1765+
"discards a reset receipt retired by %s while history loads",
1766+
async (retirement) => {
1767+
const history = createDeferred<TuiHistoryLoadResult>();
1768+
const { state, chatLog, loadHistory, handleSessionsChangedEvent, dispose } =
1769+
createHandlersHarness({
1770+
state: {
1771+
currentSessionKey: retirement === "global agent" ? "global" : "agent:main:main",
1772+
activeChatRunId: null,
1773+
},
1774+
});
1775+
loadHistory.mockReturnValueOnce(history.promise);
1776+
handleSessionsChangedEvent({ reason: "reset", agentId: "main", sessionId: "session-1" });
1777+
if (retirement === "session") {
1778+
state.currentSessionKey = "agent:main:other";
1779+
} else if (retirement === "global agent") {
1780+
state.currentAgentId = "work";
1781+
} else if (retirement === "new lifecycle") {
1782+
handleSessionsChangedEvent({ reason: "new", sessionId: "replacement" });
1783+
} else {
1784+
dispose();
1785+
}
1786+
history.resolve({ loaded: true, runOutcome: { state: "completed" } });
1787+
await new Promise<void>((resolve) => {
1788+
setImmediate(resolve);
1789+
});
1790+
expect(chatLog.addSystem).not.toHaveBeenCalled();
1791+
dispose();
1792+
},
1793+
);
1794+
1795+
it("reports an observed reset even when its history reload fails", async () => {
1796+
const { chatLog, loadHistory, handleSessionsChangedEvent, dispose } = createHandlersHarness({
1797+
state: { activeChatRunId: null },
1798+
});
1799+
loadHistory.mockRejectedValueOnce(new Error("history unavailable"));
1800+
try {
1801+
handleSessionsChangedEvent({ reason: "reset", sessionId: "session-1" });
1802+
await vi.waitFor(() =>
1803+
expect(chatLog.addSystem).toHaveBeenCalledExactlyOnceWith("session agent:main:main reset"),
1804+
);
1805+
} finally {
1806+
dispose();
1807+
}
1808+
});
1809+
17381810
it("reloads the selected session for an identity-only legacy batch invalidation", () => {
17391811
const { state, loadHistory, handleSessionsChangedEvent } = createHandlersHarness({
17401812
state: { activeChatRunId: null, currentSessionId: "session-1" },

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

Lines changed: 33 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -379,23 +379,6 @@ export function createEventHandlers(context: EventHandlerContext) {
379379
tui.requestRender();
380380
};
381381

382-
const collectTrackedSessionRunIds = () => {
383-
const runIds = new Set(sessionRuns.keys());
384-
if (state.activeChatRunId) {
385-
runIds.add(state.activeChatRunId);
386-
}
387-
const pendingRunId = getPendingSubmitAcceptedRunId(state);
388-
if (pendingRunId) {
389-
runIds.add(pendingRunId);
390-
}
391-
const finalizedRunIds = new Set(finalizedRuns.keys());
392-
const displayedRunIds = new Set(finalizedRunsWithDisplay.keys());
393-
for (const runId of finalizedRunIds) {
394-
runIds.add(runId);
395-
}
396-
return { runIds, finalizedRunIds, displayedRunIds };
397-
};
398-
399382
const handleSessionsChangedEvent = (payload: unknown) => {
400383
if (!payload || typeof payload !== "object") {
401384
return;
@@ -416,7 +399,7 @@ export function createEventHandlers(context: EventHandlerContext) {
416399
}
417400
// Legacy atomic batches expose no replayable message identity. Refresh
418401
// their authoritative history without resetting the current run or stream.
419-
runCoordinator.queueHistoryReload();
402+
void runCoordinator.queueHistoryReload();
420403
return;
421404
}
422405

@@ -428,7 +411,11 @@ export function createEventHandlers(context: EventHandlerContext) {
428411
const displayedRunIds = finalizedRunsWithDisplay.has(persistedRunId)
429412
? [persistedRunId]
430413
: [];
431-
runCoordinator.queueHistoryReload([persistedRunId], [persistedRunId], displayedRunIds);
414+
void runCoordinator.queueHistoryReload(
415+
[persistedRunId],
416+
[persistedRunId],
417+
displayedRunIds,
418+
);
432419
} else {
433420
void refreshSessionInfo?.();
434421
}
@@ -446,7 +433,7 @@ export function createEventHandlers(context: EventHandlerContext) {
446433
nextSessionId !== null &&
447434
state.currentSessionId !== nextSessionId;
448435
if (evt.reason === "new" && !replacesKnownSession) {
449-
const { runIds, displayedRunIds } = collectTrackedSessionRunIds();
436+
const { runIds, displayedRunIds } = runCoordinator.collectTrackedSessionRunIds();
450437
if (runIds.size > 0) {
451438
if (nextSessionId) {
452439
state.currentSessionId = nextSessionId;
@@ -462,17 +449,14 @@ export function createEventHandlers(context: EventHandlerContext) {
462449
pendingNewSessionRunIds.add(runId);
463450
}
464451
}
465-
runCoordinator.queueHistoryReload(persistedRunIds, persistedRunIds, displayedRunIds);
452+
void runCoordinator.queueHistoryReload(persistedRunIds, persistedRunIds, displayedRunIds);
466453
tui.requestRender();
467454
return;
468455
}
469456
}
470457

471-
const {
472-
runIds: reloadingRunIds,
473-
finalizedRunIds,
474-
displayedRunIds,
475-
} = collectTrackedSessionRunIds();
458+
const { runIds, finalizedRunIds, displayedRunIds } =
459+
runCoordinator.collectTrackedSessionRunIds();
476460
state.sessionGeneration = (state.sessionGeneration ?? 0) + 1;
477461
// Reduce the old epoch before adopting its replacement ID; otherwise the
478462
// canonical reducer correctly rejects the reset as a foreign session.
@@ -491,11 +475,27 @@ export function createEventHandlers(context: EventHandlerContext) {
491475
state.sessionInfo.updatedAt = evt.updatedAt;
492476
}
493477
getTuiSessionProjection(state);
494-
if (reloadingRunIds.size > 0) {
495-
runCoordinator.queueHistoryReload(reloadingRunIds, finalizedRunIds, displayedRunIds);
496-
} else {
497-
runCoordinator.queueHistoryReload();
498-
}
478+
const selection = { sessionKey: state.currentSessionKey, agentId: state.currentAgentId };
479+
const generation = state.sessionGeneration;
480+
const historyReload = runCoordinator.queueHistoryReload(
481+
runIds.size > 0 ? runIds : undefined,
482+
finalizedRunIds,
483+
displayedRunIds,
484+
);
485+
// The reset event can retire its own RPC acknowledgement. Its authoritative
486+
// receipt belongs after the last queued history rebuild, which clears chat.
487+
void historyReload.then((current) => {
488+
if (
489+
current &&
490+
evt.reason === "reset" &&
491+
generation === state.sessionGeneration &&
492+
matchesSelectedTuiSession(state, selection) &&
493+
selection.agentId === state.currentAgentId
494+
) {
495+
chatLog.addSystem(`session ${state.currentSessionKey} reset`);
496+
tui.requestRender();
497+
}
498+
});
499499
tui.requestRender();
500500
};
501501

@@ -739,9 +739,9 @@ export function createEventHandlers(context: EventHandlerContext) {
739739
type: "transportGap",
740740
scope: readTuiSessionProjectionScope(state),
741741
});
742-
const { runIds, displayedRunIds } = collectTrackedSessionRunIds();
742+
const { runIds, displayedRunIds } = runCoordinator.collectTrackedSessionRunIds();
743743
if (runIds.size === 0) {
744-
runCoordinator.queueHistoryReload();
744+
void runCoordinator.queueHistoryReload();
745745
return;
746746
}
747747
// A dropped final cannot distinguish a finished run from a still-streaming

‎src/tui/tui-run-lifecycle.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export function createTuiRunLifecycle(context: TuiRunLifecycleContext) {
8383
return;
8484
}
8585
runCoordinator.pendingHistoryRefresh = false;
86-
runCoordinator.queueHistoryReload();
86+
void runCoordinator.queueHistoryReload();
8787
};
8888

8989
const clearStreamingWatchdog = () => {
@@ -141,7 +141,7 @@ export function createTuiRunLifecycle(context: TuiRunLifecycleContext) {
141141
state.activityStatus = "idle";
142142
setActivityStatus("idle");
143143
runCoordinator.pendingHistoryRefresh = false;
144-
runCoordinator.queueHistoryReload();
144+
void runCoordinator.queueHistoryReload();
145145
tui.requestRender();
146146
return;
147147
}
@@ -380,7 +380,7 @@ export function createTuiRunLifecycle(context: TuiRunLifecycleContext) {
380380
return;
381381
}
382382
runCoordinator.pendingHistoryRefresh = false;
383-
runCoordinator.queueHistoryReload();
383+
void runCoordinator.queueHistoryReload();
384384
};
385385

386386
const renderTerminalRunError = (params: {

‎src/tui/tui-session-actions.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
33
import { createDeferred } from "../../test/helpers/promise.js";
44
import { ChatLog } from "./components/chat-log.js";
55
import type { TuiBackend } from "./tui-backend.js";
6+
import { createCommandHandlers } from "./tui-command-handlers.js";
67
import { createEventHandlers } from "./tui-event-handlers.js";
78
import {
89
makeChatLog,
@@ -2152,6 +2153,103 @@ describe("tui session actions", () => {
21522153
expect(addSystem).toHaveBeenCalledWith("session agent:main:new");
21532154
});
21542155

2156+
it.each(["none", "before adoption", "during refresh", "after acknowledgement"])(
2157+
"keeps the reset acknowledgement with a notification %s",
2158+
async (notification) => {
2159+
const state = createBaseState({
2160+
currentSessionId: "same-session",
2161+
sessionGeneration: 4,
2162+
historyLoaded: true,
2163+
sessionInfo: { updatedAt: 10, totalTokens: 42 },
2164+
});
2165+
const entry = { sessionId: "same-session", updatedAt: 20, totalTokens: 0 };
2166+
const result = { ok: true, key: state.currentSessionKey, entry };
2167+
const chatLog = makeChatLog();
2168+
chatLog.addUser("before reset");
2169+
const tui = makeTui();
2170+
const btw = createBtwPresenter();
2171+
const setActivityStatus = (text: string) => {
2172+
state.activityStatus = text;
2173+
};
2174+
const refreshStarted = createDeferred();
2175+
const refreshResult = createDeferred<TuiSessionList>();
2176+
const resetResponse = createDeferred<typeof result>();
2177+
const client = makeTuiBackend({
2178+
resetSession: vi.fn(() => resetResponse.promise),
2179+
listSessions: vi.fn(() => {
2180+
refreshStarted.resolve();
2181+
return refreshResult.promise;
2182+
}),
2183+
loadHistory: vi.fn(async () => ({
2184+
messages: [],
2185+
sessionInfo: { key: result.key, ...entry },
2186+
})),
2187+
});
2188+
const actions = createTestSessionActions({ client, chatLog, tui, btw, state });
2189+
const histories: Array<Promise<TuiHistoryLoadResult>> = [];
2190+
const events = createEventHandlers({
2191+
chatLog,
2192+
tui,
2193+
btw,
2194+
state,
2195+
setActivityStatus,
2196+
loadHistory: () => {
2197+
const history = actions.loadHistory();
2198+
histories.push(history);
2199+
return history;
2200+
},
2201+
refreshSessionInfo: actions.refreshSessionInfo,
2202+
});
2203+
const commands = createCommandHandlers({
2204+
client,
2205+
chatLog,
2206+
tui,
2207+
state,
2208+
opts: {},
2209+
deliverDefault: false,
2210+
openOverlay: (component) => tui.showOverlay(component),
2211+
closeOverlay: () => tui.hideOverlay(),
2212+
setActivityStatus,
2213+
formatSessionKey: (key) => key,
2214+
requestExit: vi.fn(),
2215+
...actions,
2216+
});
2217+
const notify = () =>
2218+
events.handleSessionsChangedEvent({
2219+
sessionKey: result.key,
2220+
agentId: "main",
2221+
reason: "reset",
2222+
...entry,
2223+
});
2224+
try {
2225+
const resetting = commands.handleCommand("/reset");
2226+
resetResponse.resolve(result);
2227+
if (notification === "before adoption") {
2228+
notify();
2229+
} else {
2230+
await refreshStarted.promise;
2231+
if (notification === "during refresh") {
2232+
notify();
2233+
}
2234+
}
2235+
refreshResult.resolve(makeTuiSessionList({ sessions: [{ key: result.key, ...entry }] }));
2236+
await resetting;
2237+
if (notification === "after acknowledgement") {
2238+
notify();
2239+
}
2240+
await Promise.all(histories);
2241+
await vi.waitFor(() => {
2242+
const rendered = chatLog.render(120).join("\n");
2243+
expect(rendered).not.toContain("before reset");
2244+
expect(rendered.match(/session agent:main:main reset/g)).toHaveLength(1);
2245+
});
2246+
expect(commands.resolveMessageAdmission("after reset")).toEqual({ status: "allowed" });
2247+
} finally {
2248+
events.dispose();
2249+
}
2250+
},
2251+
);
2252+
21552253
it("fences pre-reset history and session-info reads when reset commits", async () => {
21562254
const history = createDeferred<unknown>();
21572255
const sessionInfo = createDeferred<TuiSessionList>();

0 commit comments

Comments
 (0)