Skip to content

Commit ecbaf5d

Browse files
author
Peter Steinberger
committed
fix(ui): preserve chat attachments and run ownership
1 parent 12297b7 commit ecbaf5d

6 files changed

Lines changed: 297 additions & 7 deletions

File tree

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

Lines changed: 103 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,107 @@ describe("handleChatGatewayEvent", () => {
853853
expect(state.chatStreamSegments).toEqual([]);
854854
});
855855

856+
it.each([
857+
{
858+
name: "provider timeout",
859+
event: {
860+
state: "error",
861+
errorKind: "timeout",
862+
errorMessage: "agent provider timeout",
863+
},
864+
projectionStatus: "timeout",
865+
sessionStatus: "timeout",
866+
errorSummary: "Error: agent provider timeout",
867+
},
868+
{
869+
name: "provider failure",
870+
event: {
871+
state: "error",
872+
errorMessage: "agent provider failure",
873+
},
874+
projectionStatus: "error",
875+
sessionStatus: "failed",
876+
errorSummary: "Error: agent provider failure",
877+
},
878+
{
879+
name: "operator cancellation",
880+
event: { state: "aborted" },
881+
projectionStatus: "aborted",
882+
sessionStatus: "killed",
883+
errorSummary: null,
884+
},
885+
] as const)(
886+
"projects the canonical $name status onto the selected session",
887+
({ event, projectionStatus, sessionStatus, errorSummary }) => {
888+
vi.useFakeTimers();
889+
try {
890+
const state = createState({
891+
sessionKey: "main",
892+
chatRunId: "run-1",
893+
chatStream: "Partial assistant reply",
894+
chatStreamStartedAt: 100,
895+
}) as ChatState & {
896+
chatRunStatus?: { phase: string; runId: string | null; sessionKey: string } | null;
897+
lastLocalTerminalReconcile?: { sessionStatus: string } | null;
898+
sessionsResult?: {
899+
ts: number;
900+
path: string;
901+
count: number;
902+
defaults: Record<string, unknown>;
903+
sessions: Array<Record<string, unknown>>;
904+
};
905+
};
906+
state.sessionsResult = {
907+
ts: 0,
908+
path: "",
909+
count: 1,
910+
defaults: {},
911+
sessions: [
912+
{
913+
key: "main",
914+
kind: "direct",
915+
updatedAt: 1,
916+
hasActiveRun: true,
917+
activeRunIds: ["run-1"],
918+
status: "running",
919+
startedAt: 100,
920+
},
921+
],
922+
};
923+
924+
expect(
925+
handleChatGatewayEvent(state, {
926+
runId: "run-1",
927+
sessionKey: "main",
928+
...event,
929+
}),
930+
).toBe(event.state);
931+
932+
expect(
933+
getChatSessionProjection(state, state.chatMessages, { sessionKey: "main" }).runs["run-1"]
934+
?.status,
935+
).toBe(projectionStatus);
936+
expect(state.sessionsResult.sessions[0]).toMatchObject({
937+
activeRunIds: [],
938+
hasActiveRun: false,
939+
status: sessionStatus,
940+
});
941+
expect(state.lastLocalTerminalReconcile?.sessionStatus).toBe(sessionStatus);
942+
expect(state.chatRunStatus).toMatchObject({
943+
phase: "interrupted",
944+
runId: "run-1",
945+
sessionKey: "main",
946+
});
947+
expect(state.chatRunError?.summary ?? null).toBe(errorSummary);
948+
expect(state.chatRunId).toBeNull();
949+
expect(state.chatStream).toBeNull();
950+
expect(state.chatStreamStartedAt).toBeNull();
951+
} finally {
952+
vi.useRealTimers();
953+
}
954+
},
955+
);
956+
856957
it("reconciles cached run and indicator state on terminal events", () => {
857958
vi.useFakeTimers();
858959
try {
@@ -1950,7 +2051,7 @@ describe("handleChatGatewayEvent", () => {
19502051
},
19512052
);
19522053

1953-
it("does not let a completed run's late error interrupt a newer response", () => {
2054+
it("does not label a newer response with a completed run's late error", () => {
19542055
const state = createState({ sessionKey: "main", chatRunId: "run-completed" });
19552056

19562057
expect(
@@ -1982,7 +2083,7 @@ describe("handleChatGatewayEvent", () => {
19822083
expect(state.chatStream).toBe("Newer response");
19832084
expect(state.chatMessages).toHaveLength(1);
19842085
expectTextChatMessage(state.chatMessages[0], "assistant", "Delivered once.");
1985-
expect(state.chatRunError).toEqual({ summary: "Error: late provider failure" });
2086+
expect(state.chatRunError).toBeNull();
19862087
});
19872088

19882089
it("upgrades an empty final to one authoritative assistant reply", () => {

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

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -273,11 +273,12 @@ function handleChatEvent(
273273
}
274274
if (payload.state === "error") {
275275
if (
276+
(!state.chatRunId || state.chatRunId === payload.runId) &&
276277
payload.errorMessage?.trim() &&
277278
projectedRun.currentRun?.errorMessage !== previousTerminalRun.errorMessage
278279
) {
279-
// A completed transcript is immutable; retain provider guidance without
280-
// adopting its old run or interrupting a newer in-flight response.
280+
// Completed-run diagnostics belong to an idle composer or that same run;
281+
// publishing them over a newer response falsely marks the new run failed.
281282
setChatRunError(state, resolveGatewayErrorText(payload, null));
282283
}
283284
return "error";
@@ -329,7 +330,7 @@ function handleChatEvent(
329330
});
330331
const reconcileTerminalRun = (
331332
outcome: "done" | "interrupted",
332-
sessionStatus: "done" | "failed" | "killed",
333+
sessionStatus: "done" | "failed" | "killed" | "timeout",
333334
) =>
334335
reconcileChatRunLifecycle(state as unknown as Parameters<typeof reconcileChatRunLifecycle>[0], {
335336
outcome,
@@ -459,7 +460,12 @@ function handleChatEvent(
459460
state.chatMessages = materializeVisibleStream({ includeCurrent: true });
460461
}
461462
}
462-
reconcileTerminalRun("interrupted", "failed");
463+
// The shared Gateway projection owns timeout classification; preserve it
464+
// when publishing selected-session and sidebar terminal status.
465+
reconcileTerminalRun(
466+
"interrupted",
467+
projectedRun?.currentRun?.status === "timeout" ? "timeout" : "failed",
468+
);
463469
setChatRunError(
464470
state,
465471
resolveGatewayErrorText(payload, projectedErrorMessage ? visiblePayloadMessage : null),
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
// @vitest-environment node
2+
import { afterEach, describe, expect, it, vi } from "vitest";
3+
import type { ChatAttachment } from "../../lib/chat/chat-types.ts";
4+
import { createSessionCapability } from "../../lib/sessions/index.ts";
5+
import {
6+
getChatAttachmentDataUrl,
7+
registerChatAttachmentPayload,
8+
releaseChatAttachmentPayloads,
9+
} from "./attachment-payload-store.ts";
10+
import type { ChatHost } from "./chat-send-contract.ts";
11+
import { handleSendChat } from "./chat-send-submit.ts";
12+
13+
const attachmentsToRelease: ChatAttachment[] = [];
14+
const attachmentDataUrl = "data:application/pdf;base64,JVBERi0xLjQK";
15+
16+
afterEach(() => {
17+
releaseChatAttachmentPayloads(attachmentsToRelease);
18+
attachmentsToRelease.length = 0;
19+
});
20+
21+
function createStagedAttachment(id: string): ChatAttachment {
22+
const file = new File(["%PDF-1.4\n"], "brief.pdf", { type: "application/pdf" });
23+
const attachment = registerChatAttachmentPayload({
24+
attachment: {
25+
id,
26+
mimeType: "application/pdf",
27+
fileName: "brief.pdf",
28+
sizeBytes: file.size,
29+
},
30+
dataUrl: attachmentDataUrl,
31+
file,
32+
});
33+
attachmentsToRelease.push(attachment);
34+
return attachment;
35+
}
36+
37+
function createImmediateCommandHost(
38+
command: string,
39+
attachment: ChatAttachment,
40+
overrides: Partial<ChatHost> = {},
41+
): ChatHost {
42+
const host = {
43+
sessions: createSessionCapability({
44+
snapshot: { client: null, phase: "reconnecting", hello: null },
45+
subscribe: () => () => undefined,
46+
subscribeEvents: () => () => undefined,
47+
}),
48+
client: null,
49+
connected: true,
50+
sessionKey: "agent:main",
51+
chatLoading: false,
52+
chatMessage: command,
53+
chatMessages: [],
54+
chatLocalInputHistoryBySession: {},
55+
chatInputHistorySessionKey: null,
56+
chatInputHistoryItems: null,
57+
chatInputHistoryIndex: -1,
58+
chatDraftBeforeHistory: null,
59+
chatAttachments: [attachment],
60+
chatQueue: [],
61+
chatRunId: null,
62+
chatSending: false,
63+
chatStream: null,
64+
chatModelCatalog: [],
65+
hello: null,
66+
refreshSessionsAfterChat: new Map(),
67+
...overrides,
68+
} satisfies Partial<ChatHost>;
69+
return host as ChatHost;
70+
}
71+
72+
describe("handleSendChat immediate local commands", () => {
73+
it.each(["/export-session", "/export"])(
74+
"preserves staged attachments while %s exports the chat",
75+
async (command) => {
76+
const attachment = createStagedAttachment("export-att");
77+
const exportCurrentChat = vi.fn();
78+
const host = createImmediateCommandHost(command, attachment, { exportCurrentChat });
79+
80+
await handleSendChat(host);
81+
82+
expect(exportCurrentChat).toHaveBeenCalledOnce();
83+
expect(host.chatMessage).toBe("");
84+
expect(host.chatAttachments).toEqual([attachment]);
85+
expect(getChatAttachmentDataUrl(attachment)).toBe(attachmentDataUrl);
86+
expect(host.chatQueue).toStrictEqual([]);
87+
},
88+
);
89+
90+
it("does not duplicate staged attachments into both old and new session composers", async () => {
91+
const attachment = createStagedAttachment("new-session-att");
92+
const attachmentsBySession = new Map<string, ChatAttachment[]>();
93+
const host = createImmediateCommandHost("/new", attachment);
94+
host.createChatSession = vi.fn(async () => {
95+
const previousSessionKey = host.sessionKey;
96+
const nextSessionKey = "agent:main:new";
97+
// Session creation captures the next composer before route switching
98+
// decides whether the old session's attachment needs a memory fallback.
99+
const createdSessionAttachments = [...host.chatAttachments];
100+
attachmentsBySession.set(previousSessionKey, [...host.chatAttachments]);
101+
host.sessionKey = nextSessionKey;
102+
host.chatAttachments = createdSessionAttachments;
103+
attachmentsBySession.set(nextSessionKey, [...host.chatAttachments]);
104+
return true;
105+
});
106+
107+
await handleSendChat(host);
108+
109+
expect(host.createChatSession).toHaveBeenCalledOnce();
110+
expect(attachmentsBySession.get("agent:main")).toStrictEqual([]);
111+
expect(attachmentsBySession.get("agent:main:new")).toStrictEqual([]);
112+
expect(host.chatAttachments).toStrictEqual([]);
113+
});
114+
115+
it("restores staged attachments when creating a new session is cancelled", async () => {
116+
const attachment = createStagedAttachment("cancelled-new-session-att");
117+
const createChatSession = vi.fn(async () => false);
118+
const host = createImmediateCommandHost("/new", attachment, { createChatSession });
119+
120+
await handleSendChat(host);
121+
122+
expect(createChatSession).toHaveBeenCalledOnce();
123+
expect(host.chatMessage).toBe("/new");
124+
expect(host.chatAttachments).toHaveLength(1);
125+
expect(host.chatAttachments[0]).toMatchObject(attachment);
126+
expect(getChatAttachmentDataUrl(host.chatAttachments[0]!)).toBe(attachmentDataUrl);
127+
});
128+
});

‎ui/src/pages/chat/chat-send-submit.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,11 @@ export async function handleSendChat(
380380
).previousDraft;
381381
} else {
382382
host.chatMessage = "";
383-
host.chatAttachments = [];
383+
// Export leaves the composer in its current session; /new must clear
384+
// attachments before its handoff can capture them under both routes.
385+
if (parsed.command.key !== "export-session") {
386+
host.chatAttachments = [];
387+
}
384388
resetChatInputHistoryNavigation(host);
385389
}
386390
}

‎ui/src/pages/chat/run-lifecycle.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { SessionsListResult } from "../../api/types.ts";
66
import { isSessionRunActive } from "../../lib/session-run-state.ts";
77
import {
88
CHAT_RUN_STATUS_TOAST_DURATION_MS,
9+
handleAbortChat,
910
hasAbortableSessionRun,
1011
reconcileChatRunFromCurrentSessionRow,
1112
reconcileChatRunFromSessionRow,
@@ -62,6 +63,52 @@ function makeAbortHost(over: Partial<AbortHost> = {}): AbortHost {
6263
};
6364
}
6465

66+
describe("handleAbortChat", () => {
67+
it("shows reconnect guidance when an offline session run has no browser run identity", async () => {
68+
const request = vi.fn();
69+
const client = { request } as unknown as GatewayBrowserClient;
70+
const host = makeAbortHost({
71+
client,
72+
connected: false,
73+
chatMessage: "keep this draft",
74+
sessionsResult: makeSessionsResult([
75+
{ key: "agent:main", hasActiveRun: true, status: "running" },
76+
]),
77+
});
78+
79+
expect(hasAbortableSessionRun(host)).toBe(true);
80+
await handleAbortChat(host, { preserveDraft: true });
81+
82+
expect(host.chatError).toBe("Not connected. Try again after reconnecting.");
83+
expect(host.lastError).toBe(host.chatError);
84+
expect(host.chatMessage).toBe("keep this draft");
85+
expect(host.pendingAbort).toBeUndefined();
86+
expect(request).not.toHaveBeenCalled();
87+
});
88+
89+
it("keeps offline exact-run stops safely queued for reconnect", async () => {
90+
const request = vi.fn();
91+
const client = { request } as unknown as GatewayBrowserClient;
92+
const host = makeAbortHost({
93+
client,
94+
connected: false,
95+
chatRunId: "run-main",
96+
chatMessage: "keep this draft",
97+
});
98+
99+
await handleAbortChat(host, { preserveDraft: true });
100+
101+
expect(host.pendingAbort).toEqual({
102+
sourceClient: client,
103+
sessionKey: "agent:main",
104+
runId: "run-main",
105+
});
106+
expect(host.chatMessage).toBe("keep this draft");
107+
expect(host.chatError ?? null).toBeNull();
108+
expect(request).not.toHaveBeenCalled();
109+
});
110+
});
111+
65112
describe("replayPendingChatAbort", () => {
66113
it("dispatches a queued exact browser run stop through chat.abort", async () => {
67114
const request = vi.fn(async () => ({ aborted: true }));

‎ui/src/pages/chat/run-lifecycle.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { GatewayBrowserClient } from "../../api/gateway.ts";
22
import type { GatewaySessionRow, SessionRunStatus, SessionsListResult } from "../../api/types.ts";
3+
import { t } from "../../i18n/index.ts";
34
import { isSessionRunActive } from "../../lib/session-run-state.ts";
45
import {
56
reconcileSessionRunTerminal,
@@ -260,6 +261,9 @@ export async function handleAbortChat(host: ChatAbortHost, opts?: ChatAbortOptio
260261
: null;
261262
const pendingAbort = disconnectedIntent?.runId ? disconnectedIntent : null;
262263
if (!host.connected && !pendingAbort) {
264+
// Session-only stops cannot be replayed safely against a later run.
265+
// Explain the blocked action instead of leaving the visible Stop inert.
266+
setChatError(host, t("chat.questions.disconnected"));
263267
return;
264268
}
265269
if (!opts?.preserveDraft) {

0 commit comments

Comments
 (0)