From d9556e3031aa4f310567dfac4e1f6715e7ba12f7 Mon Sep 17 00:00:00 2001 From: Kiet Ho Date: Sun, 22 Nov 2026 22:20:06 -0800 Subject: [PATCH 1/3] fix(chat): offer the account switch when a Claude model limit fails a turn A turn that Claude refuses with "You've hit your Fable limit" came back as a red "Task interrupted" card with no way to move to another login. The ACP adapter now reads the structured report on the error that fails the turn (`error.data.rateLimit`, then `errorKind` with Claude Code's own refusal prefixes) before it falls back to the generic wording check. The generic check also accepts a named limit ("your Fable limit") and still rejects context, token, output and size limits. The account pill and menu from the composer notice move to a shared `UsageAccountMenu`, and the usage-limit failure card renders it too. --- .../components/SessionView/SessionView.tsx | 40 ++-- .../UsageLimitNotice.test.tsx | 24 +-- .../UsageLimitNotice/UsageLimitNotice.tsx | 188 +----------------- .../components/UsageLimitNotice/index.ts | 6 +- .../useFailureRecovery/useFailureRecovery.ts | 5 + .../TurnStatusRow/TurnStatusRow.test.tsx | 31 +++ .../TurnFailureCard/TurnFailureCard.tsx | 6 + .../UsageAccountMenu/UsageAccountMenu.tsx | 153 ++++++++++++++ .../components/UsageAccountMenu/index.ts | 6 + .../TurnFailureActionsProvider.tsx | 3 + .../src/harness/acp/acpAdapter.test.ts | 68 ++++++- .../src/harness/acp/acpAdapter.ts | 45 ++++- .../src/harness/acp/rpcClient/rpcClient.ts | 6 +- packages/chat-runtime/src/harness/acp/wire.ts | 5 +- .../claude/translateStream/translateStream.ts | 6 +- .../src/harness/usageLimit/index.ts | 4 +- .../src/harness/usageLimit/usageLimit.test.ts | 38 ++++ .../src/harness/usageLimit/usageLimit.ts | 39 +++- packages/chat/src/protocol/envelope.test.ts | 7 + packages/chat/src/protocol/envelope.ts | 2 +- 20 files changed, 440 insertions(+), 242 deletions(-) create mode 100644 apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/UsageAccountMenu/UsageAccountMenu.tsx create mode 100644 apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/UsageAccountMenu/index.ts create mode 100644 packages/chat-runtime/src/harness/usageLimit/usageLimit.test.ts diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx index 80880612a00..5c29cbd08b9 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx @@ -71,6 +71,7 @@ import { useChildrenByParent } from "../Transcript/hooks/useChildrenByParent"; import { NestedItemsProvider } from "../Transcript/providers/NestedItemsProvider"; import { SessionModeProvider } from "../Transcript/providers/SessionModeProvider"; import { TranscriptPluginsProvider } from "../Transcript/providers/TranscriptPluginsProvider"; +import type { AccountSwitch, SwitchAccount } from "../UsageAccountMenu"; import { type DrawerExit, WorkDrawer, @@ -78,11 +79,7 @@ import { } from "../WorkDrawer"; import { ComposerChips } from "./components/ComposerChips"; import { SubagentNotice } from "./components/SubagentNotice"; -import { - type SwitchAccount, - type SwitchableAgent, - UsageLimitNotice, -} from "./components/UsageLimitNotice"; +import { UsageLimitNotice } from "./components/UsageLimitNotice"; import { useAgentSignIn } from "./hooks/useAgentSignIn"; import { useFailureRecovery } from "./hooks/useFailureRecovery"; import { useLaunchPromptDelivered } from "./hooks/useLaunchPromptDelivered"; @@ -662,31 +659,26 @@ export function SessionView({ const limit = sessionState?.usageLimit; const respondToUsageLimit = session.respondToUsageLimit; const hostUrl = useWorkspaceHostUrl(workspaceId); + const accountSwitch = useMemo(() => { + const preset = harness ? presetForAnyHarness(harness) : undefined; + if (preset !== "claude" && preset !== "codex") return undefined; + return { + agent: preset, + hostUrl, + sessionAccount, + onSwitch: onSwitchAccount, + }; + }, [harness, hostUrl, sessionAccount, onSwitchAccount]); const usageLimit = useMemo(() => { if (!limit) return undefined; - const preset = harness ? presetForAnyHarness(harness) : undefined; - const agent: SwitchableAgent | undefined = - preset === "claude" ? "claude" : preset === "codex" ? "codex" : undefined; return { limit, respond: respondToUsageLimit, modelLabel: limit.model ? modelDisplayName(limit.model, configOptions ?? []) : undefined, - agent, - hostUrl, - sessionAccount, - onSwitchAccount, }; - }, [ - limit, - respondToUsageLimit, - harness, - configOptions, - hostUrl, - onSwitchAccount, - sessionAccount, - ]); + }, [limit, respondToUsageLimit, configOptions]); const heldQueued = held?.queued; const heldLaunched = held?.launched; @@ -714,6 +706,7 @@ export function SessionView({ useAgentSignIn(presetId); const { failureActions, onSetConfigOption, onModelPickerOpenChange } = useFailureRecovery({ + accountSwitch, blocked: !loaded || booting || @@ -747,13 +740,10 @@ export function SessionView({ ); const usageLimitNotice = usageLimit && !held && ( ); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/UsageLimitNotice.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/UsageLimitNotice.test.tsx index 220981093ea..6462e12bf01 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/UsageLimitNotice.test.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/UsageLimitNotice.test.tsx @@ -105,8 +105,7 @@ test("the account menu is only for agents whose logins the host can switch", () const claude = renderNotice({ limit: { hitAtMs: Date.now() }, onRespond: () => undefined, - agent: "claude", - hostUrl: null, + accountSwitch: { agent: "claude", hostUrl: null }, }); expect(claude.getByLabelText("Switch account").textContent).toBe("Account"); }); @@ -137,16 +136,18 @@ test("the account menu identifies the session's captured login even after the ho { limit: { hitAtMs: 1 }, onRespond: () => undefined, - agent: "claude", - hostUrl: null, - sessionAccount: { + accountSwitch: { agent: "claude", - selection: null, - credentialKind: "subscription", - identity: "captured", - email: "running@example.com", + hostUrl: null, + sessionAccount: { + agent: "claude", + selection: null, + credentialKind: "subscription", + identity: "captured", + email: "running@example.com", + }, + onSwitch: async () => undefined, }, - onSwitchAccount: async () => undefined, }, [current, next], ); @@ -168,8 +169,7 @@ test("an unknown session account is not inferred from the host default", () => { { limit: { hitAtMs: 1 }, onRespond: () => undefined, - agent: "claude", - hostUrl: null, + accountSwitch: { agent: "claude", hostUrl: null }, }, [account("/profiles/next", true)], ); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/UsageLimitNotice.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/UsageLimitNotice.tsx index fa0c718d353..b9ef3f73e2b 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/UsageLimitNotice.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/UsageLimitNotice.tsx @@ -1,41 +1,15 @@ import { msg } from "@lingui/core/macro"; import { Trans, useLingui } from "@lingui/react/macro"; import type { UsageLimit, UsageLimitAction } from "@superset/chat/protocol"; -import { formatPercent } from "@superset/i18n/format"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuLabel, - DropdownMenuSeparator, - DropdownMenuTrigger, -} from "@superset/ui/dropdown-menu"; import { cn } from "@superset/ui/utils"; -import { useRouter } from "@tanstack/react-router"; -import { - ArrowUpRight, - Check, - ChevronDown, - Clock, - Gauge, - Play, - UserRound, - X, -} from "lucide-react"; +import { Clock, Gauge, Play, X } from "lucide-react"; import { useEffect, useState } from "react"; -import { - type UsageAccount, - useHostUsageQuota, -} from "renderer/hooks/host-service/useHostUsageQuota"; -import type { TerminalAgentBinding } from "renderer/hooks/host-service/useTerminalAgentBindings"; -import { - MENU_PANEL_CLASS, - MENU_ROW_CLASS, - PILL_CHEVRON_CLASS, - PILL_TRIGGER_CLASS, -} from "renderer/routes/_authenticated/components/AgentComposer/constants"; -import { useSetDefaultUsageAccount } from "renderer/routes/_authenticated/settings/usage/hooks/useSetDefaultUsageAccount"; +import { PILL_TRIGGER_CLASS } from "renderer/routes/_authenticated/components/AgentComposer/constants"; import { formatResetLabel } from "renderer/utils/usage/formatResetIn"; +import { + type AccountSwitch, + UsageAccountMenu, +} from "../../../UsageAccountMenu"; const TICK_MS = 30_000; const CLOSE_TICK_MS = 5_000; @@ -54,11 +28,6 @@ const TITLES: Record> = { overage: msg({ message: "Extra usage limit reached" }), }; -export type SwitchableAgent = "claude" | "codex"; -export type SwitchAccount = ( - setAccount: () => Promise, -) => Promise; - /** * The provider refused the last turn for the account's usage. One line says * which limit, for which model, on which account, and when it reopens; the @@ -66,23 +35,17 @@ export type SwitchAccount = ( * another login the host knows, or to look at usage. */ export function UsageLimitNotice({ - agent, - hostUrl, + accountSwitch, limit, modelLabel, - sessionAccount, onRespond, - onSwitchAccount, }: { - sessionAccount?: TerminalAgentBinding["account"]; limit: UsageLimit; onRespond: (action: UsageLimitAction) => void; /** The model's name as the agent lists it; the id when it does not. */ modelLabel?: string | undefined; - /** Which agent's logins the host can switch between; others cannot. */ - agent?: SwitchableAgent | undefined; - hostUrl?: string | null | undefined; - onSwitchAccount?: SwitchAccount | undefined; + /** Set for an agent whose logins the host can switch between. */ + accountSwitch?: AccountSwitch | undefined; }) { const { i18n, t } = useLingui(); const [now, setNow] = useState(() => Date.now()); @@ -105,16 +68,6 @@ export function UsageLimitNotice({ ? Math.ceil((resumesAtMs - now) / 1000) : 0; - const quota = useHostUsageQuota(agent && hostUrl ? hostUrl : null); - const accounts = (quota.data ?? []).filter( - (account) => account.agent === agent, - ); - const current = accounts.find( - (account) => - account.agent === sessionAccount?.agent && - account.selection === sessionAccount.selection && - account.credentialKind === sessionAccount.credentialKind, - ); const title = limit.window ? TITLES[limit.window] : undefined; const detail = [ modelLabel, @@ -147,16 +100,7 @@ export function UsageLimitNotice({ )}
- {agent && ( - - )} + {accountSwitch && } {resuming ? ( - - - {accounts.length > 1 && ( - - Continue this chat on another login - - )} - {accounts.map((account) => { - const isCurrent = account === current; - const window = tightest(account); - return ( - { - void onSwitch?.(() => - setDefault.mutateAsync({ - agent, - selection: account.selection, - }), - ); - }} - > - - {isCurrent && } - - - - {account.email ?? account.sourceLabel} - - - {[ - account.plan, - window - ? t({ - message: `${window.label} · ${formatPercent(window.usedPercent / 100)} used`, - }) - : undefined, - ] - .filter(Boolean) - .join(" · ")} - - - - ); - })} - {accounts.length > 0 && } - - - {accounts.length > 1 ? ( - Usage settings - ) : ( - Add an account in Usage settings - )} - - - - ); -} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/index.ts index 3b90485ae4a..f6fc507335b 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/index.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/components/UsageLimitNotice/index.ts @@ -1,5 +1 @@ -export { - type SwitchAccount, - type SwitchableAgent, - UsageLimitNotice, -} from "./UsageLimitNotice"; +export { UsageLimitNotice } from "./UsageLimitNotice"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.ts index 98267710aaf..21847761fb7 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.ts @@ -5,10 +5,12 @@ import type { AgentSignIn, TurnFailureActions, } from "../../../../providers/TurnFailureActionsProvider"; +import type { AccountSwitch } from "../../../UsageAccountMenu"; const CONTINUE: UserContent[] = [{ type: "text", text: CONTINUE_PROMPT }]; export function useFailureRecovery({ + accountSwitch, blocked, canSwitchAgent = false, configOptions, @@ -22,6 +24,7 @@ export function useFailureRecovery({ sendPrompt, setConfigOption, }: { + accountSwitch?: AccountSwitch | undefined; blocked: boolean; canSwitchAgent?: boolean; configOptions: SessionConfigOption[] | undefined; @@ -105,6 +108,7 @@ export function useFailureRecovery({ ...(onStartNewChat ? { startNewChat: onStartNewChat } : {}), ...(manualSignIn ? { manualSignIn, openAgentSettings } : {}), ...(agentSignIn ? { agentSignIn } : {}), + ...(accountSwitch ? { accountSwitch } : {}), dismissed, setDismissed, }), @@ -119,6 +123,7 @@ export function useFailureRecovery({ manualSignIn, openAgentSettings, agentSignIn, + accountSwitch, dismissed, setDismissed, ], diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/TurnGroupSection/components/TurnStatusRow/TurnStatusRow.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/TurnGroupSection/components/TurnStatusRow/TurnStatusRow.test.tsx index 0f9de6798a6..09935a4e4ef 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/TurnGroupSection/components/TurnStatusRow/TurnStatusRow.test.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/TurnGroupSection/components/TurnStatusRow/TurnStatusRow.test.tsx @@ -1,6 +1,7 @@ import { afterEach, expect, mock, test } from "bun:test"; import { deriveTimeline, emptySnapshot, reduceMany } from "@superset/chat/core"; import type { DurableEnvelope, DurableEvent } from "@superset/chat/protocol"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { cleanup, fireEvent, render } from "@testing-library/react"; import { SandboxAccessContext } from "renderer/routes/_authenticated/providers/SandboxAccessProvider"; import { pageLinkFinder } from "../../../../../../../../utils/pageLinks"; @@ -175,6 +176,36 @@ test("a spend limit the host did not classify is a limit notice, not a red failu expect(card?.textContent).toContain("workspace API usage limits"); }); +test("an unclassified limit on an agent with switchable logins offers the account menu in place of Usage settings", () => { + const view = render( + + {}, + dismissed: new Set(), + setDismissed: () => {}, + changeModel: () => {}, + accountSwitch: { agent: "claude", hostUrl: null }, + }} + > + + + , + ); + expect(view.getByLabelText("Switch account")).toBeTruthy(); + expect(view.queryByText("Usage settings")).toBeNull(); + expect(view.getByText("Change model")).toBeTruthy(); +}); + function authCard(actions: Partial) { return render( { const button = buttons[action]; + if (accountSwitch && action === "usage_settings") return []; return button ? [{ action, ...button }] : []; }, ) @@ -297,6 +300,9 @@ export function TurnFailureCard({ limit ? "mt-0.5" : "-ml-2", )} > + {accountSwitch && ( + + )} {limit && offeredButtons} {(limit ? Boolean(text) : clamped || expanded) && ( + + + {accounts.length > 1 && ( + + Continue this chat on another login + + )} + {accounts.map((account) => { + const isCurrent = account === current; + const window = tightest(account); + return ( + { + void onSwitch?.(() => + setDefault.mutateAsync({ + agent, + selection: account.selection, + }), + ); + }} + > + + {isCurrent && } + + + + {account.email ?? account.sourceLabel} + + + {[ + account.plan, + window + ? t({ + message: `${window.label} · ${formatPercent(window.usedPercent / 100)} used`, + }) + : undefined, + ] + .filter(Boolean) + .join(" · ")} + + + + ); + })} + {accounts.length > 0 && } + + + {accounts.length > 1 ? ( + Usage settings + ) : ( + Add an account in Usage settings + )} + + + + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/UsageAccountMenu/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/UsageAccountMenu/index.ts new file mode 100644 index 00000000000..ec8e3e9ec9c --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/UsageAccountMenu/index.ts @@ -0,0 +1,6 @@ +export { + type AccountSwitch, + type SwitchAccount, + type SwitchableAgent, + UsageAccountMenu, +} from "./UsageAccountMenu"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/providers/TurnFailureActionsProvider/TurnFailureActionsProvider.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/providers/TurnFailureActionsProvider/TurnFailureActionsProvider.tsx index 414375a430f..a4fca6b9a9a 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/providers/TurnFailureActionsProvider/TurnFailureActionsProvider.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/providers/TurnFailureActionsProvider/TurnFailureActionsProvider.tsx @@ -1,4 +1,5 @@ import { createContext, useContext } from "react"; +import type { AccountSwitch } from "../../components/UsageAccountMenu"; export type DeviceCode = { userCode: string; @@ -36,6 +37,8 @@ export type TurnFailureActions = { changeModel?: () => void; /** Restarts the agent so a new sign-in takes effect, then continues; false when it could not. */ restartAndContinue?: () => Promise; + /** Set for an agent whose logins the host can switch between. */ + accountSwitch?: AccountSwitch; /** Resolves false when the new chat could not be started. */ startNewChat?: () => Promise; /** The person's own script signs this agent in, so a sign-in prompt has nothing to offer. */ diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts index bb2361f1ae8..6917c34fa59 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts @@ -63,7 +63,7 @@ class FakeAcpAgent { * rate-limited Claude does. */ promptFailure: { updates: Record[]; - error: { code: number; message: string }; + error: { code: number; message: string; data?: unknown }; } | null = null; /** Answer session/prompt once the message is inserted, as a v2 agent does. */ insertOnPrompt = false; @@ -695,6 +695,72 @@ describe("AcpAdapter", () => { await adapter.dispose(); }); + it("a turn refused before any usage reports the limit from the error's own data", async () => { + const agent = new FakeAcpAgent(); + agent.promptFailure = { + updates: [], + error: { + code: -32603, + message: "Internal error: Come back later.", + data: { + errorKind: "rate_limit", + rateLimit: { + status: "rejected", + resetsAt: 1795557600, + rateLimitType: "seven_day_overage_included", + isUsingOverage: false, + }, + }, + }, + }; + const { adapter, events } = startAdapter(agent); + await flush(); + adapter.prompt([{ type: "text", text: "go" }]); + await flush(20); + const limit = sessionsOf(events) + .flatMap((session) => (session.usageLimit ? [session.usageLimit] : [])) + .at(-1); + expect(limit?.resetsAtMs).toBe(1795557600_000); + expect(limit?.window).toBe("seven_day_overage_included"); + const turns = events.flatMap((e) => (e.kind === "turn" ? [e.turn] : [])); + expect(turns.at(-1)?.error?.kind).toBe("usage_limit"); + await adapter.dispose(); + }); + + it("a refusal the Claude agent reports with no window is a limit by the CLI's wording, and a passing rate limit is not", async () => { + const failed = async (message: string) => { + const agent = new FakeAcpAgent(); + agent.promptFailure = { + updates: [], + error: { code: -32603, message, data: { errorKind: "rate_limit" } }, + }; + const { adapter, events } = startAdapter(agent); + await flush(); + adapter.prompt([{ type: "text", text: "go" }]); + await flush(20); + await adapter.dispose(); + return { + limit: sessionsOf(events) + .flatMap((session) => + session.usageLimit ? [session.usageLimit] : [], + ) + .at(-1), + kind: events.flatMap((e) => (e.kind === "turn" ? [e.turn] : [])).at(-1) + ?.error?.kind, + }; + }; + const refused = await failed( + "Internal error: You've hit your Fable limit · resets Nov 24 at 2pm (America/Los_Angeles).", + ); + expect(refused.kind).toBe("usage_limit"); + expect(refused.limit).toEqual({ hitAtMs: 1 }); + const passing = await failed( + "Internal error: API Error: 429 Too many requests, slow down.", + ); + expect(passing.limit).toBeUndefined(); + expect(passing.kind).not.toBe("usage_limit"); + }); + it("a usage update with a null _meta still parses", () => { expect( acpUsageUpdateSchema.safeParse({ used: 1, size: 2, _meta: null }).success, diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.ts index aed92e8abd9..d4790f54677 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.ts @@ -22,7 +22,11 @@ import type { UsageLimit, UserContent, } from "@superset/chat/protocol"; -import { AGENT_DEFAULT_MODE, isHiddenText } from "@superset/chat/protocol"; +import { + AGENT_DEFAULT_MODE, + isHiddenText, + isUsageLimitMessage, +} from "@superset/chat/protocol"; import { z } from "zod"; import { BackgroundTasks } from "../backgroundTasks"; import { EventQueue } from "../eventQueue"; @@ -35,9 +39,10 @@ import type { ResolvedAttachment, } from "../types"; import { + isClaudeUsageError, type RefusedWindow, refusedWindow, - USAGE_LIMIT_TEXT, + refusedWindowOfError, } from "../usageLimit"; import { AIR_ASYNC_TASK_STOP_METHOD, @@ -1274,7 +1279,11 @@ export class AcpAdapter implements HarnessAdapter { this.endCompactions(); if (this.v2Turn?.id === turnId) this.v2Turn = null; if (this.dead) return; - this.failRefusedTurn(turnId, this.turnError(error)); + this.failRefusedTurn( + turnId, + this.turnError(error), + error instanceof AcpRpcError ? error.data : undefined, + ); } } @@ -1320,6 +1329,7 @@ export class AcpAdapter implements HarnessAdapter { this.turnError( idle.error?.message ?? "The agent stopped with an error.", ), + idle.error?.data, ); else this.finishTurn(turnId, idle.stopReason ?? undefined); } @@ -1346,8 +1356,12 @@ export class AcpAdapter implements HarnessAdapter { } /** A failed turn, reported as a usage limit when the agent refused for usage. */ - private failRefusedTurn(turnId: string, failure: TurnError): void { - const limit = this.usageLimitFrom(failure.message); + private failRefusedTurn( + turnId: string, + failure: TurnError, + errorData?: unknown, + ): void { + const limit = this.usageLimitFrom(failure.message, errorData); if (limit) this.emitSession({ usageLimit: limit }); this.failTurn( turnId, @@ -2949,14 +2963,23 @@ export class AcpAdapter implements HarnessAdapter { } /** - * The agent forwards Claude's `rate_limit_event` on its usage updates and - * ends a refused turn with the CLI's own words. A refusal paid for by extra - * usage reports nothing, and a turn that survives one is not a limit. + * The agent forwards Claude's `rate_limit_event` on the error that fails the + * turn and on its usage updates. The CLI's own words are the last resort. A + * refusal paid for by extra usage reports nothing, and a turn that survives + * one is not a limit. */ - private usageLimitFrom(message: string): UsageLimit | null { - const refused = this.refused; + private usageLimitFrom( + message: string, + errorData?: unknown, + ): UsageLimit | null { + const refused = refusedWindowOfError(errorData) ?? this.refused; this.refused = null; - if (!refused && !USAGE_LIMIT_TEXT.test(message)) return null; + if ( + !refused && + !isClaudeUsageError(errorData, message) && + !isUsageLimitMessage(message) + ) + return null; return { hitAtMs: this.now(), ...(refused?.resetsAtMs ? { resetsAtMs: refused.resetsAtMs } : {}), diff --git a/packages/chat-runtime/src/harness/acp/rpcClient/rpcClient.ts b/packages/chat-runtime/src/harness/acp/rpcClient/rpcClient.ts index 343a9efa2b0..b7122c57965 100644 --- a/packages/chat-runtime/src/harness/acp/rpcClient/rpcClient.ts +++ b/packages/chat-runtime/src/harness/acp/rpcClient/rpcClient.ts @@ -127,6 +127,8 @@ export class AcpRpcError extends Error { readonly code: number, /** The agent's own words, without the method that failed. */ readonly detail: string, + /** What the agent attached for clients to dispatch on in place of the text. */ + readonly data?: unknown, ) { super(`${method}: ${detail}`); this.name = "AcpRpcError"; @@ -232,7 +234,7 @@ export class AcpRpcClient { method?: string; params?: unknown; result?: unknown; - error?: { code: number; message: string }; + error?: { code: number; message: string; data?: unknown }; }; try { frame = JSON.parse(line); @@ -266,7 +268,7 @@ export class AcpRpcClient { this.pending.delete(id); if (error !== undefined) { request.reject( - new AcpRpcError(request.method, error.code, error.message), + new AcpRpcError(request.method, error.code, error.message, error.data), ); return; } diff --git a/packages/chat-runtime/src/harness/acp/wire.ts b/packages/chat-runtime/src/harness/acp/wire.ts index d96360bbf21..fad1793363f 100644 --- a/packages/chat-runtime/src/harness/acp/wire.ts +++ b/packages/chat-runtime/src/harness/acp/wire.ts @@ -260,7 +260,10 @@ export const acpStateUpdateSchema = z.looseObject({ state: z.string(), stopReason: z.string().nullable().optional(), error: z - .looseObject({ message: z.string().optional() }) + .looseObject({ + message: z.string().optional(), + data: z.unknown().optional(), + }) .nullable() .optional(), }); diff --git a/packages/chat-runtime/src/harness/claude/translateStream/translateStream.ts b/packages/chat-runtime/src/harness/claude/translateStream/translateStream.ts index 1d98ed4bdc1..fef6ccd3162 100644 --- a/packages/chat-runtime/src/harness/claude/translateStream/translateStream.ts +++ b/packages/chat-runtime/src/harness/claude/translateStream/translateStream.ts @@ -9,12 +9,13 @@ import type { TurnError, Usage, } from "@superset/chat/protocol"; +import { isUsageLimitMessage } from "@superset/chat/protocol"; import { classifyTurnFailure } from "../../turnFailure"; import type { AdapterEvent } from "../../types"; import { + isClaudeUsageRefusal, type RefusedWindow, refusedWindow, - USAGE_LIMIT_TEXT, } from "../../usageLimit"; import type { ToolOutcome, ToolUse } from "../mapToolUse"; import { contentFor, locationsFor, titleFor, toolKindFor } from "../mapToolUse"; @@ -387,7 +388,8 @@ export class ClaudeTranslator { const text = [asString(envelope.result) ?? "", ...asArray(envelope.errors)] .filter((item): item is string => typeof item === "string") .join("\n"); - if (!refused && !USAGE_LIMIT_TEXT.test(text)) return null; + if (!refused && !isClaudeUsageRefusal(text) && !isUsageLimitMessage(text)) + return null; return { kind: "session", session: { diff --git a/packages/chat-runtime/src/harness/usageLimit/index.ts b/packages/chat-runtime/src/harness/usageLimit/index.ts index 5c50d2b5f1e..53c0adf371f 100644 --- a/packages/chat-runtime/src/harness/usageLimit/index.ts +++ b/packages/chat-runtime/src/harness/usageLimit/index.ts @@ -1,5 +1,7 @@ export { + isClaudeUsageError, + isClaudeUsageRefusal, type RefusedWindow, refusedWindow, - USAGE_LIMIT_TEXT, + refusedWindowOfError, } from "./usageLimit"; diff --git a/packages/chat-runtime/src/harness/usageLimit/usageLimit.test.ts b/packages/chat-runtime/src/harness/usageLimit/usageLimit.test.ts new file mode 100644 index 00000000000..eb5d8f965e0 --- /dev/null +++ b/packages/chat-runtime/src/harness/usageLimit/usageLimit.test.ts @@ -0,0 +1,38 @@ +import { expect, test } from "bun:test"; +import { isClaudeUsageError, isClaudeUsageRefusal } from "./usageLimit"; + +test("Claude's usage refusals are known by the CLI's own wording, with or without the ACP error label", () => { + expect( + isClaudeUsageRefusal( + "Internal error: You've hit your Fable limit · resets Nov 24 at 2pm (America/Los_Angeles).", + ), + ).toBe(true); + expect( + isClaudeUsageRefusal("Your seat type doesn't include usage credits"), + ).toBe(true); + expect( + isClaudeUsageRefusal("Internal error: API Error: 529 Overloaded"), + ).toBe(false); +}); + +test("the CLI's wording counts only on an error the Claude agent marked as a rate limit or billing failure", () => { + const refusal = "Internal error: You've hit your Fable limit · resets 2pm"; + expect(isClaudeUsageError({ errorKind: "rate_limit" }, refusal)).toBe(true); + expect(isClaudeUsageError({ errorKind: "billing_error" }, refusal)).toBe( + true, + ); + expect( + isClaudeUsageError( + { errorKind: "rate_limit" }, + "Internal error: API Error: 429 This request would exceed your organization's rate limit", + ), + ).toBe(false); + expect(isClaudeUsageError({ errorKind: "invalid_request" }, refusal)).toBe( + false, + ); + for (const data of [undefined, null, "rate_limit", [], {}]) { + expect( + isClaudeUsageError(data, "You've reached your maximum context length"), + ).toBe(false); + } +}); diff --git a/packages/chat-runtime/src/harness/usageLimit/usageLimit.ts b/packages/chat-runtime/src/harness/usageLimit/usageLimit.ts index 9e5aec0d1a7..3a44507c620 100644 --- a/packages/chat-runtime/src/harness/usageLimit/usageLimit.ts +++ b/packages/chat-runtime/src/harness/usageLimit/usageLimit.ts @@ -1,3 +1,5 @@ +import { USAGE_LIMIT_ERROR_PREFIXES } from "@anthropic-ai/claude-agent-sdk"; + /** * Claude's `rate_limit_info`, as the CLI streams it and as the ACP agent * forwards it under `_meta["_claude/rateLimit"]`. `resetsAt` is in seconds. @@ -29,6 +31,37 @@ export function refusedWindow(rateLimitInfo: unknown): RefusedWindow { }; } -/** The CLI's own words for the refusal, when no event said so. */ -export const USAGE_LIMIT_TEXT = - /hit your (?:usage )?limit|usage limit reached/i; +/** + * The Claude ACP agent puts `{ errorKind, rateLimit }` on the error that fails + * a turn. A turn refused before its first usage has no usage update to carry + * the window, so this is its only structured report. + */ +export function refusedWindowOfError(data: unknown): RefusedWindow { + if (typeof data !== "object" || data === null) return null; + return refusedWindow((data as Record).rateLimit); +} + +const ACP_INTERNAL_ERROR_LABEL = /^Internal error:\s*/; + +/** Claude Code's own list of how its usage refusals start. */ +export function isClaudeUsageRefusal(text: string): boolean { + const words = text.replace(ACP_INTERNAL_ERROR_LABEL, ""); + return USAGE_LIMIT_ERROR_PREFIXES.some((prefix) => words.startsWith(prefix)); +} + +const USAGE_ERROR_KINDS = new Set(["rate_limit", "billing_error"]); + +/** + * The Claude ACP agent gives a usage refusal and a passing rate limit the same + * `errorKind`, and tells them apart by the CLI's words as this does. It puts + * JSON-RPC's "Internal error" label in front of those words. + */ +export function isClaudeUsageError(data: unknown, message: string): boolean { + if (typeof data !== "object" || data === null) return false; + const kind = (data as Record).errorKind; + return ( + typeof kind === "string" && + USAGE_ERROR_KINDS.has(kind) && + isClaudeUsageRefusal(message) + ); +} diff --git a/packages/chat/src/protocol/envelope.test.ts b/packages/chat/src/protocol/envelope.test.ts index 4d82f14e36e..35181624a7b 100644 --- a/packages/chat/src/protocol/envelope.test.ts +++ b/packages/chat/src/protocol/envelope.test.ts @@ -4,6 +4,9 @@ import { isUsageLimitMessage } from "./envelope"; test("usage and spend refusals read as a usage limit; rate limits and other errors do not", () => { for (const message of [ "You've hit your usage limit.", + "Internal error: You've hit your Fable limit · resets Nov 24 at 2pm (America/Los_Angeles).", + "You've hit your session limit · resets 3pm", + "You've hit your Sonnet 4.5 limit", "Claude AI usage limit reached|1794450000", "You have reached your specified workspace API usage limits.", "You've hit your org's monthly spend limit", @@ -15,6 +18,10 @@ test("usage and spend refusals read as a usage limit; rate limits and other erro } for (const message of [ "Rate limit exceeded. Try again in 20s.", + "You've hit your rate limit.", + "You've hit your context window limit.", + "You have hit your token limit for this request.", + "You've hit your file size limit.", "You exceeded your current quota, please check your plan and billing details. For more information on this error, head to: https://ai.google.dev/gemini-api/docs/rate-limits.", "acp agent exited (code 1)", "prompt is too long", diff --git a/packages/chat/src/protocol/envelope.ts b/packages/chat/src/protocol/envelope.ts index f13de961000..805d0adfa16 100644 --- a/packages/chat/src/protocol/envelope.ts +++ b/packages/chat/src/protocol/envelope.ts @@ -134,7 +134,7 @@ export const turnErrorSchema = z.looseObject({ export type TurnError = z.infer; const USAGE_LIMIT_MESSAGE = - /(?:usage|spend|spending|monthly|weekly|daily) limits? (?:reached|exceeded)|(?:reached|hit) your (?:[\w'-]+ ){0,4}(?:usage|spend|spending) limits?|hit your (?:usage )?limit|(?:quota|credits?) (?:exceeded|exhausted|depleted)|exceeded your current quota|insufficient[_ ](?:quota|credits)|credit balance is too low/i; + /(?:usage|spend|spending|monthly|weekly|daily) limits? (?:reached|exceeded)|(?:reached|hit) your (?:[\w'-]+ ){0,4}(?:usage|spend|spending) limits?|hit your (?:(?!context|token|output|size)[\w.'-]+ ){0,2}limit|(?:quota|credits?) (?:exceeded|exhausted|depleted)|exceeded your current quota|insufficient[_ ](?:quota|credits)|credit balance is too low/i; /** Gemini words a per-minute 429 as "exceeded your current quota" and links its rate-limit docs. */ const RATE_LIMIT_MESSAGE = /rate[-_ ]?limit/i; From e1421d0e8f0d50d5193cfdd05dc4de97bac8184b Mon Sep 17 00:00:00 2001 From: Kiet Ho Date: Sun, 22 Nov 2026 22:28:19 -0800 Subject: [PATCH 2/3] fix(chat): resume a usage-limited session when another model is picked The refusal says to switch model, but a model picked under the notice left the limit in place and queued every later message. A different model now resumes the session the same way the Resume button does. --- .../components/SessionView/SessionView.tsx | 5 ++++ .../useFailureRecovery.test.ts | 24 ++++++++++++++++++- .../useFailureRecovery/useFailureRecovery.ts | 16 ++++++++----- 3 files changed, 38 insertions(+), 7 deletions(-) diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx index 5c29cbd08b9..db340e73c7c 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx @@ -698,6 +698,10 @@ export function SessionView({ [sentOutbox.transcript, heldOutbox], ); const booting = sessionState?.status === "starting"; + const resumeAfterLimit = useMemo( + () => (limit ? () => respondToUsageLimit("resume") : undefined), + [limit, respondToUsageLimit], + ); const openModelPicker = useCallback( () => composerRef.current?.openModelPicker(), [], @@ -723,6 +727,7 @@ export function SessionView({ onRestartAndContinue, onStartNewChat, openModelPicker, + resumeAfterLimit, sendPrompt, setConfigOption, }); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.test.ts index 77efde74b79..72109c16a87 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.test.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.test.ts @@ -16,7 +16,7 @@ const MODEL: SessionConfigOption = { }; const CONTINUE: UserContent[] = [{ type: "text", text: CONTINUE_PROMPT }]; -function setup() { +function setup(options: { resumeAfterLimit?: () => void } = {}) { const sendPrompt = mock((_content: UserContent[]) => {}); const openModelPicker = mock(() => {}); let finishSet = () => {}; @@ -35,6 +35,7 @@ function setup() { openModelPicker, sendPrompt, setConfigOption, + ...options, }), ); return { @@ -70,6 +71,27 @@ test("a model picked after Change model continues once the agent has it", async expect(sendPrompt.mock.calls).toEqual([[CONTINUE]]); }); +test("another model picked under a usage limit resumes the session", async () => { + const resumeAfterLimit = mock(() => {}); + const { hook, sendPrompt, setConfigOption, finish } = setup({ + resumeAfterLimit, + }); + + hook.result.current.onSetConfigOption("model", "sonnet"); + await act(async () => finish()); + expect(resumeAfterLimit).not.toHaveBeenCalled(); + + hook.result.current.onSetConfigOption("model", "opus"); + await act(async () => finish()); + expect(setConfigOption.mock.calls[1]).toEqual([ + "model", + "opus", + { confirm: true }, + ]); + expect(resumeAfterLimit).toHaveBeenCalledTimes(1); + expect(sendPrompt).not.toHaveBeenCalled(); +}); + test("a model the agent refuses does not continue the task", async () => { const { hook, sendPrompt, setConfigOption, refuse } = setup(); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.ts index 21847761fb7..adeeb2802a8 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/hooks/useFailureRecovery/useFailureRecovery.ts @@ -21,6 +21,7 @@ export function useFailureRecovery({ onRestartAndContinue, onStartNewChat, openModelPicker, + resumeAfterLimit, sendPrompt, setConfigOption, }: { @@ -36,6 +37,8 @@ export function useFailureRecovery({ onRestartAndContinue?: ((prompt: string) => Promise) | undefined; onStartNewChat?: (() => Promise) | undefined; openModelPicker: () => void; + /** Set while a usage limit holds the session: another model can lift it. */ + resumeAfterLimit?: (() => void) | undefined; sendPrompt: (content: UserContent[]) => unknown; setConfigOption: ( configId: string, @@ -53,20 +56,21 @@ export function useFailureRecovery({ const onSetConfigOption = useCallback( (configId: string, value: string) => { - const isModel = - configOptions?.find((option) => option.id === configId)?.category === - "model"; - if (!isModel || !continueAfterModelPick.current) { + const option = configOptions?.find((option) => option.id === configId); + const isModel = option?.category === "model"; + const afterLimit = + option?.currentValue !== value ? resumeAfterLimit : undefined; + if (!isModel || (!continueAfterModelPick.current && !afterLimit)) { void setConfigOption(configId, value); return; } continueAfterModelPick.current = false; void setConfigOption(configId, value, { confirm: true }).then( - continueTask, + afterLimit ?? continueTask, () => undefined, ); }, - [setConfigOption, configOptions, continueTask], + [setConfigOption, configOptions, continueTask, resumeAfterLimit], ); const onModelPickerOpenChange = useCallback((open: boolean) => { if (!open) continueAfterModelPick.current = false; From adb5c606c0e0138b0f3e40279e47250aad916fef Mon Sep 17 00:00:00 2001 From: Kiet Ho Date: Sun, 22 Nov 2026 22:42:57 -0800 Subject: [PATCH 3/3] fix(chat): continue the refused work after an account switch with nothing queued Resume and a model switch send the continue prompt when the queue is empty. A login picked from the usage limit notice cleared the notice and left the refused prompt unanswered. It now continues the same way. --- .../ChatPane/components/AcpChatPane/AcpChatPane.tsx | 11 +++++++++-- .../components/SessionView/SessionView.tsx | 11 ++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/AcpChatPane.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/AcpChatPane.tsx index 8a5a02f5ca3..25a2aad6bbc 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/AcpChatPane.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/AcpChatPane.tsx @@ -1,5 +1,5 @@ import { Trans, useLingui } from "@lingui/react/macro"; -import { acpHarnessForPreset } from "@superset/chat/core"; +import { acpHarnessForPreset, CONTINUE_PROMPT } from "@superset/chat/core"; import { AGENT_DEFAULT_MODE, type UserContent } from "@superset/chat/protocol"; import { errorMessage } from "@superset/i18n/errors"; import { getAgentModelSupport } from "@superset/shared/agent-models"; @@ -541,7 +541,10 @@ export function AcpChatPane({ .then(() => start(harness, agentSessionId, true)); }, [harness, agentSessionId, sessionId, start, wiring.transport]); const switchAccount = useCallback( - async (setAccount: () => Promise) => { + async ( + setAccount: () => Promise, + { continueWork }: { continueWork: boolean }, + ) => { if (!harness || !sessionId || recoveryInFlight.current) return; recoveryInFlight.current = true; setSwitchingAccount(true); @@ -554,7 +557,11 @@ export function AcpChatPane({ if (!mounted.current) return; setTransferredFrom(sessionId); onRestoreQueuedPrompts(queued); + if (continueWork && queued.length === 0) { + continueAfterRestart.current = CONTINUE_PROMPT; + } const restarted = await start(harness, agentSessionId, true); + if (!restarted) continueAfterRestart.current = null; if (!restarted && mounted.current) setTransferredFrom(null); } catch (error) { recoveryInFlight.current = false; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx index db340e73c7c..144f435b441 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/SessionView/SessionView.tsx @@ -160,7 +160,9 @@ export function SessionView({ onSessionState?: (session: SessionState | null) => void; /** The mode the user picked, so a resumed session can start in it again. */ onModeChange?: (modeId: string) => void; - onSwitchAccount?: SwitchAccount; + onSwitchAccount?: ( + ...args: [...Parameters, { continueWork: boolean }] + ) => Promise; sessionAccount?: TerminalAgentBinding["account"]; /** * Absent when the agent cannot branch its own session. The transcript is @@ -659,6 +661,7 @@ export function SessionView({ const limit = sessionState?.usageLimit; const respondToUsageLimit = session.respondToUsageLimit; const hostUrl = useWorkspaceHostUrl(workspaceId); + const limited = limit !== undefined; const accountSwitch = useMemo(() => { const preset = harness ? presetForAnyHarness(harness) : undefined; if (preset !== "claude" && preset !== "codex") return undefined; @@ -666,9 +669,11 @@ export function SessionView({ agent: preset, hostUrl, sessionAccount, - onSwitch: onSwitchAccount, + onSwitch: onSwitchAccount + ? (setAccount) => onSwitchAccount(setAccount, { continueWork: limited }) + : undefined, }; - }, [harness, hostUrl, sessionAccount, onSwitchAccount]); + }, [harness, hostUrl, sessionAccount, onSwitchAccount, limited]); const usageLimit = useMemo(() => { if (!limit) return undefined; return {