From 0a859deeb17a79bea6140f9a8ec9a92652572cff Mon Sep 17 00:00:00 2001 From: tianzishen Date: Thu, 29 Oct 2026 14:29:50 +0800 Subject: [PATCH 1/2] fix(chat): stop showing one failed run's error three times MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A terminal non-quota error (provider failure, interrupt) rendered the same text simultaneously as a Request failed toast, a shelf notice and the assistant bubble's inline banner. For a run that produced a reply, the bubble banner — stamped live or carried by the transcript reload — is now the single rendering; the shelf notice stays as the in-chat message for silent stops, and the duplicate toasts are gone. --- CHANGELOG.md | 1 + hooks/useAgentSession.ts | 18 +++++++++--------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 304da937a..799452e1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **No blank band above the composer on phones either.** Scrolling to the newest message could also shift the message area itself up, leaving an empty band above the composer until the page was reloaded. Scrolling can no longer shift the message area (Safari 16 and later; older Safari keeps the old behavior). - **Sending to a session another omp process has open no longer leaves a dead fork.** When omp moved the resumed session to a new file during startup, the tab kept the old id, the event stream failed with "Failed to connect to the agent event stream", the prompt never went, and the forked session was reaped two minutes later. The requested id now stays routable alongside the new one. - **Changing Advisor keeps a moved session on the right conversation.** A tab still using the pre-move session ID now restarts the current session file on its owning host when toggling Advisor, instead of reopening the original file, selecting another host’s copy, or returning “Session not found” if the original was removed. +- **A failed run no longer shows its error three times.** A terminal error (provider failure, interrupt) used to appear simultaneously as a top-right "Request failed" toast, a shelf notice above the composer, and the assistant bubble's inline banner, all with the same text. For a run that produced a reply, the inline banner — stamped live, or carried by the transcript reload — is now the single rendering; the shelf notice remains the in-chat message for silent stops, and the duplicate toast is gone. --- diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 2baaeb649..29cad105b 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -1879,12 +1879,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (!recoveryLoaded && !hadContent && !runError && !quotaMessage && !allowEmptyResponse) return; if (!agentRunningRef.current) return; if (runError) { + // The shelf notice is the in-chat record here; no duplicate toast. addNotice({ type: "error", message: runError }); - if (!isQuotaLikeError(runError)) { - toast.error("Request failed", runError, { timeout: 12000 }); - } else { - surfaceQuotaOnStream(runError); - } + if (isQuotaLikeError(runError)) surfaceQuotaOnStream(runError); } else if (quotaMessage && isQuotaLikeError(quotaMessage) && !hadContent) { // Silent stop: no assistant bubble to stamp — the shelf notice is the // in-chat message. Mid-run quota already toasted via the notice path. @@ -1896,7 +1893,6 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // an assistant message, hence allowEmptyResponse above. const message = translate("agentSession.responseFailed"); addNotice({ type: "error", message }); - toast.error("Request failed", message, { timeout: 10000 }); } catchUp.invalidate(); eventCoalescer.reset(); @@ -2330,14 +2326,18 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const errorMessage = terminalError ?? (!hadContent && quotaMessage && isQuotaLikeError(quotaMessage) ? quotaMessage : null); if (errorMessage) { - addNotice({ type: "error", message: errorMessage }); if (isQuotaLikeError(errorMessage)) { // Inline chat banner on the live bubble when still streaming; // otherwise the shelf notice is the in-chat message. No toast — // quota must read as a chat message, not a transient popup. surfaceQuotaOnStream(errorMessage); - } else { - toast.error("Request failed", errorMessage, { timeout: 12000 }); + addNotice({ type: "error", message: errorMessage }); + } else if (!hadContent) { + // A content-producing run renders the error on its assistant + // bubble (stamped live, or carried by the transcript the reload + // below brings in) — a notice or toast on top would duplicate it. + // Without one, the shelf notice is the in-chat message. + addNotice({ type: "error", message: errorMessage }); } } // async, and a next prompt (or session switch) that starts while it is From 1af365321b3039ba6d090fead3ac58ef2d5a3f89 Mon Sep 17 00:00:00 2001 From: tianzishen Date: Mon, 9 Nov 2026 16:37:58 +0800 Subject: [PATCH 2/2] fix(chat): retain independent run errors --- CHANGELOG.md | 2 +- hooks/useAgentSession-notices.ts | 2 +- hooks/useAgentSession.rpc.test.mjs | 315 ++++++++++++++++++++++++++++- hooks/useAgentSession.ts | 195 ++++++++++++++++-- 4 files changed, 488 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 799452e1d..6a551ab46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,7 +116,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **No blank band above the composer on phones either.** Scrolling to the newest message could also shift the message area itself up, leaving an empty band above the composer until the page was reloaded. Scrolling can no longer shift the message area (Safari 16 and later; older Safari keeps the old behavior). - **Sending to a session another omp process has open no longer leaves a dead fork.** When omp moved the resumed session to a new file during startup, the tab kept the old id, the event stream failed with "Failed to connect to the agent event stream", the prompt never went, and the forked session was reaped two minutes later. The requested id now stays routable alongside the new one. - **Changing Advisor keeps a moved session on the right conversation.** A tab still using the pre-move session ID now restarts the current session file on its owning host when toggling Advisor, instead of reopening the original file, selecting another host’s copy, or returning “Session not found” if the original was removed. -- **A failed run no longer shows its error three times.** A terminal error (provider failure, interrupt) used to appear simultaneously as a top-right "Request failed" toast, a shelf notice above the composer, and the assistant bubble's inline banner, all with the same text. For a run that produced a reply, the inline banner — stamped live, or carried by the transcript reload — is now the single rendering; the shelf notice remains the in-chat message for silent stops, and the duplicate toast is gone. +- **A failed run no longer shows its error three times.** The duplicate "Request failed" toast is gone. A non-quota error already shown on the current run's assistant message does not also need a shelf notice; standalone errors and errors whose message cannot be confirmed remain visible in the shelf, even after partial output. If the matching assistant message is saved later, it replaces only that run's duplicate notice. Quota handling is unchanged and may show both an inline banner and a shelf notice. --- diff --git a/hooks/useAgentSession-notices.ts b/hooks/useAgentSession-notices.ts index 5a6341c9f..c18062388 100644 --- a/hooks/useAgentSession-notices.ts +++ b/hooks/useAgentSession-notices.ts @@ -71,7 +71,7 @@ export function noticeReducer(state: NoticeState, action: NoticeAction): NoticeS return { ...state, visible: markOldestNoticeExiting(state.visible) }; case "remove": { const visible = state.visible.filter((notice) => notice.id !== action.id); - return fillPendingNotices(visible, state.pending); + return fillPendingNotices(visible, state.pending.filter((notice) => notice.id !== action.id)); } default: return state; diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 5e3c3cfda..150bc9a0f 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1358,6 +1358,310 @@ test("provider error on the assistant message is shown instead of ending silentl assert.ok(w.latest.notices.some((notice) => notice.message === providerError), "the provider error must be visible"); }); +for (const terminal of ["rpc_frame_error", "turn_end", "agent_end"]) { + test(`${terminal} after assistant text remains visible without a duplicate toast`, async () => { + resetWorld(); + toastCalls.length = 0; + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const failure = "Malformed RPC frame after assistant text"; + await act(async () => { + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + es.emit({ type: "message_end", message: { ...assistantMsg("a1", "Partial answer"), timestamp: 42 } }); + if (terminal !== "agent_end") es.emit({ type: terminal, errorMessage: failure }); + es.emit({ type: "agent_end", isTerminal: true, ...(terminal === "agent_end" ? { errorMessage: failure } : {}) }); + }); + await settle(); + assert.equal(w.latest.agentRunning, false); + assert.ok(w.latest.messages.some((m) => m.role === "assistant" && m.content[0]?.text === "Partial answer")); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); + assert.equal(toastCalls.some((call) => call[0] === "error" && call[1] === "Request failed"), false); + }); +} + +for (const saved of ["same message", "different message", "no saved error"]) { + test(`a message-carried provider error with ${saved} after terminal reload`, async () => { + resetWorld(); + toastCalls.length = 0; + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const failure = "Provider disconnected during generation"; + const reply = { ...assistantMsg("a1", "Partial answer"), timestamp: 42, stopReason: "error", errorMessage: failure }; + await act(async () => { + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + es.emit({ type: "message_end", message: reply }, { persist: false }); + const savedReply = saved === "same message" ? reply + : saved === "different message" ? { ...reply, timestamp: 43 } + : { ...assistantMsg("a1", "Partial answer"), timestamp: 42 }; + saveSession("s1", [userMsg("u0", "old question"), userMsg("u1", "new question"), savedReply]); + es.emit({ type: "agent_end", isTerminal: true }); + }); + await settle(); + assert.equal(w.latest.agentRunning, false); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), + saved === "same message" ? [] : [failure]); + if (saved === "same message") { + assert.equal(w.latest.messages.at(-1).errorMessage, failure); + const bubble = ownRoot(render(React.createElement(MessageView, { message: w.latest.messages.at(-1) }), { wrapper: TestRoot })); + assert.ok(bubble.getByText(failure), "the assistant actually renders the provider error"); + } + assert.equal(toastCalls.some((call) => call[0] === "error" && call[1] === "Request failed"), false); + }); +} + +for (const location of ["saved", "not saved"]) { + test(`an error-only assistant message is deduplicated only when visible: ${location}`, async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const failure = "Provider disconnected during generation"; + const reply = { ...assistantMsg("a1", ""), content: [], timestamp: 42, stopReason: "error", errorMessage: failure }; + await act(async () => { + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + es.emit({ type: "message_end", message: reply }, { persist: false }); + if (location !== "not saved") { + saveSession("s1", [userMsg("u0", "old question"), userMsg("u1", "new question"), reply]); + } + es.emit({ type: "agent_end", isTerminal: true }); + }); + await settle(); + assert.equal(w.latest.agentRunning, false); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), + location === "saved" ? [] : [failure]); + if (location === "saved") { + const bubble = ownRoot(render(React.createElement(MessageView, { message: w.latest.messages.at(-1) }), { wrapper: TestRoot })); + assert.ok(bubble.getByText(failure), "the saved error-only message renders a banner"); + } + }); +} + +test("a run started elsewhere keeps its error visible while an older branch is selected", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const w = await mountSession("s1"); + world.views.set("s1:branch:false", { leafId: "branch", messages: [userMsg("old", "selected branch")], entryIds: ["branch-entry"] }); + await act(async () => { await w.changeLeaf("branch"); }); + assert.deepEqual(w.latest.entryIds, ["branch-entry"], "the user is viewing the historical branch"); + world.agents.set("s1", { running: true, state: { isStreaming: true, isPromptRunning: true } }); + await act(async () => { + world.runningStreams.at(-1).deliver({ type: "message", data: JSON.stringify({ type: "running", runningSessionIds: ["s1"] }) }); + await settle(); + lastEs().open(); + await settle(); + }); + const es = lastEs(); + const failure = "Provider disconnected during generation"; + const reply = { ...assistantMsg("a1", ""), content: [], timestamp: 42, stopReason: "error", errorMessage: failure }; + await act(async () => { + es.emit({ type: "agent_start" }); + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + es.emit({ type: "message_end", message: reply }, { persist: false }); + saveSession("s1", [userMsg("u0", "old question"), userMsg("u1", "new question"), reply]); + es.emit({ type: "agent_end", isTerminal: true }); + }); + await settle(); + assert.equal(w.latest.agentRunning, false); + assert.deepEqual(w.latest.entryIds, ["branch-entry"], "the failed current-run message is not in the selected branch"); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); +}); + +for (const ending of ["message_end", "turn_end", "agent_end", "recovery"]) { + test(`${ending} error stays visible until its late saved assistant message replaces the notice`, async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const failure = "Provider disconnected during generation"; + const reply = { ...assistantMsg("a1", ""), content: [], timestamp: 42, stopReason: "error", errorMessage: failure }; + await act(async () => { + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + es.emit({ type: "message_end", message: reply }, { persist: false }); + if (ending === "turn_end") es.emit({ type: "turn_end", message: reply }); + if (ending === "recovery") es.emit({ type: "prompt_result", agentInvoked: false }); + else es.emit({ type: "agent_end", isTerminal: true, ...(ending === "agent_end" ? { messages: [reply] } : {}) }); + }); + await settle(); + assert.equal(w.latest.agentRunning, false); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure], + "an unsaved error-only message cannot carry the error visibly"); + await act(async () => { + appendEntry("s1", reply); + publishSessionsChanged(["s1"]); + }); + await settle(); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), []); + const bubble = ownRoot(render(React.createElement(MessageView, { message: w.latest.messages.at(-1) }), { wrapper: TestRoot })); + assert.ok(bubble.getByText(failure), "the saved error banner replaces the notice"); + }); +} + +for (const ending of ["agent_end", "recovery"]) { + test(`${ending} exposes an error-only failure while transcript loading is blocked`, async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const failure = "Provider disconnected during generation"; + const reply = { ...assistantMsg("a1", ""), content: [], timestamp: 42, stopReason: "error", errorMessage: failure }; + let release; + world.holds.push({ + match: (method, url) => method === "GET" && url.startsWith("/api/sessions/s1?"), + produce: () => new Promise((resolve) => { + release = () => { + const fixture = world.sessions.get("s1"); + resolve({ value: { sessionId: "s1", filePath: "/fixture/session.jsonl", tree: [], + leafId: fixture.leafId, context: { todoPhases: [], thinkingLevel: "off", model: null, ...fixture } } }); + }; + }), + }); + await act(async () => { + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + es.emit({ type: "message_end", message: reply }, { persist: false }); + if (ending === "recovery") es.emit({ type: "prompt_result", agentInvoked: false }); + else es.emit({ type: "agent_end", isTerminal: true }); + await sleep(20); + }); + assert.ok(release, "the transcript request is held"); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); + await act(async () => { release(); }); + await settle(); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); + }); +} + +test("a queued error notice is removed when its message appears without removing other notices", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const failure = "Provider disconnected during generation"; + const reply = { ...assistantMsg("a1", ""), content: [], timestamp: 42, stopReason: "error", errorMessage: failure }; + await act(async () => { + for (let i = 0; i < 5; i++) es.emit({ type: "notice", level: "info", message: `Unrelated notice ${i}` }); + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + es.emit({ type: "message_end", message: reply }, { persist: false }); + es.emit({ type: "agent_end", isTerminal: true }); + }); + await act(async () => { appendEntry("s1", reply); publishSessionsChanged(["s1"]); }); + await settle(30); + assert.ok(w.latest.notices.some((n) => n.message.startsWith("Unrelated notice"))); + await act(async () => { for (const notice of w.latest.notices) w.latest.dismissNotice(notice.id); }); + await settle(); + assert.equal(w.latest.notices.some((n) => n.message === failure), false, "the pending duplicate cannot appear later"); +}); + +for (const order of ["frame before message", "frame after message"]) { + test(`a late equal-looking saved assistant error cannot retract an independent error: ${order}`, async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const failure = "Provider disconnected during generation"; + const reply = { ...assistantMsg("a1", ""), content: [], timestamp: 42, stopReason: "error", errorMessage: failure }; + await act(async () => { + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + if (order === "frame before message") es.emit({ type: "rpc_frame_error", errorMessage: failure }); + es.emit({ type: "message_end", message: reply }, { persist: false }); + if (order === "frame after message") es.emit({ type: "rpc_frame_error", errorMessage: failure }); + es.emit({ type: "agent_end", isTerminal: true, messages: [reply] }); + }); + await settle(); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); + await act(async () => { appendEntry("s1", reply); publishSessionsChanged(["s1"]); }); + await settle(); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); + }); +} + +for (const change of ["new run", "historical branch"]) { + test(`a late saved error cannot retract a notice in a ${change}`, async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const failure = "Provider disconnected during generation"; + const reply = { ...assistantMsg("a1", ""), content: [], timestamp: 42, stopReason: "error", errorMessage: failure }; + await act(async () => { + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + es.emit({ type: "message_end", message: reply }, { persist: false }); + es.emit({ type: "agent_end", isTerminal: true }); + }); + await settle(); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); + if (change === "new run") { + await act(async () => { es.emit({ type: "agent_start" }); }); + } else { + world.views.set("s1:branch:false", { leafId: "branch", messages: [userMsg("old", "selected branch")], entryIds: ["branch-entry"] }); + await act(async () => { await w.changeLeaf("branch"); }); + } + await act(async () => { appendEntry("s1", reply); publishSessionsChanged(["s1"]); }); + await settle(); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); + }); +} + +test("an independent error is not hidden by an equal-looking assistant error", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const failure = "Provider disconnected during generation"; + const reply = { ...assistantMsg("a1", "Partial answer"), timestamp: 42, stopReason: "error", errorMessage: failure }; + await act(async () => { + es.emit({ type: "message_end", message: userMsg("u1", "new question") }); + es.emit({ type: "message_end", message: reply }); + es.emit({ type: "rpc_frame_error", errorMessage: failure }); + es.emit({ type: "agent_end", isTerminal: true }); + }); + await settle(); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); +}); + +for (const previous of ["same turn", "previous turn"]) { + test(`recovery keeps an independent error despite an equal-looking ${previous} error`, async () => { + resetWorld(); + const failure = "Provider disconnected during generation"; + const oldReply = { ...assistantMsg("a0", "Old answer"), timestamp: 41, stopReason: "error", errorMessage: failure }; + const history = [userMsg("u0", "old question"), ...(previous === "previous turn" ? [oldReply] : [])]; + primeSession("s1", history); + const { w, es } = await startRun("s1", "new question"); + const reply = previous === "same turn" ? { ...oldReply, timestamp: 42 } : assistantMsg("a1", "Partial answer"); + saveSession("s1", [...history, userMsg("u1", "new question"), reply]); + await act(async () => { + es.emit({ type: "rpc_frame_error", errorMessage: failure }); + es.emit({ type: "prompt_result", agentInvoked: false }); + }); + await settle(); + assert.equal(w.latest.agentRunning, false); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); + }); +} + +test("recovery does not use a previous turn's saved error as the current failure", async () => { + resetWorld(); + const failure = "Provider disconnected during generation"; + const oldReply = { ...assistantMsg("a0", "Old answer"), timestamp: 42, stopReason: "error", errorMessage: failure }; + primeSession("s1", [userMsg("u0", "old question"), oldReply]); + const { w, es } = await startRun("s1", "new question"); + await act(async () => { + es.emit({ type: "message_end", message: { ...oldReply, content: [{ type: "text", text: "New partial answer" }] } }, { persist: false }); + es.emit({ type: "prompt_result", agentInvoked: false }); + }); + await settle(); + assert.equal(w.latest.agentRunning, false); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [failure]); +}); + +test("recovery retains a frame error that differs from the saved assistant error", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "old question")]); + const { w, es } = await startRun("s1", "new question"); + const reply = { ...assistantMsg("a1", "Partial answer"), timestamp: 42, stopReason: "error", errorMessage: "Earlier provider failure" }; + saveSession("s1", [userMsg("u0", "old question"), userMsg("u1", "new question"), reply]); + await act(async () => { + es.emit({ type: "rpc_frame_error", errorMessage: "Malformed RPC frame" }); + es.emit({ type: "prompt_result", agentInvoked: false }); + }); + await settle(); + assert.equal(w.latest.agentRunning, false); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), ["Malformed RPC frame"]); + assert.equal(w.latest.messages.at(-1).errorMessage, "Earlier provider failure"); +}); + test("a silent idle transition shows a fallback error instead of disappearing", async () => { resetWorld(); primeSession("s1", [userMsg("u0", "q")]); @@ -1452,7 +1756,8 @@ test("recovery preserves a saved provider failure even after partial response co }); await settle(); assert.equal(w.latest.agentRunning, false); - assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), [providerError]); + assert.equal(w.latest.messages.at(-1).errorMessage, providerError); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), []); }); test("a failed transcript reload is retried instead of being classified as an empty response", async () => { @@ -1528,8 +1833,8 @@ for (const result of ["visible answer", "provider failure"]) { await settle(); assert.equal(w.latest.agentRunning, false); assert.equal(w.latest.messages.at(-1).content[0].text, "Visible response"); - assert.deepEqual(w.latest.notices.filter((n) => n.type === "error").map((n) => n.message), - result === "provider failure" ? ["Provider rejected the request"] : []); + if (result === "provider failure") assert.equal(w.latest.messages.at(-1).errorMessage, "Provider rejected the request"); + assert.deepEqual(w.latest.notices.filter((n) => n.type === "error"), []); }); } @@ -4926,9 +5231,11 @@ test("a saved provider failure still surfaces when its SSE completion arrives be }); await settle(); assert.equal(w.latest.agentRunning, false); - assert.ok(w.latest.notices.some((notice) => notice.type === "error" && notice.message === providerError)); + assert.deepEqual(w.latest.notices.filter((notice) => notice.type === "error"), []); assert.deepEqual(w.latest.entryIds, ["e0", "e1", "e2"]); assert.equal(w.latest.messages.filter((message) => message.role === "assistant" && message.errorMessage === providerError).length, 1); + const bubble = ownRoot(render(React.createElement(MessageView, { message: w.latest.messages.at(-1) }), { wrapper: TestRoot })); + assert.ok(bubble.getByText(providerError), "the recovered saved message renders the failure to the user"); }); test("terminal full refresh updates branch metadata as well as cursor-owned history", async () => { diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 29cad105b..e3b481c47 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -185,6 +185,38 @@ function readTerminalAgentError(event: AgentEvent): string | null { return null; } +type ErrorAssistantSource = { error: string; timestamp: number }; + +// A terminal envelope can carry an assistant message, or an unrelated error +// field. Equal text alone never establishes that the message caused the error. +function terminalErrorAssistant(event: AgentEvent, error: string): ErrorAssistantSource | null { + if (readAgentError(event.errorMessage) || readAgentError(event.error)) return null; + const values = [event.message, ...(Array.isArray(event.messages) ? [...event.messages].reverse() : [])]; + for (const value of values) { + if (!readAgentError(value)) continue; + if (isRecord(value) && value.role === "assistant" && typeof value.timestamp === "number" + && typeof value.errorMessage === "string" && value.errorMessage.trim() === error) { + return { error, timestamp: value.timestamp }; + } + return null; + } + return null; +} + +// Only a new entry in the latest user turn can represent this run's error. +function currentRunAssistant(context: SessionData["context"], previousEntryIds: readonly string[] | null): AgentMessage | null { + if (!previousEntryIds) return null; + const { messages, entryIds } = context; + const userIndex = messages.findLastIndex((message) => message.role === "user"); + if (userIndex < 0 || !entryIds[userIndex] || previousEntryIds.includes(entryIds[userIndex])) return null; + for (let i = messages.length - 1; i > userIndex; i -= 1) { + if (messages[i].role === "assistant") { + return entryIds[i] && !previousEntryIds.includes(entryIds[i]) ? messages[i] : null; + } + } + return null; +} + export interface UseAgentSessionOptions { session: SessionInfo | null; newSessionCwd: string | null; @@ -600,6 +632,17 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // agent_end itself is often deliberately payload-free. Keep the message // until the terminal path can surface it exactly once. const lastRunErrorRef = useRef(null); + // Identity of a message-sourced error, not merely an equal-looking error frame. + const runErrorAssistantRef = useRef(null); + const independentRunErrorRef = useRef(null); + const unconfirmedErrorNoticeRef = useRef<{ + id: string; + sessionId: string; + runId: number; + responseVersion: number; + previousEntryIds: readonly string[]; + source: ErrorAssistantSource; + } | null>(null); const lastShownExitRef = useRef(null); const runHadContentRef = useRef(false); // Native starts/epoch changes also fence recovery, even without a local send. @@ -638,6 +681,16 @@ export function useAgentSession(opts: UseAgentSessionOptions) { scope: () => hookAliveRef.current && !editInFlightRef.current ? `${sessionIdRef.current}:${promptRunIdRef.current}:${contextRequestSeqRef.current}` : null, metadataVersion: () => authoritativeModelSeqRef.current, history: (context, leafId, metadata) => { + const pending = unconfirmedErrorNoticeRef.current; + if (pending && sessionIdRef.current === pending.sessionId && promptRunIdRef.current === pending.runId + && responseRunVersionRef.current === pending.responseVersion && !catchUpRef.current?.view().leafId) { + const assistant = currentRunAssistant(context, pending.previousEntryIds); + if (assistant?.role === "assistant" && assistant.timestamp === pending.source.timestamp + && assistant.errorMessage?.trim() === pending.source.error) { + dispatchNotice({ type: "remove", id: pending.id }); + unconfirmedErrorNoticeRef.current = null; + } + } setMessages(context.messages); setEntryIds(context.entryIds); setData((current) => current ? { ...current, context } : current); @@ -1412,6 +1465,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; eventCoalescer.reset(); dispatch({ type: "reset" }); clearLiveToolResults(); @@ -1682,6 +1737,21 @@ export function useAgentSession(opts: UseAgentSessionOptions) { }); }, []); + const addUnconfirmedRunErrorNotice = useCallback(( + error: string, source: ErrorAssistantSource | null, sid: string | null, + runId: number, responseVersion: number, previousEntryIds: readonly string[] | null, + ) => { + const pending = unconfirmedErrorNoticeRef.current; + if (pending && source && pending.sessionId === sid && pending.runId === runId + && pending.responseVersion === responseVersion && pending.source.error === error + && pending.source.timestamp === source.timestamp) return; + const id = createNoticeId(); + if (source?.error === error && sid && previousEntryIds) { + unconfirmedErrorNoticeRef.current = { id, sessionId: sid, runId, responseVersion, previousEntryIds, source }; + } + addNotice({ id, type: "error", message: error }); + }, [addNotice]); + const respondToExtensionUi = useCallback(async ( request: ExtensionUiDialogRequest, response: { value: string } | { confirmed: boolean } | { cancelled: true } | { answers: RpcAskDialogAnswer[] }, @@ -1840,6 +1910,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const allowEmptyResponse = slashCommandRunRef.current; const previousEntryIds = runPreviousEntryIdsRef.current; if (previousEntryIds === null) return; + let provisionalError: string | null = null; + const initialSource = runErrorAssistantRef.current; + if (agentRunningRef.current && sid && runError && !isQuotaLikeError(runError) + && independentRunErrorRef.current !== runError && initialSource?.error === runError) { + const history = catchUp.history(); + const assistant = history && !catchUp.view().leafId ? currentRunAssistant(history, previousEntryIds) : null; + if (assistant?.role !== "assistant" || assistant.timestamp !== initialSource.timestamp + || assistant.errorMessage?.trim() !== runError) { + addUnconfirmedRunErrorNotice(runError, initialSource, sid, runId, responseVersion, previousEntryIds); + provisionalError = runError; + } + } + let recoveredAssistant: AgentMessage | null = null; let recoveryLoaded = false; let stillBusy = false; try { @@ -1854,12 +1937,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) { const state = loaded.agentState?.state; stillBusy = !!(state?.isStreaming || state?.isPromptRunning || state?.isCompacting); if (!promptDispatchPendingRef.current && state?.responseObserved) hadContent = true; - const { messages, entryIds = [] } = loaded.context; - // Only the latest user turn can answer the current prompt. Entry ids - // distinguish repeated same-text prompts from the previous saved turn. + const { messages, entryIds } = loaded.context; const userIndex = messages.findLastIndex((message) => message.role === "user"); - const userEntryId = entryIds[userIndex]; - if (userIndex >= 0 && userEntryId && !previousEntryIds.includes(userEntryId)) { + if (userIndex >= 0 && entryIds[userIndex] && !previousEntryIds.includes(entryIds[userIndex])) { for (let i = userIndex + 1; i < messages.length; i += 1) { const message = messages[i]; if (message.role !== "assistant") continue; @@ -1867,6 +1947,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runError = readAgentError(message) ?? runError; } } + recoveredAssistant = currentRunAssistant(loaded.context, previousEntryIds); } } finally { if (!hookAliveRef.current || promptRunIdRef.current !== runId || sessionIdRef.current !== sid @@ -1879,9 +1960,22 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (!recoveryLoaded && !hadContent && !runError && !quotaMessage && !allowEmptyResponse) return; if (!agentRunningRef.current) return; if (runError) { - // The shelf notice is the in-chat record here; no duplicate toast. - addNotice({ type: "error", message: runError }); - if (isQuotaLikeError(runError)) surfaceQuotaOnStream(runError); + const source = independentRunErrorRef.current === runError ? null : runErrorAssistantRef.current; + const currentHistory = catchUp.history(); + if (source && currentHistory && !catchUp.view().leafId) { + recoveredAssistant = currentRunAssistant(currentHistory, previousEntryIds); + } + const transcriptIsSource = !lastRunErrorRef.current; + const sameAssistant = transcriptIsSource || (source?.error === runError + && recoveredAssistant?.timestamp !== undefined && source.timestamp === recoveredAssistant.timestamp); + const represented = !catchUp.view().leafId && sameAssistant + && recoveredAssistant?.role === "assistant" && recoveredAssistant.errorMessage?.trim() === runError; + if (isQuotaLikeError(runError)) { + addNotice({ type: "error", message: runError }); + surfaceQuotaOnStream(runError); + } else if (!represented && !(provisionalError === runError && independentRunErrorRef.current === runError)) { + addUnconfirmedRunErrorNotice(runError, source, sid, runId, responseVersion, previousEntryIds); + } } else if (quotaMessage && isQuotaLikeError(quotaMessage) && !hadContent) { // Silent stop: no assistant bubble to stamp — the shelf notice is the // in-chat message. Mid-run quota already toasted via the notice path. @@ -1915,10 +2009,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; slashCommandRunRef.current = false; onAgentEnd?.(); } - }, [addNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, loadSession, onAgentEnd, refreshSubagentHistory, resetSubagentActivityState, surfaceQuotaOnStream]); + }, [addNotice, addUnconfirmedRunErrorNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, loadSession, onAgentEnd, refreshSubagentHistory, resetSubagentActivityState, surfaceQuotaOnStream]); const waitForPromptSettlement = useCallback(async (sid: string, runId?: number) => { await delay(PROMPT_SETTLE_INITIAL_DELAY_MS); const startedAt = Date.now(); @@ -2285,6 +2381,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; break; case "agent_end": { // isTerminal === false means an async delivery resumes this run soon. @@ -2332,12 +2430,27 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // quota must read as a chat message, not a transient popup. surfaceQuotaOnStream(errorMessage); addNotice({ type: "error", message: errorMessage }); - } else if (!hadContent) { - // A content-producing run renders the error on its assistant - // bubble (stamped live, or carried by the transcript the reload - // below brings in) — a notice or toast on top would duplicate it. - // Without one, the shelf notice is the in-chat message. - addNotice({ type: "error", message: errorMessage }); + } else { + // A frame-level error is independent even if its text happens to + // equal an earlier message. Only a saved copy of the originating + // assistant message can replace its notice. + const source = independentRunErrorRef.current === errorMessage ? null + : readTerminalAgentError(event) ? terminalErrorAssistant(event, errorMessage) : runErrorAssistantRef.current; + const previousEntryIds = runPreviousEntryIdsRef.current; + const endedSid = sessionIdRef.current; + const endedRunId = promptRunIdRef.current; + const responseVersion = responseRunVersionRef.current; + if (source?.error === errorMessage && endedSid) { + const history = catchUp.history(); + const assistant = history && !catchUp.view().leafId + ? currentRunAssistant(history, previousEntryIds) : null; + if (assistant?.role !== "assistant" || assistant.timestamp !== source.timestamp + || assistant.errorMessage?.trim() !== errorMessage) { + addUnconfirmedRunErrorNotice(errorMessage, source, endedSid, endedRunId, responseVersion, previousEntryIds); + } + } else { + addNotice({ type: "error", message: errorMessage }); + } } } // async, and a next prompt (or session switch) that starts while it is @@ -2358,6 +2471,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; slashCommandRunRef.current = false; if (endedSid) { void loadSession(endedSid, false, false, endedRunId); @@ -2418,6 +2533,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) { ?? readAgentError(event.message) ?? translate("agentSession.commandFailed"); lastRunErrorRef.current = promptMsg; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = promptMsg; + unconfirmedErrorNoticeRef.current = null; // A failed prompt is terminal: no agent_end follows it. Without this the // spinner and the locked input wait for the 15s reconcile poll. Fenced // with the run id for the same reason as prompt_result above. @@ -2437,6 +2555,9 @@ export function useAgentSession(opts: UseAgentSessionOptions) { case "rpc_frame_error": { const message = readTerminalAgentError(event) ?? translate("agentSession.responseFailed"); lastRunErrorRef.current = message; + runErrorAssistantRef.current = null; + unconfirmedErrorNoticeRef.current = null; + independentRunErrorRef.current = message; if (!agentRunningRef.current) addNotice({ type: "error", message }); break; } @@ -2533,7 +2654,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (!agentRunningRef.current || catchUp.view().leafId) break; const msg = event.message as Partial | undefined; const messageError = readAgentError(msg); - if (messageError) lastRunErrorRef.current = messageError; + if (messageError) { + lastRunErrorRef.current = messageError; + runErrorAssistantRef.current = msg?.role === "assistant" && msg.errorMessage?.trim() === messageError + && msg.timestamp !== undefined ? { error: messageError, timestamp: msg.timestamp } : null; + } if (msg?.role === "user") { break; } @@ -2564,7 +2689,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setEchoedUserMessage(completed); } const messageError = readAgentError(completed); - if (messageError) lastRunErrorRef.current = messageError; + if (messageError) { + lastRunErrorRef.current = messageError; + runErrorAssistantRef.current = completed?.role === "assistant" && completed.errorMessage?.trim() === messageError + && completed.timestamp !== undefined ? { error: messageError, timestamp: completed.timestamp } : null; + } if (completed) { if (hasVisibleAssistantContent(completed)) runHadContentRef.current = true; const text = extractMessageText(completed as Partial); @@ -2609,7 +2738,14 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } case "turn_end": { const messageError = readTerminalAgentError(event); - if (messageError) lastRunErrorRef.current = messageError; + if (messageError) { + lastRunErrorRef.current = messageError; + runErrorAssistantRef.current = terminalErrorAssistant(event, messageError); + if (!runErrorAssistantRef.current) { + independentRunErrorRef.current = messageError; + unconfirmedErrorNoticeRef.current = null; + } + } break; } case "tool_execution_start": { @@ -2868,7 +3004,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { handleExtensionUiRequest(event as unknown as IncomingExtensionUiRequest); break; } - }, [addNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, refreshSubagentRoster, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync, setCompacting, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot]); + }, [addNotice, addUnconfirmedRunErrorNotice, catchUp, eventCoalescer, clearLiveToolResults, clearTerminalReconcileTimer, finishPromptWithoutStream, handleExtensionUiRequest, handleHostToolCall, handleHostUriRequest, loadSession, reloadActiveSessionHistory, mergeSubagents, onAgentEnd, reconcileAgentState, refreshLiveModelState, refreshSubagentRoster, resetSubagentActivityState, applyAuthoritativeModel, applySkillDiagnosticsSnapshot, beginAuthoritativeModelSync, setCompacting, setLiveToolResult, surfaceQuotaOnStream, updateQueuedMessages, applyQueueStateSnapshot]); handleAgentEventRef.current = handleAgentEvent; syncActionsRef.current = { metadata: (context, version, hasLive = liveModelMeta !== null || currentModelOverride !== null) => { @@ -2889,6 +3025,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; } void connectEvents(sid, true); return true; @@ -2914,6 +3052,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; } if (!promptDispatchPendingRef.current && snapshot.responseObserved) runHadContentRef.current = true; applyNativeCompacting(snapshot.isCompacting, compactionGenRef.current); @@ -2935,7 +3075,12 @@ export function useAgentSession(opts: UseAgentSessionOptions) { : { type: "idle", streaming: snapshot.isStreaming }); if (!promptDispatchPendingRef.current && hasVisibleAssistantContent(snapshot.streamingMessage)) runHadContentRef.current = true; const messageError = readAgentError(snapshot.streamingMessage); - if (messageError) lastRunErrorRef.current = messageError; + if (messageError) { + lastRunErrorRef.current = messageError; + const message = snapshot.streamingMessage; + runErrorAssistantRef.current = message?.role === "assistant" && message.errorMessage?.trim() === messageError + && message.timestamp !== undefined ? { error: messageError, timestamp: message.timestamp } : null; + } } // omp's next delta applies to this snapshot, or completes deltas that arrived without their message. eventCoalescer.seed(snapshot.streamingMessageId ?? null, snapshot.streamingMessage, snapshot.cursor.sequence, fields.message); @@ -3068,6 +3213,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; runPreviousEntryIdsRef.current = sessionIdRef.current ? null : []; agentRunningRef.current = true; slashCommandRunRef.current = isSlashCommandPrompt; @@ -3155,6 +3302,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { clearLiveToolResults(); lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; slashCommandRunRef.current = false; dispatch({ type: "end" }); addNotice({ type: "info", message: translate("agentSession.queuedWhileShellRunning") }); @@ -3190,6 +3339,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { clearLiveToolResults(); lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; slashCommandRunRef.current = false; dispatch({ type: "end" }); return mayHaveRun ? { status: "accepted" } : { status: "rejected", recoveryKey }; @@ -3221,6 +3372,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; const previousRunEntryIds = runPreviousEntryIdsRef.current; runPreviousEntryIdsRef.current = null; @@ -4339,6 +4492,8 @@ export function useAgentSession(opts: UseAgentSessionOptions) { runHadContentRef.current = false; lastQuotaErrorRef.current = null; lastRunErrorRef.current = null; + runErrorAssistantRef.current = null; + independentRunErrorRef.current = null; catchUp.select({ leafId: null, includePreCompaction: false }); const compactionGen = compactionGenRef.current; mountLoadingRef.current = session.id;