Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): fallback provider on outage (macro-1914) (#4198)
Eric Hayes29f2b2af4c91
diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsxindex 3257697b01..86df415e22 100644--- a/js/app/packages/block-chat/component/Chat.tsx+++ b/js/app/packages/block-chat/component/Chat.tsx@@ -6,12 +6,18 @@ import type { SendBuilder } from '@block-chat/blockClient';import { TopBar } from '@block-chat/component/TopBar';import type { ChatData } from '@block-chat/definition';import { pendingLocationParamsSignal } from '@block-chat/signal/pendingLocationParams';+import { useHasPaidAccess } from '@core/auth/license';import { useBlockId, useIsNestedBlock } from '@core/block';import { DragDropWrapper } from '@core/component/AI/component/DragDrop';import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';import { useSendChatMessage } from '@core/component/AI/component/input/buildRequest';import { ChatMessages } from '@core/component/AI/component/message/ChatMessages';+import {+ alternateProviderModel,+ MODEL_PROVIDER,+ modelsForPlan,+} from '@core/component/AI/constant';import {ChatInputProvider,ChatProvider,@@ -52,7 +58,6 @@ import { createEffect, createSignal, getOwner, Show, Suspense } from 'solid-js';export function Chat(props: { data: ChatData }) {const loadedState = getChatInputStoredState(props.data.chat.id);- const { showPaywall } = usePaywallState();// Seed the model selector, highest priority first:// 1. peekPendingSend — the model the user just sent with in the soup chat@@ -73,17 +78,63 @@ export function Chat(props: { data: ChatData }) {initialAttachments={loadedState.attachments}model={initialModel}>- <ChatProvider- chatId={props.data.chat.id}- messages={props.data.chat.messages}- controllerOptions={{ onShowPaywall: showPaywall }}- >- <ChatInner data={props.data} loadedInputText={loadedState.input} />- </ChatProvider>+ <ChatWithController+ data={props.data}+ loadedInputText={loadedState.input}+ /></ChatInputProvider>);}+/**+ * Sits inside `ChatInputProvider` so the controller can be wired to model+ * state — specifically, so a provider-outage error toast can switch the chat+ * to a model from a different provider.+ */+function ChatWithController(props: {+ data: ChatData;+ loadedInputText: string | undefined;+}) {+ const { showPaywall } = usePaywallState();+ const input = useChatInputContext();+ const hasPaidAccess = useHasPaidAccess();++ // Providers that have failed during this chat session. We avoid bouncing the+ // user back to a provider we already know is down (e.g. Anthropic → OpenAI →+ // back to Anthropic). Lives for the life of this chat component.+ const failedProviders = new Set<string>();++ // The model we'd fall back to if the current one failed: a different,+ // non-failed provider drawn from the user's accessible models.+ const nextModel = () =>+ alternateProviderModel(input.model(), {+ candidates: [...modelsForPlan(hasPaidAccess())],+ failedProviders,+ });++ const onSwitchModel = () => {+ const alternate = nextModel();+ if (!alternate) return;+ // Record the provider that just failed before moving off it.+ failedProviders.add(MODEL_PROVIDER[input.model()]);+ input.setModel(alternate);+ };++ return (+ <ChatProvider+ chatId={props.data.chat.id}+ messages={props.data.chat.messages}+ controllerOptions={{+ onShowPaywall: showPaywall,+ onSwitchModel,+ hasAlternateModel: () => nextModel() !== undefined,+ }}+ >+ <ChatInner data={props.data} loadedInputText={props.loadedInputText} />+ </ChatProvider>+ );+}+function ChatInner(props: {data: ChatData;loadedInputText: string | undefined;diff --git a/js/app/packages/core/component/AI/component/debug/Component.tsx b/js/app/packages/core/component/AI/component/debug/Component.tsxindex 7b46ff9652..8014b008b9 100644--- a/js/app/packages/core/component/AI/component/debug/Component.tsx+++ b/js/app/packages/core/component/AI/component/debug/Component.tsx@@ -1,13 +1,15 @@import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';-import type { Model } from '@core/component/AI/types';+import { MODEL_PRETTYNAME, MODEL_PROVIDER } from '@core/component/AI/constant';+import { Model } from '@core/component/AI/types';import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';+import LockIcon from '@phosphor-icons/core/regular/lock-simple.svg?component-solid';import { cognitionApiServiceClient } from '@service-cognition/client';import type { ChatMessageStream } from '@service-connection/stream';import { subscribe } from '@service-connection/stream';-import { Button } from '@ui';-import { createEffect, createSignal } from 'solid-js';+import { Button, cn } from '@ui';+import { createEffect, createSignal, For, Show } from 'solid-js';import {ChatInputProvider,ChatProvider,@@ -45,6 +47,8 @@ export default function Debug() {<StreamMessages /><StaticMessages /><FullChat />+ <ProviderFailureChat />+ <FreeProviderFailureChat /><ToolCallRender /><ToolCallResponseRender /><LoadingMessageScroll />@@ -188,7 +192,10 @@ function StreamMessagesInner() {Stream</button><StreamStatus stream={stream} />- <div data-chat-scroll>+ {/* Must be height-bounded (max-h + overflow): ChatMessages sizes a child+ to the scroll container's own height, so an unbounded container grows+ without limit (container height -> child min-height -> container ...). */}+ <div data-chat-scroll class="min-h-0 max-h-100 overflow-y-auto"><ChatMessages /></div></Item>@@ -289,6 +296,215 @@ function FullChatInner() {);}+// --- Gallery-only multi-provider model set (NOT the product model list) ---+// A third provider (Cerebras) lets the gallery exercise multi-hop provider+// fallback. It deliberately lives here, not in model.ts, so it never surfaces+// in the real product model selector.+const CEREBRAS_MODEL = 'cerebras/llama-3.3-70b';+const GALLERY_MODELS: string[] = [...Object.values(Model), CEREBRAS_MODEL];++const galleryProvider = (id: string): string =>+ MODEL_PROVIDER[id as Model] ?? 'cerebras';+const galleryPrettyName = (id: string): string =>+ MODEL_PRETTYNAME[id as Model] ?? 'Cerebras Llama 3.3';++// Gallery copy of alternateProviderModel that also understands Cerebras: pick a+// candidate whose provider is neither the current one nor any that has failed.+function galleryAlternateModel(+ current: string,+ opts: { candidates: string[]; failedProviders: Set<string> }+): string | undefined {+ const excluded = new Set(opts.failedProviders);+ excluded.add(galleryProvider(current));+ return opts.candidates.find((id) => !excluded.has(galleryProvider(id)));+}++// Flat, always-visible model picker for the gallery: shows every gallery model+// with availability lock state (mirrors how the real selector dims + locks+// inaccessible models), so the free variant can show all models with only one+// available.+function GalleryModelSelector(props: {+ selected: string;+ isAvailable: (id: string) => boolean;+ onSelect: (id: string) => void;+ onLocked?: (id: string) => void;+}) {+ return (+ <div class="flex flex-wrap items-center gap-1.5 text-xs">+ <span class="text-ink-muted">Models:</span>+ <For each={GALLERY_MODELS}>+ {(id) => (+ <button+ type="button"+ class={cn(+ 'flex items-center gap-1 rounded-md border px-2 py-1',+ props.selected === id+ ? 'border-accent bg-accent text-ink'+ : 'border-edge text-ink-muted',+ !props.isAvailable(id) && 'opacity-50'+ )}+ onClick={() =>+ props.isAvailable(id) ? props.onSelect(id) : props.onLocked?.(id)+ }+ >+ {galleryPrettyName(id)}+ <Show when={!props.isAvailable(id)}>+ <LockIcon class="size-3" />+ </Show>+ </button>+ )}+ </For>+ </div>+ );+}++// A chat that always fails with a provider error, to exercise the+// provider-outage fallback UX end to end. Parameterized by which models the+// "user" can access so we can show both a paid variant (multi-provider+// fallback: Anthropic -> OpenAI -> Cerebras) and a free variant (no accessible+// alternate -> outage message).+function ProviderFailureDemo(props: {+ label: string;+ initialModel: string;+ availableModels: string[];+}) {+ return (+ <ChatInputProvider model={props.initialModel as Model}>+ <ProviderFailureDemoInner+ label={props.label}+ availableModels={props.availableModels}+ />+ </ChatInputProvider>+ );+}++function ProviderFailureDemoInner(props: {+ label: string;+ availableModels: string[];+}) {+ const input = useChatInputContext();++ // Remember which providers failed this session so we never bounce back to a+ // known-bad one — mirrors block-chat's Chat.tsx wiring.+ const failedProviders = new Set<string>();+ const nextModel = () =>+ galleryAlternateModel(input.model(), {+ // Only ever fall back to a model the "user" can access.+ candidates: props.availableModels,+ failedProviders,+ });+ const onSwitchModel = () => {+ const alt = nextModel();+ if (!alt) return;+ failedProviders.add(galleryProvider(input.model()));+ input.setModel(alt as Model);+ };++ return (+ <ChatProvider+ chatId={`debug-provider-failure-${props.availableModels.length}`}+ messages={[]}+ controllerOptions={{+ onSwitchModel,+ hasAlternateModel: () => nextModel() !== undefined,+ onShowPaywall: () => {},+ }}+ >+ <ProviderFailureDemoBody+ label={props.label}+ isAvailable={(id) => props.availableModels.includes(id)}+ />+ </ChatProvider>+ );+}++function ProviderFailureDemoBody(props: {+ label: string;+ isAvailable: (id: string) => boolean;+}) {+ const chat = useChatContext();+ const input = useChatInputContext();+ const [text, setText] = createSignal('Why did the AI provider fall over?');++ const send = () => {+ const content = text().trim();+ if (!content) return;+ // Optimistically show the user's message...+ chat.dispatch({+ type: 'send_started',+ optimisticMessage: {+ id: crypto.randomUUID(),+ content,+ role: 'user',+ attachments: [],+ },+ });+ // ...then simulate the provider erroring mid-stream. This drives the real+ // controller, which emits the actual error toast — the "Switch model"+ // button while an accessible alternate provider remains, or a "try again+ // later" outage message once none do.+ setTimeout(+ () =>+ chat.dispatch({ type: 'stream_error', streamError: 'provider_error' }),+ 350+ );+ };++ return (+ <Item col label={props.label}>+ <GalleryModelSelector+ selected={input.model()}+ isAvailable={props.isAvailable}+ onSelect={(id) => input.setModel(id as Model)}+ onLocked={(id) => console.log('paywall for locked model', id)}+ />+ <div data-chat-scroll class="min-h-0 max-h-72 w-full overflow-y-auto">+ <ChatMessages />+ </div>+ <div class="flex w-full gap-2">+ <input+ class="flex-1 rounded border border-accent px-2 py-1 text-sm"+ value={text()}+ onInput={(e) => setText(e.currentTarget.value)}+ placeholder="Type a message and send"+ onKeyDown={(e) => {+ if (e.key === 'Enter') send();+ }}+ />+ <Button variant="active" onClick={send}>+ Send+ </Button>+ </div>+ </Item>+ );+}++// Paid: every provider (incl. Cerebras) is available, so the fallback chains+// Anthropic -> OpenAI -> Cerebras before running out and showing the outage+// message.+function ProviderFailureChat() {+ return (+ <ProviderFailureDemo+ label="Provider failure - switch-model fallback"+ initialModel={Model.opus48}+ availableModels={GALLERY_MODELS}+ />+ );+}++// Free: all models are shown but only Haiku is available, so there is no+// accessible model on another provider — the first failure already shows the+// outage message (no switch button).+function FreeProviderFailureChat() {+ return (+ <ProviderFailureDemo+ label="Provider failure (free) - all shown, only Haiku available"+ initialModel={Model.haiku45}+ availableModels={[Model.haiku45]}+ />+ );+}+function ToolCallRender() {const stream = toolCall(() => 1);const initialMessages = mockMessages([diff --git a/js/app/packages/core/component/AI/component/input/ModelSelector.test.tsx b/js/app/packages/core/component/AI/component/input/ModelSelector.test.tsxnew file mode 100644index 0000000000..f63c6af984--- /dev/null+++ b/js/app/packages/core/component/AI/component/input/ModelSelector.test.tsx@@ -0,0 +1,204 @@+/**+ * @vitest-environment jsdom+ */++import {+ MODEL_PRETTYNAME,+ Model,+ modelsForPlan,+ type TModel,+} from '@core/component/AI/constant';+import { fireEvent, render } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import { type ModelOption, ModelSelector } from './ModelSelector';++// Render the Kobalte dropdown as a transparent passthrough so the menu items+// are always in the DOM — we're testing ModelSelector's own logic (which models+// render, lock state, select vs. paywall routing), not the dropdown primitive.+vi.mock('@ui', () => {+ const cn = (...args: unknown[]) =>+ args.flat(Infinity).filter(Boolean).join(' ');+ const Dropdown: any = (p: any) => <div>{p.children}</div>;+ Dropdown.Trigger = (p: any) => (+ <button type="button" data-trigger class={p.class}>+ {p.children}+ </button>+ );+ Dropdown.Content = (p: any) => <div>{p.children}</div>;+ Dropdown.Group = (p: any) => <div>{p.children}</div>;+ Dropdown.Item = (p: any) => (+ <div role="menuitem" class={p.class} onClick={() => p.onSelect?.()}>+ {p.children}+ </div>+ );+ return { cn, Dropdown };+});++// Neutralize SVG imports; tag the lock so we can assert it renders.+vi.mock('@core/component/AI/assets/anthropic.svg', () => ({+ default: () => null,+}));+vi.mock('@core/component/AI/assets/openai.svg', () => ({+ default: () => null,+}));+vi.mock('@phosphor-icons/core/regular/caret-down.svg?component-solid', () => ({+ default: () => null,+}));+vi.mock('@phosphor-icons/core/regular/lock-simple.svg?component-solid', () => ({+ default: () => <span data-testid="lock-icon" />,+}));++const ALL_PAID: ModelOption[] = (Object.values(Model) as TModel[]).map(+ (id) => ({ id, available: true })+);++/** Find the menu item row for a model by its pretty name. */+function itemFor(container: HTMLElement, model: TModel): HTMLElement {+ const rows = Array.from(+ container.querySelectorAll('[role="menuitem"]')+ ) as HTMLElement[];+ const row = rows.find((r) =>+ r.textContent?.includes(MODEL_PRETTYNAME[model])+ );+ if (!row) throw new Error(`no menu item for ${model}`);+ return row;+}++describe('ModelSelector: availability', () => {+ it('lists every provided model', () => {+ const { container } = render(() => (+ <ModelSelector models={ALL_PAID} onSelect={() => {}} />+ ));+ expect(container.querySelectorAll('[role="menuitem"]')).toHaveLength(+ ALL_PAID.length+ );+ });++ it('grays out and locks inaccessible models, leaving accessible ones clean', () => {+ // A free user: only the fast model is available.+ const freeAllowed = modelsForPlan(false);+ const options: ModelOption[] = (Object.values(Model) as TModel[]).map(+ (id) => ({ id, available: freeAllowed.includes(id) })+ );+ const { container } = render(() => (+ <ModelSelector models={options} onSelect={() => {}} />+ ));++ const available = itemFor(container, Model.haiku45);+ expect(available.className).not.toContain('opacity-50');+ expect(available.querySelector('[data-testid="lock-icon"]')).toBeNull();++ const locked = itemFor(container, Model.opus48);+ expect(locked.className).toContain('opacity-50');+ expect(locked.querySelector('[data-testid="lock-icon"]')).not.toBeNull();+ });+});++describe('ModelSelector: selection routing', () => {+ it('selecting an available model calls onSelect, not onLocked', () => {+ const onSelect = vi.fn();+ const onLocked = vi.fn();+ const { container } = render(() => (+ <ModelSelector+ models={ALL_PAID}+ onSelect={onSelect}+ onLocked={onLocked}+ />+ ));++ fireEvent.click(itemFor(container, Model.gpt55));+ expect(onSelect).toHaveBeenCalledWith(Model.gpt55);+ expect(onLocked).not.toHaveBeenCalled();+ });++ it('selecting an inaccessible model triggers the paywall (onLocked), not a send', () => {+ const onSelect = vi.fn();+ const onLocked = vi.fn();+ const freeAllowed = modelsForPlan(false);+ const options: ModelOption[] = (Object.values(Model) as TModel[]).map(+ (id) => ({ id, available: freeAllowed.includes(id) })+ );+ const { container } = render(() => (+ <ModelSelector models={options} onSelect={onSelect} onLocked={onLocked} />+ ));++ fireEvent.click(itemFor(container, Model.opus48)); // locked for a free user+ expect(onLocked).toHaveBeenCalledWith(Model.opus48);+ expect(onSelect).not.toHaveBeenCalled();+ });+});++describe('ModelSelector: what is shown is what is sent', () => {+ // The selector's trigger and the message it would send both read the same+ // model accessor. Picking a model updates that single source, so the request+ // can never diverge from what the selector displays.+ function Harness() {+ const [model, setModel] = createSignal<TModel>(Model.opus48);+ return (+ <>+ {/* stand-in for the value sendMessage() reads */}+ <span data-testid="would-send">{model()}</span>+ <ModelSelector+ selectedModel={model()}+ models={ALL_PAID}+ onSelect={setModel}+ />+ </>+ );+ }++ it('reflects the selected model in the trigger and in the would-send value', () => {+ const { container, getByTestId } = render(() => <Harness />);++ // Initial state: trigger shows the selected model.+ const trigger = container.querySelector('[data-trigger]')!;+ expect(trigger.textContent).toContain(MODEL_PRETTYNAME[Model.opus48]);+ expect(getByTestId('would-send').textContent).toBe(Model.opus48);++ // Select a different model -> both the trigger and the would-send value move+ // together to exactly that model.+ fireEvent.click(itemFor(container, Model.sonnet46));+ expect(getByTestId('would-send').textContent).toBe(Model.sonnet46);+ expect(trigger.textContent).toContain(MODEL_PRETTYNAME[Model.sonnet46]);+ });++ it('a free user cannot select an inaccessible model into the would-send value', () => {+ const onLocked = vi.fn();+ const freeAllowed = modelsForPlan(false);+ const options: ModelOption[] = (Object.values(Model) as TModel[]).map(+ (id) => ({ id, available: freeAllowed.includes(id) })+ );+ function FreeHarness() {+ const [model, setModel] = createSignal<TModel>(Model.haiku45);+ return (+ <>+ <span data-testid="would-send">{model()}</span>+ <ModelSelector+ selectedModel={model()}+ models={options}+ onSelect={setModel}+ onLocked={onLocked}+ />+ </>+ );+ }+ const { container, getByTestId } = render(() => <FreeHarness />);++ fireEvent.click(itemFor(container, Model.opus48)); // locked+ // The would-send value is unchanged; only the paywall fired.+ expect(getByTestId('would-send').textContent).toBe(Model.haiku45);+ expect(onLocked).toHaveBeenCalledWith(Model.opus48);+ });+});++// GAP / out of unit scope: the on-mount reconcile that forces a *persisted or+// chat-provided* inaccessible model down to the plan default lives in+// ChatInput's effect (packages/core/.../input/ChatInput.tsx), and the+// stored-draft > chat-model > default precedence lives in Chat.tsx (block-chat,+// outside this test runner's projects). Both are exercised here only indirectly+// via modelsForPlan + the selector's locking. Cover them with a ChatInput-level+// render test (heavy: editor/markdown/upload mocks) when that harness exists.+it.todo(+ 'ChatInput reconciles a persisted/chat inaccessible model down to the plan default on mount'+);diff --git a/js/app/packages/core/component/AI/constant/model.test.ts b/js/app/packages/core/component/AI/constant/model.test.tsnew file mode 100644index 0000000000..95ea87e3f5--- /dev/null+++ b/js/app/packages/core/component/AI/constant/model.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it } from 'vitest';+import { parseModel } from '../util/parse';+import {+ alternateProviderModel,+ DEFAULT_MODEL,+ defaultModelForPlan,+ FREE_DEFAULT_MODEL,+ MODEL_PROVIDER,+ Model,+ modelsForPlan,+ type TModel,+} from './model';++const PROVIDER_OF = (m: TModel) => MODEL_PROVIDER[m];++describe('modelsForPlan / defaultModelForPlan', () => {+ it('gives paid users every model and an Anthropic-smart default', () => {+ const paid = modelsForPlan(true);+ // Every known model is selectable for a paid user.+ expect([...paid].sort()).toEqual([...Object.values(Model)].sort());+ expect(defaultModelForPlan(true)).toBe(DEFAULT_MODEL);+ });++ it('gives free users only the fast model, defaulted to it', () => {+ const free = modelsForPlan(false);+ expect(free).toEqual([FREE_DEFAULT_MODEL]);+ expect(defaultModelForPlan(false)).toBe(FREE_DEFAULT_MODEL);+ // The premium models are *not* in a free user's selectable set.+ expect(free).not.toContain(Model.opus48);+ expect(free).not.toContain(Model.gpt55);+ });+});++describe('parseModel', () => {+ it('passes through known model ids', () => {+ for (const id of Object.values(Model)) {+ expect(parseModel(id)).toBe(id);+ }+ });++ it('rejects unknown / empty values so callers can fall back to a default', () => {+ expect(parseModel('anthropic/claude-opus-4-7')).toBeUndefined(); // retired id+ expect(parseModel('gpt-5.5')).toBeUndefined(); // unprefixed / legacy+ expect(parseModel('not-a-model')).toBeUndefined();+ expect(parseModel('')).toBeUndefined();+ expect(parseModel(null)).toBeUndefined();+ expect(parseModel(undefined)).toBeUndefined();+ });+});++describe('alternateProviderModel', () => {+ it('always suggests a model from a different provider than the current one', () => {+ for (const current of Object.values(Model)) {+ const alt = alternateProviderModel(current);+ expect(alt).toBeDefined();+ expect(PROVIDER_OF(alt!)).not.toBe(PROVIDER_OF(current));+ }+ });++ it('only ever suggests a model the user has access to (stays within candidates)', () => {+ // Candidates model the user's accessible models. The suggestion must be+ // one of them, never a model outside the accessible set.+ const candidates: TModel[] = [Model.haiku45, Model.gpt5Mini];+ const alt = alternateProviderModel(Model.opus48, { candidates });+ expect(candidates).toContain(alt);+ expect(PROVIDER_OF(alt!)).toBe('openai'); // the only different-provider candidate+ });++ it('returns undefined when no accessible model uses a different provider', () => {+ // User is on OpenAI but the only accessible model is also OpenAI — there is+ // no provider to fall back to.+ expect(+ alternateProviderModel(Model.gpt55, { candidates: [Model.gpt5Mini] })+ ).toBeUndefined();+ // Likewise when every candidate shares the current (Anthropic) provider.+ expect(+ alternateProviderModel(Model.opus48, {+ candidates: [Model.haiku45, Model.sonnet46],+ })+ ).toBeUndefined();+ });++ it('remembers failures within a session, never re-suggesting a downed provider', () => {+ // Simulate a session where providers fail one after another. The caller+ // accumulates failed providers; the suggestion must avoid all of them, not+ // just the current model's provider.+ const candidates = [...Object.values(Model)] as TModel[];+ const failedProviders = new Set<string>();+ let current: TModel = Model.opus48; // anthropic++ // Anthropic has an outage → suggest a different provider.+ failedProviders.add(PROVIDER_OF(current));+ const first = alternateProviderModel(current, {+ candidates,+ failedProviders,+ });+ expect(first).toBeDefined();+ expect(PROVIDER_OF(first!)).toBe('openai');+ current = first!;++ // OpenAI then also fails → there is no un-failed provider left, so we must+ // NOT bounce the user back to Anthropic (which already failed this session).+ failedProviders.add(PROVIDER_OF(current));+ const second = alternateProviderModel(current, {+ candidates,+ failedProviders,+ });+ expect(second).toBeUndefined();+ });++ it('still avoids the current provider when no failures are recorded', () => {+ const alt = alternateProviderModel(Model.opus48, {+ candidates: [...Object.values(Model)] as TModel[],+ failedProviders: new Set(),+ });+ expect(PROVIDER_OF(alt!)).toBe('openai');+ });+});diff --git a/js/app/packages/core/component/AI/constant/model.ts b/js/app/packages/core/component/AI/constant/model.tsindex 13b7ad4525..b1a6576bed 100644--- a/js/app/packages/core/component/AI/constant/model.ts+++ b/js/app/packages/core/component/AI/constant/model.ts@@ -71,3 +71,51 @@ export function defaultModelForPlan(hasPaidAccess: boolean): TModel {export function modelsForPlan(hasPaidAccess: boolean): readonly TModel[] {return hasPaidAccess ? PAID_MODELS : FREE_MODELS;}++/** Provider serving each model — mirrors the backend `provider` field. */+export const MODEL_PROVIDER: ExhaustiveMap = {+ 'anthropic/claude-opus-4-8': 'anthropic',+ 'anthropic/claude-haiku-4-5': 'anthropic',+ 'anthropic/claude-sonnet-4-6': 'anthropic',+ 'openai/gpt-5.5': 'openai',+ 'openai/gpt-5-mini': 'openai',+} as const;++/** Options for {@link alternateProviderModel}. */+export type AlternateProviderModelOptions = {+ /**+ * The user's available models (in display order). The suggestion is drawn+ * only from these so we never propose a model the user can't use. When+ * omitted/empty, the full static model list is used.+ */+ candidates?: readonly TModel[];+ /**+ * Providers known to be failing this session. The suggestion avoids all of+ * them — so once Anthropic *and* OpenAI have failed we stop bouncing the user+ * between them and return `undefined` instead.+ */+ failedProviders?: Iterable<string>;+};++/**+ * Pick a model from a provider other than `current`'s — and other than any+ * provider already known to be failing this session — for recovering from a+ * provider outage. Returns `undefined` when no accessible model on a healthy+ * provider remains.+ */+export function alternateProviderModel(+ current: TModel,+ options?: AlternateProviderModelOptions+): TModel | undefined {+ // Exclude the current provider (always switch *away* from it) plus every+ // provider that has already failed this session.+ const excluded = new Set<string>(options?.failedProviders ?? []);+ excluded.add(MODEL_PROVIDER[current]);++ const candidates = options?.candidates;+ const pool =+ candidates && candidates.length > 0+ ? candidates+ : (Object.values(Model) as readonly TModel[]);+ return pool.find((id) => !excluded.has(MODEL_PROVIDER[id]));+}diff --git a/js/app/packages/core/component/AI/state/chatState.test.ts b/js/app/packages/core/component/AI/state/chatState.test.tsnew file mode 100644index 0000000000..543b3e616d--- /dev/null+++ b/js/app/packages/core/component/AI/state/chatState.test.ts@@ -0,0 +1,104 @@+import type { ChatMessageWithAttachments } from '@core/component/AI/types';+import { describe, expect, it } from 'vitest';+import { type ChatPhase, type SideEffect, transition } from './chatState';++const streaming: ChatPhase = { type: 'streaming' };+const sending: ChatPhase = { type: 'sending', optimisticMessageId: 'm1' };++const userMessage: ChatMessageWithAttachments = {+ id: 'm1',+ content: 'hi',+ role: 'user',+ attachments: [],+} as ChatMessageWithAttachments;++/** The single toast effect produced by a transition, or undefined. */+function toastOf(effects: SideEffect[]) {+ return effects.find((e) => e.type === 'toast') as+ | Extract<SideEffect, { type: 'toast' }>+ | undefined;+}++describe('transition: provider failure surfaces a toast', () => {+ it('a provider_error while streaming returns to idle and emits a switch-model toast', () => {+ const result = transition(streaming, {+ type: 'stream_error',+ streamError: 'provider_error',+ });++ expect(result.phase).toEqual({ type: 'idle' });+ const toast = toastOf(result.effects);+ expect(toast).toBeDefined();+ // The message points the user at switching models...+ expect(toast!.message).toMatch(/provider/i);+ // ...and flags that a "Switch model" action should be offered.+ expect(toast!.offerModelSwitch).toBe(true);+ });++ it('also surfaces the switch-model toast from the sending phase', () => {+ const result = transition(sending, {+ type: 'stream_error',+ streamError: 'provider_error',+ });+ expect(result.phase).toEqual({ type: 'idle' });+ expect(toastOf(result.effects)?.offerModelSwitch).toBe(true);+ });++ it('a context-overflow error toasts without offering a model switch', () => {+ const toast = toastOf(+ transition(streaming, {+ type: 'stream_error',+ streamError: 'model_context_overflow',+ }).effects+ );+ expect(toast).toBeDefined();+ expect(toast!.offerModelSwitch).toBeFalsy();+ expect(toast!.message).toMatch(/context/i);+ });++ it('an unknown stream error toasts a generic message without a switch', () => {+ const toast = toastOf(+ transition(streaming, {+ type: 'stream_error',+ streamError: 'something_unexpected',+ }).effects+ );+ expect(toast).toBeDefined();+ expect(toast!.offerModelSwitch).toBeFalsy();+ });+});++describe('transition: paywall on payment failure', () => {+ it('a send_failed with paymentError opens the paywall', () => {+ const result = transition(sending, {+ type: 'send_failed',+ paymentError: true,+ });+ expect(result.phase).toEqual({ type: 'idle' });+ expect(result.effects).toContainEqual({ type: 'show_paywall' });+ });++ it('a plain send_failure does not open the paywall', () => {+ const result = transition(sending, { type: 'send_failed' });+ expect(result.effects).toHaveLength(0);+ });+});++describe('transition: sanity of the happy path used by the failure tests', () => {+ it('send_started moves idle -> sending and queues the optimistic message', () => {+ const result = transition(+ { type: 'idle' },+ { type: 'send_started', optimisticMessage: userMessage }+ );+ expect(result.phase).toEqual({+ type: 'sending',+ optimisticMessageId: 'm1',+ });+ });+});++// Note: `transition` stays availability-agnostic by design — it always sets+// `offerModelSwitch: true` for a provider_error. Whether that becomes a "Switch+// model" button or a plain "try again later" outage message depends on whether+// an accessible alternate model exists, which only the controller knows. That+// branching is covered in createChatController.test.tsx.diff --git a/js/app/packages/core/component/AI/state/chatState.ts b/js/app/packages/core/component/AI/state/chatState.tsindex efd48f07ee..f121dba265 100644--- a/js/app/packages/core/component/AI/state/chatState.ts+++ b/js/app/packages/core/component/AI/state/chatState.ts@@ -34,7 +34,12 @@ export type ChatEvent =};export type SideEffect =- | { type: 'toast'; message: string }+ | {+ type: 'toast';+ message: string;+ /** When set, the toast offers a "Switch model" action button. */+ offerModelSwitch?: boolean;+ }| { type: 'show_paywall' };// --- Transition result ---@@ -47,6 +52,26 @@ type TransitionResult = {effects: SideEffect[];};+/** Build the toast effect for a `stream_error`, keyed off the typed reason. */+function streamErrorToast(streamError: string | undefined): SideEffect {+ switch (streamError) {+ case 'provider_error':+ return {+ type: 'toast',+ message:+ 'The AI provider may be down. Try switching to a different model.',+ offerModelSwitch: true,+ };+ case 'model_context_overflow':+ return {+ type: 'toast',+ message: 'Too much context. Remove attachments or start a new chat',+ };+ default:+ return { type: 'toast', message: 'Failed to respond to message' };+ }+}+const rejected = (phase: ChatPhase, event: string): TransitionResult => {console.warn(`chat transition: ${event} from ${phase.type}`);return { phase, effects: [] };@@ -125,15 +150,7 @@ export function transition([{ type: P.union('streaming', 'sending') }, { type: 'stream_error' }],([, e]) => ({phase: { type: 'idle' as const },- effects: [- {- type: 'toast' as const,- message:- e.streamError === 'model_context_overflow'- ? 'Too much context. Remove attachments or start a new chat'- : 'Failed to respond to message',- },- ],+ effects: [streamErrorToast(e.streamError)],})).otherwise(([p, e]) => rejected(p, e.type));diff --git a/js/app/packages/core/component/AI/state/createChatController.test.tsx b/js/app/packages/core/component/AI/state/createChatController.test.tsxnew file mode 100644index 0000000000..a921ce65cb--- /dev/null+++ b/js/app/packages/core/component/AI/state/createChatController.test.tsx@@ -0,0 +1,145 @@+/**+ * @vitest-environment jsdom+ */++import {+ alternateProviderModel,+ MODEL_PROVIDER,+ Model,+ modelsForPlan,+ type TModel,+} from '@core/component/AI/constant';+import type { ChatMessageWithAttachments } from '@core/component/AI/types';+import { createRoot, createSignal } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ failure: vi.fn() }));++// Capture toast calls so we can inspect the action buttons the controller wires.+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { failure: mocks.failure },+}));++// The controller subscribes to live streams on creation; no streams in tests.+vi.mock('@service-connection/stream', () => ({+ getEntityStreams: () => () => [],+}));++import {+ type ChatControllerOptions,+ createChatController,+} from './createChatController';++type ToastAction = { label: string; onClick: () => void };++function lastToastActions(): ToastAction[] | undefined {+ const call = mocks.failure.mock.calls.at(-1);+ return call?.[1]?.actions as ToastAction[] | undefined;+}++const optimistic: ChatMessageWithAttachments = {+ id: 'm1',+ content: 'hi',+ role: 'user',+ attachments: [],+} as ChatMessageWithAttachments;++/** Create a controller inside a reactive root and drive it into a failure. */+function failWhileSending(options?: ChatControllerOptions) {+ let dispose = () => {};+ createRoot((d) => {+ dispose = d;+ const controller = createChatController('chat-1', [], options);+ controller.dispatch({+ type: 'send_started',+ optimisticMessage: optimistic,+ });+ controller.dispatch({+ type: 'stream_error',+ streamError: 'provider_error',+ });+ });+ return dispose;+}++beforeEach(() => {+ mocks.failure.mockClear();+});++describe('createChatController: provider-failure toast', () => {+ it('shows a failure toast on a provider error', () => {+ const dispose = failWhileSending({ onSwitchModel: () => {} });+ expect(mocks.failure).toHaveBeenCalledTimes(1);+ dispose();+ });++ it('offers a "Switch model" action button when a model switch is wired up', () => {+ const onSwitchModel = vi.fn();+ const dispose = failWhileSending({ onSwitchModel });++ const actions = lastToastActions();+ expect(actions).toBeDefined();+ expect(actions![0].label).toBe('Switch model');++ // Clicking the button invokes the supplied switch handler.+ actions![0].onClick();+ expect(onSwitchModel).toHaveBeenCalledTimes(1);+ dispose();+ });++ it('the switch action swaps the active model to a different provider', () => {+ // Mirror exactly how Chat.tsx wires onSwitchModel: the chat's model signal+ // is the single source of truth, swapped via alternateProviderModel against+ // the user's accessible (paid) models.+ const [model, setModel] = createSignal<TModel>(Model.opus48);+ const onSwitchModel = () => {+ const alt = alternateProviderModel(model(), {+ candidates: [...modelsForPlan(true)],+ });+ if (alt) setModel(alt);+ };++ const dispose = failWhileSending({ onSwitchModel });+ expect(MODEL_PROVIDER[model()]).toBe('anthropic'); // before the swap++ lastToastActions()![0].onClick();++ // After clicking, the active model is from a different provider.+ expect(MODEL_PROVIDER[model()]).not.toBe('anthropic');+ expect(MODEL_PROVIDER[model()]).toBe('openai');+ dispose();+ });++ it('falls back to a plain toast (no action) when no switch handler is wired', () => {+ const dispose = failWhileSending(); // no onSwitchModel+ expect(mocks.failure).toHaveBeenCalledTimes(1);+ expect(lastToastActions()).toBeUndefined();+ dispose();+ });++ it('shows an outage message with no action when no alternate model is available', () => {+ // A switch handler is wired, but there is no accessible model on another+ // provider to switch to (e.g. every other provider already failed this+ // session). Instead of a dead "Switch model" button, the user gets a plain+ // "try again later" outage message.+ const onSwitchModel = vi.fn();+ const dispose = failWhileSending({+ onSwitchModel,+ hasAlternateModel: () => false,+ });++ const [message] = mocks.failure.mock.calls.at(-1)!;+ expect(lastToastActions()).toBeUndefined(); // no dead button+ expect(String(message)).toMatch(/try again later/i);+ dispose();+ });++ it('keeps offering the switch button while an alternate is still available', () => {+ const dispose = failWhileSending({+ onSwitchModel: () => {},+ hasAlternateModel: () => true,+ });+ expect(lastToastActions()?.[0].label).toBe('Switch model');+ dispose();+ });+});diff --git a/js/app/packages/core/component/AI/state/createChatController.ts b/js/app/packages/core/component/AI/state/createChatController.tsindex 72262a6022..ab198923cb 100644--- a/js/app/packages/core/component/AI/state/createChatController.ts+++ b/js/app/packages/core/component/AI/state/createChatController.ts@@ -47,6 +47,18 @@ export type ChatController = {export type ChatControllerOptions = {onShowPaywall?: () => void;+ /**+ * Switch the chat to a model from a different provider. When provided, a+ * provider-outage error toast offers a "Switch model" button that calls this.+ */+ onSwitchModel?: () => void;+ /**+ * Whether an accessible model on another (non-failed) provider exists to+ * switch to. When this returns `false`, a provider-outage toast shows a plain+ * "try again later" message instead of a dead "Switch model" button. Defaults+ * to assuming an alternate exists when not provided.+ */+ hasAlternateModel?: () => boolean;};export function createChatController(@@ -62,7 +74,28 @@ export function createChatController(function executeEffects(effects: SideEffect[]) {for (const effect of effects) {match(effect)- .with({ type: 'toast' }, (e) => toast.failure(e.message))+ .with({ type: 'toast' }, (e) => {+ const onSwitchModel = options?.onSwitchModel;+ const canSwitch =+ !!e.offerModelSwitch &&+ !!onSwitchModel &&+ (options?.hasAlternateModel?.() ?? true);+ if (canSwitch) {+ toast.failure(e.message, {+ duration: 10000,+ actions: [{ label: 'Switch model', onClick: onSwitchModel! }],+ });+ } else if (e.offerModelSwitch) {+ // Provider outage but nowhere to fall back to (no accessible model+ // on another provider, or every other provider has already failed+ // this session). Don't offer a dead button — tell the user to wait.+ toast.failure(+ 'The AI provider is currently unavailable. Please try again later.'+ );+ } else {+ toast.failure(e.message);+ }+ }).with({ type: 'show_paywall' }, () => options?.onShowPaywall?.()).exhaustive();}diff --git a/js/app/packages/core/component/AI/util/storage.test.ts b/js/app/packages/core/component/AI/util/storage.test.tsnew file mode 100644index 0000000000..8ae4cc5de4--- /dev/null+++ b/js/app/packages/core/component/AI/util/storage.test.ts@@ -0,0 +1,40 @@+/**+ * @vitest-environment jsdom+ */+import { beforeEach, describe, expect, it } from 'vitest';+import { DEFAULT_MODEL, Model } from '../constant';+import { getChatInputStoredState, storeChatStateImmediate } from './storage';++beforeEach(() => {+ localStorage.clear();+});++describe('chat input storage: model defaults', () => {+ it('remembers the last model a user picked for a chat', () => {+ storeChatStateImmediate('chat-a', { model: Model.gpt55, input: 'draft' });++ const restored = getChatInputStoredState('chat-a');+ expect(restored.model).toBe(Model.gpt55);+ expect(restored.input).toBe('draft');+ });++ it('keeps each chat on its own remembered model', () => {+ storeChatStateImmediate('chat-a', { model: Model.gpt55 });+ storeChatStateImmediate('chat-b', { model: Model.sonnet46 });++ expect(getChatInputStoredState('chat-a').model).toBe(Model.gpt55);+ expect(getChatInputStoredState('chat-b').model).toBe(Model.sonnet46);+ });++ it('returns no stored model for a chat that has never been used', () => {+ expect(getChatInputStoredState('never-seen').model).toBeUndefined();+ });++ it('falls back to the default model when the persisted value is stale/unknown', () => {+ // A model id that is no longer valid (e.g. left over from a previous build).+ storeChatStateImmediate('chat-c', {+ model: 'anthropic/claude-opus-4-7' as Model,+ });+ expect(getChatInputStoredState('chat-c').model).toBe(DEFAULT_MODEL);+ });+});diff --git a/js/app/packages/core/component/Toast/Toast.tsx b/js/app/packages/core/component/Toast/Toast.tsxindex 2bf64570c3..4621a26328 100644--- a/js/app/packages/core/component/Toast/Toast.tsx+++ b/js/app/packages/core/component/Toast/Toast.tsx@@ -233,7 +233,10 @@ function dismiss(toastId: number) {}// Tell users that an action has failed, because of us-function failure(message: string, options?: ToastOptions) {+function failure(+ message: string,+ options?: ToastOptions & { actions?: ToastAction[] }+) {dismissIfRecent(message, ToastType.FAILURE);createToast(message, ToastType.FAILURE, options);}diff --git a/js/bun.lock b/js/bun.lockindex add29b5d74..5498e98b42 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -883,7 +883,7 @@"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],@@ -2613,7 +2613,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/rust/cloud-storage/agent/src/error.rs b/rust/cloud-storage/agent/src/error.rsindex d7e8d3b8d6..2fc4d3f03c 100644--- a/rust/cloud-storage/agent/src/error.rs+++ b/rust/cloud-storage/agent/src/error.rs@@ -1,3 +1,25 @@+use rig_core::agent::StreamingError;+use rig_core::completion::{CompletionError, PromptError};++#[cfg(test)]+mod test;++/// How a failed agent turn should be surfaced to the user.+///+/// Lets callers (e.g. the chat stream endpoint) turn an opaque [`AgentError`]+/// into a well-typed, user-facing error without re-implementing the rig error+/// archaeology below.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FailureKind {+ /// The model provider returned an error or was unreachable — most likely a+ /// provider outage. The user should try a different model / provider.+ ProviderOutage,+ /// The request exceeded the model's context window.+ ContextOverflow,+ /// Anything else (serialization, our own bug, etc.).+ Internal,+}+/// Errors produced by the agent crate.#[derive(Debug, thiserror::Error)]pub enum AgentError {@@ -49,7 +71,58 @@ impl AgentError {_ => false,}}++ /// Classify this error for user-facing reporting.+ ///+ /// rig collapses provider HTTP failures into+ /// [`CompletionError::ProviderError`] / [`CompletionError::ResponseError`]+ /// (the HTTP status code is not preserved), so we inspect the innermost+ /// completion error: a context-window message maps to+ /// [`FailureKind::ContextOverflow`]; any other provider or transport+ /// failure maps to [`FailureKind::ProviderOutage`]; everything else is+ /// [`FailureKind::Internal`].+ pub fn failure_kind(&self) -> FailureKind {+ match self.completion_error() {+ Some(CompletionError::ProviderError(msg) | CompletionError::ResponseError(msg)) => {+ if is_context_overflow(msg) {+ FailureKind::ContextOverflow+ } else {+ FailureKind::ProviderOutage+ }+ }+ // Connection error / timeout — we couldn't reach the provider.+ Some(CompletionError::HttpError(_)) => FailureKind::ProviderOutage,+ _ => FailureKind::Internal,+ }+ }++ /// The innermost rig [`CompletionError`], if this error wraps one.+ fn completion_error(&self) -> Option<&CompletionError> {+ match self {+ AgentError::Completion(e) => Some(e),+ AgentError::Prompt(e) => prompt_completion_error(e),+ AgentError::Streaming(StreamingError::Completion(e)) => Some(e),+ AgentError::Streaming(StreamingError::Prompt(e)) => prompt_completion_error(e),+ _ => None,+ }+ }}-#[cfg(test)]-mod test;+/// Pull the [`CompletionError`] out of a [`PromptError`], if present.+fn prompt_completion_error(e: &PromptError) -> Option<&CompletionError> {+ match e {+ PromptError::CompletionError(e) => Some(e),+ _ => None,+ }+}++/// Whether a provider error message describes a context-window overflow rather+/// than an outage. Anthropic returns "prompt is too long"; OpenAI returns+/// "context_length_exceeded" / "maximum context length".+fn is_context_overflow(msg: &str) -> bool {+ let m = msg.to_ascii_lowercase();+ m.contains("context length")+ || m.contains("context_length")+ || m.contains("maximum context")+ || m.contains("prompt is too long")+}diff --git a/rust/cloud-storage/agent/src/error/test.rs b/rust/cloud-storage/agent/src/error/test.rsindex 8e0ec4324e..6ea99576b0 100644--- a/rust/cloud-storage/agent/src/error/test.rs+++ b/rust/cloud-storage/agent/src/error/test.rs@@ -37,3 +37,62 @@ fn unrelated_error_is_not_cancelled() {let err = AgentError::UnknownModel("foo/bar".to_string());assert!(!err.was_cancelled());}++#[test]+fn anthropic_500_body_is_provider_outage() {+ // What rig hands us for a 5xx: the raw provider body wrapped in ProviderError.+ let err = AgentError::Completion(CompletionError::ProviderError(+ r#"{"type":"error","error":{"type":"api_error","message":"Internal server error"}}"#+ .to_string(),+ ));+ assert_eq!(err.failure_kind(), FailureKind::ProviderOutage);+}++#[test]+fn overloaded_is_provider_outage() {+ let err = AgentError::Completion(CompletionError::ProviderError(+ r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#+ .to_string(),+ ));+ assert_eq!(err.failure_kind(), FailureKind::ProviderOutage);+}++#[test]+fn anthropic_prompt_too_long_is_context_overflow() {+ let err = AgentError::Completion(CompletionError::ProviderError(+ "prompt is too long: 250000 tokens > 200000 maximum".to_string(),+ ));+ assert_eq!(err.failure_kind(), FailureKind::ContextOverflow);+}++#[test]+fn openai_context_length_is_context_overflow() {+ let err = AgentError::Completion(CompletionError::ProviderError(+ "context_length_exceeded: maximum context length exceeded".to_string(),+ ));+ assert_eq!(err.failure_kind(), FailureKind::ContextOverflow);+}++#[test]+fn provider_error_through_streaming_prompt_is_classified() {+ // The real chat path surfaces errors as Streaming(Prompt(CompletionError)).+ let err = AgentError::Streaming(StreamingError::Prompt(Box::new(+ PromptError::CompletionError(CompletionError::ProviderError(+ "Service Unavailable".to_string(),+ )),+ )));+ assert_eq!(err.failure_kind(), FailureKind::ProviderOutage);+}++#[test]+fn json_error_is_internal() {+ let json_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();+ let err = AgentError::Json(json_err);+ assert_eq!(err.failure_kind(), FailureKind::Internal);+}++#[test]+fn unknown_model_is_internal() {+ let err = AgentError::UnknownModel("bogus".to_string());+ assert_eq!(err.failure_kind(), FailureKind::Internal);+}diff --git a/rust/cloud-storage/agent/src/lib.rs b/rust/cloud-storage/agent/src/lib.rsindex a290004613..6edac857b5 100644--- a/rust/cloud-storage/agent/src/lib.rs+++ b/rust/cloud-storage/agent/src/lib.rs@@ -19,7 +19,7 @@ pub use accumulator::StreamAccumulator;pub use agent_loop::{AgentLoop, Session};pub use completion::{complete, complete_with_history};pub use convert::{merge_consecutive_parts, to_rig_messages};-pub use error::AgentError;+pub use error::{AgentError, FailureKind};pub use model::PredefinedModel;pub use stream::{ChatCompletionStream, McpInfo, StreamPart, ToolCall, ToolResponse, Usage};pub use tool_adapter::{DynToolSetAdapter, ToolsetToolAdapter, normalize_request_schema};diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rsindex 62f095c410..698100dc80 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs@@ -407,6 +407,25 @@ async fn create_new_chat(Ok((chat, new_chat_id))}+/// Map an [`agent::AgentError`] to the well-typed [`StreamError`] sent to the+/// client. Provider outages and context overflows get their own variants so+/// the frontend can react specifically (e.g. prompt the user to switch+/// models); anything else falls back to a generic internal error.+fn stream_error_for(err: &agent::AgentError, stream_id: &str, model: &str) -> StreamError {+ match err.failure_kind() {+ agent::FailureKind::ProviderOutage => StreamError::ProviderError {+ stream_id: stream_id.to_string(),+ model: model.to_string(),+ },+ agent::FailureKind::ContextOverflow => StreamError::ModelContextOverflow {+ stream_id: stream_id.to_string(),+ },+ agent::FailureKind::Internal => StreamError::InternalError {+ stream_id: stream_id.to_string(),+ },+ }+}+/// For every `ToolCall` in `parts` that has no matching response, insert a/// synthetic `ToolCallErr { description: "cancelled", .. }` immediately after/// it. Used on cancellation so the persisted assistant message stays@@ -532,9 +551,7 @@ fn stream_and_save_message(Ok(stream) => stream,Err(e) => {tracing::error!(error=?e, chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "failed to create AI stream");- let stream_error = StreamError::InternalError {- stream_id: stream_id.clone(),- };+ let stream_error = stream_error_for(&e, &stream_id, &model);if let Ok(json) = serde_json::to_value(ChatStream::Error(stream_error)) {yield json;}@@ -609,9 +626,7 @@ fn stream_and_save_message(break;}tracing::error!(error=?e, chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "error in AI stream");- let stream_error = StreamError::InternalError {- stream_id: stream_id.clone(),- };+ let stream_error = stream_error_for(&e, &stream_id, &model);if let Ok(json) = serde_json::to_value(ChatStream::Error(stream_error)) {yield json;}