Skip to content

Commit 97c0455

Browse files
authored
fix(tui): route messages to the replacement agent session (#126820)
1 parent a4901b6 commit 97c0455

3 files changed

Lines changed: 176 additions & 42 deletions

File tree

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

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,10 @@ describe("tui session actions", () => {
216216
agentNames,
217217
updateHeader,
218218
updateFooter,
219+
resolveSessionSelection: vi.fn((_raw?: string, agentId = state.currentAgentId) => ({
220+
key: `agent:${agentId}:${state.sessionMainKey}`,
221+
agentId,
222+
})),
219223
});
220224

221225
await expect(refreshAgents()).resolves.toEqual({ ok: true, value: undefined });
@@ -227,6 +231,7 @@ describe("tui session actions", () => {
227231
{ id: "system-agent", kind: "system", name: "System Agent" },
228232
]);
229233
expect(state.currentAgentId).toBe("team-lead");
234+
expect(state.currentSessionKey).toBe("agent:team-lead:primary");
230235
expect([...agentNames]).toEqual([
231236
["team-lead", "Lead Agent"],
232237
["system-agent", "System Agent"],
@@ -235,6 +240,129 @@ describe("tui session actions", () => {
235240
expect(updateFooter).toHaveBeenCalledTimes(1);
236241
});
237242

243+
it.each([
244+
{
245+
scope: "per-sender" as const,
246+
previousKey: "agent:research:main",
247+
nextKey: "agent:ops:main",
248+
},
249+
{
250+
scope: "global" as const,
251+
previousKey: "global",
252+
nextKey: "global",
253+
},
254+
])(
255+
"retires the complete $scope session when its selected agent disappears",
256+
async ({ scope, previousKey, nextKey }) => {
257+
const state = createBaseState({
258+
agents: [{ id: "research" }],
259+
currentAgentId: "research",
260+
currentSessionKey: previousKey,
261+
currentSessionId: "old-session",
262+
sessionMainKey: "main",
263+
sessionScope: scope,
264+
activeChatRunId: "old-run",
265+
pendingSubmit: acceptedSubmit("pending-run"),
266+
historyLoaded: true,
267+
sessionInfo: { updatedAt: 100, thinkingLevel: "high", verboseLevel: "full" },
268+
});
269+
sendPendingUser(state, "pending-run", "stale prompt");
270+
const loadHistory = vi.fn();
271+
const invalidateRunOwnership = vi.fn();
272+
const clearLocalRunIds = vi.fn();
273+
const clearAll = vi.fn();
274+
const clearPendingUsers = vi.fn();
275+
const btw = createBtwPresenter();
276+
const { refreshAgents } = createTestSessionActions({
277+
client: makeTuiBackend({
278+
loadHistory,
279+
listAgents: vi.fn().mockResolvedValue({
280+
defaultId: "ops",
281+
mainKey: "main",
282+
scope,
283+
agents: [{ id: "ops" }],
284+
}),
285+
}),
286+
chatLog: makeChatLog({ clearAll, clearPendingUsers }),
287+
btw,
288+
state,
289+
invalidateRunOwnership,
290+
clearLocalRunIds,
291+
resolveSessionSelection: vi.fn((_raw?: string, agentId = state.currentAgentId) => ({
292+
key: scope === "global" ? "global" : `agent:${agentId}:main`,
293+
agentId,
294+
})),
295+
});
296+
297+
await expect(refreshAgents()).resolves.toEqual({ ok: true, value: undefined });
298+
299+
expect(state).toMatchObject({
300+
currentAgentId: "ops",
301+
currentSessionKey: nextKey,
302+
currentSessionId: null,
303+
activeChatRunId: null,
304+
pendingSubmit: null,
305+
historyLoaded: false,
306+
sessionInfo: { updatedAt: null },
307+
});
308+
expect(state.sessionInfo.thinkingLevel).toBe("high");
309+
expect(state.sessionInfo.verboseLevel).toBeUndefined();
310+
expect(state.sessionProjection?.entries).toEqual([]);
311+
expect(invalidateRunOwnership).toHaveBeenCalledOnce();
312+
expect(clearLocalRunIds).toHaveBeenCalledOnce();
313+
expect(clearAll).toHaveBeenCalledOnce();
314+
expect(clearPendingUsers).toHaveBeenCalledOnce();
315+
expect(btw.clear).toHaveBeenCalledOnce();
316+
expect(loadHistory).not.toHaveBeenCalled();
317+
},
318+
);
319+
320+
it("preserves the complete selected session when its agent remains in the roster", async () => {
321+
const state = createBaseState({
322+
agents: [{ id: "research" }],
323+
currentAgentId: "research",
324+
currentSessionKey: "agent:research:incident",
325+
currentSessionId: "current-session",
326+
sessionScope: "per-sender",
327+
activeChatRunId: "current-run",
328+
pendingSubmit: acceptedSubmit("pending-run"),
329+
historyLoaded: true,
330+
sessionInfo: { updatedAt: 100, thinkingLevel: "high" },
331+
});
332+
sendPendingUser(state, "pending-run", "current prompt");
333+
const previousProjection = state.sessionProjection;
334+
const invalidateRunOwnership = vi.fn();
335+
const resolveSessionSelection = vi.fn();
336+
const { refreshAgents } = createTestSessionActions({
337+
client: makeTuiBackend({
338+
listAgents: vi.fn().mockResolvedValue({
339+
defaultId: "ops",
340+
mainKey: "main",
341+
scope: "per-sender",
342+
agents: [{ id: "ops" }, { id: "research" }],
343+
}),
344+
}),
345+
state,
346+
invalidateRunOwnership,
347+
resolveSessionSelection,
348+
});
349+
350+
await expect(refreshAgents()).resolves.toEqual({ ok: true, value: undefined });
351+
352+
expect(state).toMatchObject({
353+
currentAgentId: "research",
354+
currentSessionKey: "agent:research:incident",
355+
currentSessionId: "current-session",
356+
activeChatRunId: "current-run",
357+
historyLoaded: true,
358+
sessionInfo: { updatedAt: 100, thinkingLevel: "high" },
359+
});
360+
expect(state.pendingSubmit).toEqual(acceptedSubmit("pending-run"));
361+
expect(state.sessionProjection).toBe(previousProjection);
362+
expect(invalidateRunOwnership).not.toHaveBeenCalled();
363+
expect(resolveSessionSelection).not.toHaveBeenCalled();
364+
});
365+
238366
it("queues session refreshes and applies the latest result", async () => {
239367
let resolveFirst: ((value: unknown) => void) | undefined;
240368
let resolveSecond: ((value: unknown) => void) | undefined;

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

Lines changed: 46 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ type SessionActionContext = {
5050
agentNames: Map<string, string>;
5151
initialSessionInput: string;
5252
initialSessionAgentId: string | null;
53-
resolveSessionSelection: (raw?: string) => { key: string; agentId: string };
53+
resolveSessionSelection: (raw?: string, agentId?: string) => { key: string; agentId: string };
5454
updateHeader: () => void;
5555
updateFooter: () => void;
5656
updateAutocompleteProvider: () => void;
@@ -88,6 +88,45 @@ export function createSessionActions(context: SessionActionContext) {
8888
agentId: state.currentAgentId,
8989
});
9090

91+
const applySessionSelection = (nextSelection: { key: string; agentId: string }) => {
92+
const previousSelection = captureSessionSelection();
93+
const selectionChanged = !(
94+
nextSelection.agentId === previousSelection.agentId &&
95+
agentSessionKeysMatchByRequestKey(nextSelection.key, previousSelection.sessionKey)
96+
);
97+
if (selectionChanged) {
98+
// Retire the previous session's runs before history can adopt a new
99+
// in-flight owner; otherwise its completion can promote an old run.
100+
invalidateRunOwnership?.();
101+
reduceTuiSessionProjection(state, {
102+
type: "sessionReset",
103+
scope: readTuiSessionProjectionScope(state),
104+
});
105+
}
106+
state.currentAgentId = nextSelection.agentId;
107+
state.currentSessionKey = nextSelection.key;
108+
state.activeChatRunId = null;
109+
submit.clearPendingSubmit(state);
110+
setActivityStatus("idle");
111+
if (selectionChanged) {
112+
state.currentSessionId = null;
113+
clearTuiSessionModeOverrides(state.sessionInfo);
114+
}
115+
// Session keys can move backwards in updatedAt ordering; drop previous session freshness
116+
// so refresh data for the newly selected session isn't rejected as stale.
117+
state.sessionInfo.updatedAt = null;
118+
state.historyLoaded = false;
119+
if (selectionChanged) {
120+
// Live prompt identities belong to the old selection, not its pending successor.
121+
chatLog.clearAll();
122+
}
123+
chatLog.clearPendingUsers();
124+
clearLocalRunIds?.();
125+
btw.clear();
126+
updateHeader();
127+
updateFooter();
128+
};
129+
91130
const isCurrentSessionSelection = (selection: { sessionKey: string; agentId: string }): boolean =>
92131
state.currentAgentId === selection.agentId &&
93132
agentSessionKeysMatchByRequestKey(state.currentSessionKey, selection.sessionKey);
@@ -134,8 +173,12 @@ export function createSessionActions(context: SessionActionContext) {
134173
}
135174
state.initialSessionApplied = true;
136175
} else if (!state.agents.some((agent) => agent.id === state.currentAgentId)) {
137-
state.currentAgentId =
176+
const nextAgentId =
138177
state.agents[0]?.id ?? normalizeAgentId(result.defaultId ?? state.currentAgentId);
178+
if (nextAgentId !== state.currentAgentId) {
179+
applySessionSelection(resolveSessionSelection(undefined, nextAgentId));
180+
return;
181+
}
139182
}
140183
updateHeader();
141184
updateFooter();
@@ -599,44 +642,7 @@ export function createSessionActions(context: SessionActionContext) {
599642
};
600643

601644
const setSession = async (rawKey: string) => {
602-
const previousSelection = captureSessionSelection();
603-
const nextSelection = resolveSessionSelection(rawKey);
604-
const nextKey = nextSelection.key;
605-
const selectionChanged = !(
606-
nextSelection.agentId === previousSelection.agentId &&
607-
agentSessionKeysMatchByRequestKey(nextKey, previousSelection.sessionKey)
608-
);
609-
if (selectionChanged) {
610-
// Retire the previous session's runs before history can adopt a new
611-
// in-flight owner; otherwise its completion can promote an old run.
612-
invalidateRunOwnership?.();
613-
reduceTuiSessionProjection(state, {
614-
type: "sessionReset",
615-
scope: readTuiSessionProjectionScope(state),
616-
});
617-
}
618-
state.currentAgentId = nextSelection.agentId;
619-
state.currentSessionKey = nextKey;
620-
state.activeChatRunId = null;
621-
submit.clearPendingSubmit(state);
622-
setActivityStatus("idle");
623-
if (selectionChanged) {
624-
state.currentSessionId = null;
625-
clearTuiSessionModeOverrides(state.sessionInfo);
626-
}
627-
// Session keys can move backwards in updatedAt ordering; drop previous session freshness
628-
// so refresh data for the newly selected session isn't rejected as stale.
629-
state.sessionInfo.updatedAt = null;
630-
state.historyLoaded = false;
631-
if (selectionChanged) {
632-
// Live prompt identities belong to the old selection, not its pending successor.
633-
chatLog.clearAll();
634-
}
635-
chatLog.clearPendingUsers();
636-
clearLocalRunIds?.();
637-
btw.clear();
638-
updateHeader();
639-
updateFooter();
645+
applySessionSelection(resolveSessionSelection(rawKey));
640646
await loadHistory();
641647
};
642648

‎src/tui/tui.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1037,12 +1037,12 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
10371037
return name ? `${id} (${name})` : id;
10381038
};
10391039

1040-
const resolveSessionSelection = (raw?: string) => {
1040+
const resolveSessionSelection = (raw?: string, agentId = state.currentAgentId) => {
10411041
return resolveTuiSessionSelection({
10421042
raw,
10431043
cfg: config,
10441044
sessionScope: state.sessionScope,
1045-
currentAgentId: state.currentAgentId,
1045+
currentAgentId: agentId,
10461046
sessionMainKey: state.sessionMainKey,
10471047
});
10481048
};

0 commit comments

Comments
 (0)