Skip to content

AI-native design editor. Open-source Figma alternative.

fix(ai): surface actionable provider failures

Danila Poyarkov61f11e7d24dc
diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.json
index 7cecc7bad..77bb803af 100644
--- a/packages/vue/src/i18n/locales/de/ai.json
+++ b/packages/vue/src/i18n/locales/de/ai.json
@@ -94,6 +94,12 @@
"reasoningEffortPlaceholder": "z. B. low, high, none",
"reasoningEffortDescription": "Optionaler anbieterspezifischer Wert.",
"maxOutputTokens": "Maximale Ausgabetoken",
+ "chatAuthenticationFailed": "Der API-Schlüssel des Anbieters ist ungültig oder abgelaufen. Ersetze ihn in den Einstellungen.",
+ "chatForbidden": "Dieser API-Schlüssel kann das ausgewählte Modell nicht verwenden. Prüfe den Modellzugriff.",
+ "chatModelNotFound": "Das ausgewählte Modell ist nicht verfügbar. Wähle in den Einstellungen ein anderes Modell.",
+ "chatNetworkFailed": "OpenPencil konnte den Anbieter nicht erreichen. Prüfe die Verbindung und den Endpunkt.",
+ "chatRateLimited": "Das Anfragelimit des Anbieters wurde erreicht. Warte kurz und versuche es erneut.",
+ "openProviderSettingsAction": "Einstellungen öffnen",
"chatInsufficientCredit": "Das Anbieterkonto hat nicht genügend Guthaben oder Kontingent. Lade es auf und versuche es erneut.",
"chatOutputLimit": "Das Modell hat beim Schlussfolgern das Ausgabetoken-Limit erreicht. Erhöhe die maximalen Ausgabetoken oder verringere den Schlussfolgerungsaufwand.",
"chatRequestFailed": "Die Modellanfrage ist fehlgeschlagen. Prüfe die Anbietereinstellungen und versuche es erneut.",
diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.json
index 56ebea44f..6befdac1a 100644
--- a/packages/vue/src/i18n/locales/es/ai.json
+++ b/packages/vue/src/i18n/locales/es/ai.json
@@ -94,6 +94,12 @@
"reasoningEffortPlaceholder": "p. ej. low, high, none",
"reasoningEffortDescription": "Valor opcional específico del proveedor.",
"maxOutputTokens": "Tokens de salida máx.",
+ "chatAuthenticationFailed": "La clave API del proveedor no es válida o ha caducado. Sustitúyela en Ajustes.",
+ "chatForbidden": "Esta clave API no puede usar el modelo seleccionado. Comprueba el acceso al modelo.",
+ "chatModelNotFound": "El modelo seleccionado no está disponible. Elige otro modelo en Ajustes.",
+ "chatNetworkFailed": "OpenPencil no pudo acceder al proveedor. Comprueba la conexión y el endpoint.",
+ "chatRateLimited": "Se alcanzó el límite de solicitudes del proveedor. Espera un momento e inténtalo de nuevo.",
+ "openProviderSettingsAction": "Abrir ajustes",
"chatInsufficientCredit": "La cuenta del proveedor no tiene suficiente saldo o cuota. Recárgala e inténtalo de nuevo.",
"chatOutputLimit": "El modelo agotó los tokens de salida mientras razonaba. Aumenta los tokens máximos de salida o reduce el esfuerzo de razonamiento.",
"chatRequestFailed": "La solicitud al modelo falló. Comprueba la configuración del proveedor e inténtalo de nuevo.",
diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.json
index 0b9ca3b2a..b0f900cb9 100644
--- a/packages/vue/src/i18n/locales/fr/ai.json
+++ b/packages/vue/src/i18n/locales/fr/ai.json
@@ -94,6 +94,12 @@
"reasoningEffortPlaceholder": "p. ex. low, high, none",
"reasoningEffortDescription": "Valeur facultative propre au fournisseur.",
"maxOutputTokens": "Jetons de sortie maximum",
+ "chatAuthenticationFailed": "La clé API du fournisseur est invalide ou expirée. Remplacez-la dans les paramètres.",
+ "chatForbidden": "Cette clé API ne peut pas utiliser le modèle sélectionné. Vérifiez son accès au modèle.",
+ "chatModelNotFound": "Le modèle sélectionné est indisponible. Choisissez-en un autre dans les paramètres.",
+ "chatNetworkFailed": "OpenPencil n’a pas pu joindre le fournisseur. Vérifiez la connexion et le point de terminaison.",
+ "chatRateLimited": "La limite de requêtes du fournisseur a été atteinte. Patientez puis réessayez.",
+ "openProviderSettingsAction": "Ouvrir les paramètres",
"chatInsufficientCredit": "Le compte du fournisseur n’a pas assez de crédit ou de quota. Rechargez-le et réessayez.",
"chatOutputLimit": "Le modèle a épuisé ses jetons de sortie pendant le raisonnement. Augmentez le nombre maximal de jetons de sortie ou réduisez l’effort de raisonnement.",
"chatRequestFailed": "La requête au modèle a échoué. Vérifiez les paramètres du fournisseur et réessayez.",
diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.json
index 1e5fdaf32..d94ebd648 100644
--- a/packages/vue/src/i18n/locales/it/ai.json
+++ b/packages/vue/src/i18n/locales/it/ai.json
@@ -94,6 +94,12 @@
"reasoningEffortPlaceholder": "es. low, high, none",
"reasoningEffortDescription": "Valore facoltativo specifico del provider.",
"maxOutputTokens": "Token di output massimi",
+ "chatAuthenticationFailed": "La chiave API del provider non è valida o è scaduta. Sostituiscila nelle Impostazioni.",
+ "chatForbidden": "Questa chiave API non può usare il modello selezionato. Controlla l’accesso al modello.",
+ "chatModelNotFound": "Il modello selezionato non è disponibile. Scegli un altro modello nelle Impostazioni.",
+ "chatNetworkFailed": "OpenPencil non ha raggiunto il provider. Controlla connessione ed endpoint.",
+ "chatRateLimited": "È stato raggiunto il limite di richieste del provider. Attendi e riprova.",
+ "openProviderSettingsAction": "Apri impostazioni",
"chatInsufficientCredit": "L’account del provider non dispone di credito o quota sufficiente. Ricaricalo e riprova.",
"chatOutputLimit": "Il modello ha esaurito i token di output durante il ragionamento. Aumenta i token di output massimi o riduci lo sforzo di ragionamento.",
"chatRequestFailed": "La richiesta al modello non è riuscita. Controlla le impostazioni del provider e riprova.",
diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.json
index ef0719c9c..ab4e726d2 100644
--- a/packages/vue/src/i18n/locales/ja/ai.json
+++ b/packages/vue/src/i18n/locales/ja/ai.json
@@ -94,6 +94,12 @@
"reasoningEffortPlaceholder": "例: low, high, none",
"reasoningEffortDescription": "プロバイダー固有の任意の値です。",
"maxOutputTokens": "最大出力トークン数",
+ "chatAuthenticationFailed": "プロバイダーのAPIキーが無効か期限切れです。設定で置き換えてください。",
+ "chatForbidden": "このAPIキーでは選択したモデルを使用できません。モデルへのアクセス権を確認してください。",
+ "chatModelNotFound": "選択したモデルは利用できません。設定で別のモデルを選択してください。",
+ "chatNetworkFailed": "OpenPencilからプロバイダーに接続できませんでした。接続とエンドポイントを確認してください。",
+ "chatRateLimited": "プロバイダーのリクエスト制限に達しました。少し待ってから再試行してください。",
+ "openProviderSettingsAction": "設定を開く",
"chatInsufficientCredit": "プロバイダーのアカウントに十分なクレジットまたは割り当てがありません。チャージして再試行してください。",
"chatOutputLimit": "推論中にモデルの出力トークンが上限に達しました。最大出力トークンを増やすか、推論の強度を下げてください。",
"chatRequestFailed": "モデルへのリクエストに失敗しました。プロバイダー設定を確認して再試行してください。",
diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.json
index 763918f7d..ebe8f3cc1 100644
--- a/packages/vue/src/i18n/locales/pl/ai.json
+++ b/packages/vue/src/i18n/locales/pl/ai.json
@@ -94,6 +94,12 @@
"reasoningEffortPlaceholder": "np. low, high, none",
"reasoningEffortDescription": "Opcjonalna wartość zależna od dostawcy.",
"maxOutputTokens": "Maks. tokenów wyjściowych",
+ "chatAuthenticationFailed": "Klucz API dostawcy jest nieprawidłowy lub wygasł. Zastąp go w Ustawieniach.",
+ "chatForbidden": "Ten klucz API nie może używać wybranego modelu. Sprawdź dostęp do modelu.",
+ "chatModelNotFound": "Wybrany model jest niedostępny. Wybierz inny model w Ustawieniach.",
+ "chatNetworkFailed": "OpenPencil nie mógł połączyć się z dostawcą. Sprawdź połączenie i endpoint.",
+ "chatRateLimited": "Osiągnięto limit żądań dostawcy. Poczekaj chwilę i spróbuj ponownie.",
+ "openProviderSettingsAction": "Otwórz ustawienia",
"chatInsufficientCredit": "Konto dostawcy nie ma wystarczających środków lub limitu. Doładuj je i spróbuj ponownie.",
"chatOutputLimit": "Model wyczerpał limit tokenów wyjściowych podczas rozumowania. Zwiększ maksymalną liczbę tokenów wyjściowych lub zmniejsz poziom rozumowania.",
"chatRequestFailed": "Żądanie do modelu nie powiodło się. Sprawdź ustawienia dostawcy i spróbuj ponownie.",
diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.json
index 6ae9945bf..a7a4277a1 100644
--- a/packages/vue/src/i18n/locales/ru/ai.json
+++ b/packages/vue/src/i18n/locales/ru/ai.json
@@ -94,6 +94,12 @@
"reasoningEffortPlaceholder": "например, low, high, none",
"reasoningEffortDescription": "Необязательное значение, зависящее от провайдера.",
"maxOutputTokens": "Максимум выходных токенов",
+ "chatAuthenticationFailed": "API-ключ провайдера недействителен или истёк. Замените его в настройках.",
+ "chatForbidden": "Этот API-ключ не может использовать выбранную модель. Проверьте доступ к модели.",
+ "chatModelNotFound": "Выбранная модель недоступна. Выберите другую модель в настройках.",
+ "chatNetworkFailed": "OpenPencil не удалось связаться с провайдером. Проверьте соединение и адрес сервера.",
+ "chatRateLimited": "Достигнут лимит запросов провайдера. Подождите и повторите попытку.",
+ "openProviderSettingsAction": "Открыть настройки",
"chatInsufficientCredit": "На счёте провайдера недостаточно средств или квоты. Пополните его и повторите попытку.",
"chatOutputLimit": "Модель исчерпала лимит выходных токенов во время рассуждения. Увеличьте максимум выходных токенов или снизьте глубину рассуждения.",
"chatRequestFailed": "Запрос к модели завершился ошибкой. Проверьте настройки провайдера и повторите попытку.",
diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.json
index 899d20637..bc39d6996 100644
--- a/packages/vue/src/i18n/locales/zh-cn/ai.json
+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json
@@ -94,6 +94,12 @@
"reasoningEffortPlaceholder": "例如 low、high、none",
"reasoningEffortDescription": "可选的提供商特定值。",
"maxOutputTokens": "最大输出 token 数",
+ "chatAuthenticationFailed": "提供商API密钥无效或已过期。请在设置中替换。",
+ "chatForbidden": "此API密钥无法使用所选模型。请检查模型访问权限。",
+ "chatModelNotFound": "所选模型不可用。请在设置中选择其他模型。",
+ "chatNetworkFailed": "OpenPencil无法连接提供商。请检查网络和端点。",
+ "chatRateLimited": "已达到提供商请求限制。请稍候再试。",
+ "openProviderSettingsAction": "打开设置",
"chatInsufficientCredit": "提供商账户的余额或配额不足。请充值后重试。",
"chatOutputLimit": "模型在推理时耗尽了输出 token。请提高最大输出 token 数或降低推理强度。",
"chatRequestFailed": "模型请求失败。请检查提供商设置后重试。",
diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.ts
index 507f770f3..905e315fd 100644
--- a/packages/vue/src/i18n/messages/ai.ts
+++ b/packages/vue/src/i18n/messages/ai.ts
@@ -107,11 +107,17 @@ export const aiMessageDefaults = {
reasoningEffortPlaceholder: 'e.g. low, high, none',
reasoningEffortDescription: 'Optional provider-specific value.',
maxOutputTokens: 'Max output tokens',
+ chatAuthenticationFailed: 'Your provider API key is invalid or expired. Replace it in Settings.',
+ chatForbidden: 'This API key cannot use the selected model. Check its model access.',
chatInsufficientCredit:
'The provider account has insufficient credit or quota. Top it up and try again.',
chatOutputLimit:
'The model ran out of output tokens while reasoning. Raise Max output tokens or lower reasoning effort.',
+ chatModelNotFound: 'The selected model is unavailable. Choose another model in Settings.',
+ chatNetworkFailed: 'OpenPencil could not reach the provider. Check your connection and endpoint.',
+ chatRateLimited: 'The provider rate limit was reached. Wait a moment and try again.',
chatRequestFailed: 'The model request failed. Check the provider settings and try again.',
+ openProviderSettingsAction: 'Open settings',
visionModelUnavailable: 'Choose a Vision model in Settings before attaching images.',
completions: 'Completions',
responses: 'Responses'
diff --git a/src/app/ai/chat/failure.ts b/src/app/ai/chat/failure.ts
index 99937f841..2c44a92d1 100644
--- a/src/app/ai/chat/failure.ts
+++ b/src/app/ai/chat/failure.ts
@@ -1,8 +1,20 @@
-export type AIChatFailureReason = 'insufficient-credit' | 'output-limit' | 'request-failed'
+import { APICallError } from 'ai'
+
+export type AIChatFailureReason =
+ | 'authentication'
+ | 'forbidden'
+ | 'insufficient-credit'
+ | 'model-not-found'
+ | 'network'
+ | 'output-limit'
+ | 'rate-limit'
+ | 'request-failed'
export type AIChatFailure = {
reason: AIChatFailureReason
detail?: string
+ statusCode?: number
+ retryable?: boolean
}
export type ProviderErrorShape = {
@@ -21,6 +33,7 @@ function statusNumber(value: unknown): number | null {
}
export function providerErrorStatus(error: unknown): number | null {
+ if (APICallError.isInstance(error)) return error.statusCode ?? null
if (typeof error !== 'object' || error === null) return null
const value = error as ProviderErrorShape
return (
@@ -37,9 +50,13 @@ function errorText(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
+function normalizedErrorText(error: unknown): string {
+ return errorText(error).toLowerCase()
+}
+
export function isInsufficientCreditError(error: unknown): boolean {
if (providerErrorStatus(error) === 402) return true
- const text = errorText(error).toLowerCase()
+ const text = normalizedErrorText(error)
return [
'insufficient credit',
'insufficient balance',
@@ -53,13 +70,49 @@ export function isInsufficientCreditError(error: unknown): boolean {
].some((phrase) => text.includes(phrase))
}
+function statusFailureReason(status: number | null): AIChatFailureReason | null {
+ if (status === 401) return 'authentication'
+ if (status === 402) return 'insufficient-credit'
+ if (status === 403) return 'forbidden'
+ if (status === 404) return 'model-not-found'
+ if (status === 408) return 'network'
+ if (status === 429) return 'rate-limit'
+ return null
+}
+
+function failureReason(error: unknown): AIChatFailureReason {
+ const statusReason = statusFailureReason(providerErrorStatus(error))
+ if (statusReason) return statusReason
+ if (isInsufficientCreditError(error)) return 'insufficient-credit'
+ const text = normalizedErrorText(error)
+ if (
+ (text.includes('expired') || text.includes('invalid') || text.includes('authentication')) &&
+ (text.includes('key') || text.includes('token') || text.includes('credential'))
+ ) {
+ return 'authentication'
+ }
+ if (text.includes('rate limit') || text.includes('too many requests')) return 'rate-limit'
+ if (text.includes('model not found') || text.includes('unknown model')) return 'model-not-found'
+ if (
+ text.includes('failed to fetch') ||
+ text.includes('network') ||
+ text.includes('cors') ||
+ text.includes('connection')
+ ) {
+ return 'network'
+ }
+ return 'request-failed'
+}
+
export function classifyAIChatFinish(finishReason?: string): AIChatFailure | null {
return finishReason === 'length' ? { reason: 'output-limit' } : null
}
export function classifyAIChatError(error: unknown): AIChatFailure {
return {
- reason: isInsufficientCreditError(error) ? 'insufficient-credit' : 'request-failed',
- detail: errorText(error)
+ reason: failureReason(error),
+ detail: errorText(error),
+ statusCode: providerErrorStatus(error) ?? undefined,
+ retryable: APICallError.isInstance(error) ? error.isRetryable : undefined
}
}
diff --git a/src/app/ai/chat/submission/use.ts b/src/app/ai/chat/submission/use.ts
index 3df1d2d14..58d451843 100644
--- a/src/app/ai/chat/submission/use.ts
+++ b/src/app/ai/chat/submission/use.ts
@@ -21,6 +21,7 @@ import type { EditorStore } from '@/app/editor/active-store'
export type ChatInstance = Pick<Chat<UIMessage>, 'messages' | 'sendMessage' | 'stop'>
interface SubmissionMessages {
+ openSettings: string
requestFailed: string
visionUnavailable: string
}
@@ -31,7 +32,7 @@ interface SubmissionOptions {
clearFailure: () => void
getEditor: () => EditorStore
messages: Ref<SubmissionMessages>
- reportError: (message: string) => void
+ reportError: (message: string, action?: { label: string; run: () => void }) => void
openModelSettings: () => void
}
@@ -41,7 +42,7 @@ export function useChatSubmission(options: SubmissionOptions) {
async function sendText(currentChat: ChatInstance, submission: ChatSubmission): Promise<void> {
const previousIds = new Set(currentChat.messages.map((message) => message.id))
- await currentChat.sendMessage({ text: submission.modelText })
+ await currentChat.sendMessage({ text: submission.modelText }).catch(() => undefined)
const message = currentChat.messages.find(
(candidate) => candidate.role === 'user' && !previousIds.has(candidate.id)
)
@@ -68,7 +69,9 @@ export function useChatSubmission(options: SubmissionOptions) {
for (const image of submission.images) revokeImagePreviewURL(image.previewURL)
if (submission.images.length === 0) {
- await currentChat.sendMessage({ messageId, text: submission.modelText })
+ await currentChat
+ .sendMessage({ messageId, text: submission.modelText })
+ .catch(() => undefined)
return
}
@@ -84,21 +87,25 @@ export function useChatSubmission(options: SubmissionOptions) {
preparedImages
)
setMessageAttachments(messageId, [...nodeAttachments, ...normalizedImages])
- await currentChat.sendMessage({
- messageId,
- text: designMessageWithImageFindings(
- submission.modelText,
- submission.images.map((image) => image.file.name),
- findings
- )
- })
+ await currentChat
+ .sendMessage({
+ messageId,
+ text: designMessageWithImageFindings(
+ submission.modelText,
+ submission.images.map((image) => image.file.name),
+ findings
+ )
+ })
+ .catch(() => undefined)
}
function reportSubmissionError(error: unknown): void {
console.error('Chat error:', error)
if (error instanceof VisionModelUnavailableError) {
- options.reportError(options.messages.value.visionUnavailable)
- options.openModelSettings()
+ options.reportError(options.messages.value.visionUnavailable, {
+ label: options.messages.value.openSettings,
+ run: options.openModelSettings
+ })
return
}
options.reportError(options.messages.value.requestFailed)
diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.ts
index fd9b01b4d..277e6375c 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -31,13 +31,14 @@ type ChatSessionOptions = {
getActiveEditorStore: () => EditorStore
}
-type ToolLoopTransportOptions = {
+export type ToolLoopTransportOptions = {
store: EditorStore
providerID: AIProviderID
model: LanguageModel
effectiveModelID: string
maxOutputTokens: number
reasoningEffort: string
+ onError?: (error: unknown) => void
}
const ANTHROPIC_CACHE_CONTROL = {
@@ -76,7 +77,8 @@ export function createToolLoopTransport({
model,
effectiveModelID,
maxOutputTokens,
- reasoningEffort
+ reasoningEffort,
+ onError
}: ToolLoopTransportOptions) {
const tools = createAITools(store)
const cacheProviderOptions = supportsAnthropicCaching(providerID, effectiveModelID)
@@ -115,7 +117,13 @@ export function createToolLoopTransport({
}
})
- return new DirectChatTransport({ agent }) as ChatTransport<UIMessage>
+ return new DirectChatTransport({
+ agent,
+ onError: (error) => {
+ onError?.(error)
+ return 'The provider rejected the request.'
+ }
+ }) as ChatTransport<UIMessage>
}
export function createChatSessionManager({
@@ -134,6 +142,11 @@ export function createChatSessionManager({
let acpTransportInstance: { destroy(): Promise<void> } | null = null
let harnessTransportInstance: { destroy(): Promise<void> } | null = null
let overrideTransport: (() => ChatTransport<UIMessage>) | null = null
+ let activeProviderError: unknown = null
+
+ function captureProviderError(error: unknown): void {
+ activeProviderError ??= error
+ }
function handleChatFinish({
finishReason,
@@ -152,6 +165,7 @@ export function createChatSessionManager({
}
function clearFailure(): void {
+ activeProviderError = null
failure.value = null
}
@@ -228,7 +242,8 @@ export function createChatSessionManager({
customModelID: runtime.role.profile.customModelID
}),
maxOutputTokens: runtime.role.profile.maxOutputTokens,
- reasoningEffort: runtime.role.profile.reasoningEffort ?? ''
+ reasoningEffort: runtime.role.profile.reasoningEffort ?? '',
+ onError: captureProviderError
})
}
@@ -251,8 +266,12 @@ export function createChatSessionManager({
transport,
messages,
onError: (error) => {
- failure.value = classifyAIChatError(error)
- recordChatFailed({ errorName: error instanceof Error ? error.name : 'unknown' })
+ const reportedError = activeProviderError ?? error
+ activeProviderError = null
+ failure.value = classifyAIChatError(reportedError)
+ recordChatFailed({
+ errorName: reportedError instanceof Error ? reportedError.name : 'unknown'
+ })
},
onFinish: handleChatFinish
})
diff --git a/src/app/shell/ui.ts b/src/app/shell/ui.ts
index d3225d897..8f2b32279 100644
--- a/src/app/shell/ui.ts
+++ b/src/app/shell/ui.ts
@@ -6,12 +6,18 @@ import type { ToastVariant } from '@/components/ui/toast'
export type { ToastVariant } from '@/components/ui/toast'
+export interface ToastAction {
+ label: string
+ run: () => void
+}
+
export interface Toast {
id: number
message: string
variant: ToastVariant
/** Number of times this message has been raised since it appeared. */
count: number
+ action?: ToastAction
}
const TOAST_DURATION = 3000
@@ -26,7 +32,7 @@ const toasts = ref<Toast[]>([])
let nextId = 0
let errorHandlersInitialized = false
-function push(message: string, variant: ToastVariant) {
+function push(message: string, variant: ToastVariant, action?: ToastAction) {
// Dedupe: if the same message+variant is already visible, increment
// its repeat count instead of stacking a duplicate. Prevents the
// cascade-on-every-frame failure mode where a single unhealthy
@@ -34,10 +40,10 @@ function push(message: string, variant: ToastVariant) {
const existing = toasts.value.find((t) => t.message === message && t.variant === variant)
if (existing) {
existing.count += 1
- existing.id = ++nextId
+ existing.action = action
return
}
- toasts.value.push({ id: ++nextId, message, variant, count: 1 })
+ toasts.value.push({ id: ++nextId, message, variant, count: 1, action })
if (toasts.value.length > TOAST_STACK_LIMIT) {
toasts.value.splice(0, toasts.value.length - TOAST_STACK_LIMIT)
}
@@ -51,8 +57,8 @@ function warning(message: string) {
push(message, 'warning')
}
-function error(message: string) {
- push(message, 'error')
+function error(message: string, action?: ToastAction) {
+ push(message, 'error', action)
}
function remove(id: number) {
diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vue
index 3e2cc74e3..9d5a021da 100644
--- a/src/components/ChatPanel.vue
+++ b/src/components/ChatPanel.vue
@@ -42,6 +42,7 @@ const submission = useChatSubmission({
clearFailure: clearChatFailure,
getEditor: getActiveEditorStore,
messages: computed(() => ({
+ openSettings: ai.value.openProviderSettingsAction,
requestFailed: ai.value.chatRequestFailed,
visionUnavailable: ai.value.visionModelUnavailable
})),
@@ -68,16 +69,29 @@ const acpLogCopied = refAutoReset(false, 1500)
const messages = computed(() => chat.value?.messages ?? [])
const failureMessage = computed(() => {
switch (chatFailure.value?.reason) {
+ case 'authentication':
+ return ai.value.chatAuthenticationFailed
+ case 'forbidden':
+ return ai.value.chatForbidden
case 'insufficient-credit':
return ai.value.chatInsufficientCredit
+ case 'model-not-found':
+ return ai.value.chatModelNotFound
+ case 'network':
+ return ai.value.chatNetworkFailed
case 'output-limit':
return ai.value.chatOutputLimit
+ case 'rate-limit':
+ return ai.value.chatRateLimited
case 'request-failed':
return ai.value.chatRequestFailed
default:
return null
}
})
+const failureHasSettingsAction = computed(() =>
+ ['authentication', 'forbidden', 'model-not-found'].includes(chatFailure.value?.reason ?? '')
+)
const status = computed(() => chat.value?.status ?? 'ready')
function isStreamingMessage(message: UIMessage, index: number): boolean {
return (
@@ -119,7 +133,15 @@ watch(
() => chatFailure.value?.reason,
(reason) => {
if (!reason) return
- toast.error(failureMessage.value ?? ai.value.chatRequestFailed)
+ toast.error(
+ failureMessage.value ?? ai.value.chatRequestFailed,
+ failureHasSettingsAction.value
+ ? {
+ label: ai.value.openProviderSettingsAction,
+ run: () => openSettingsDialog('ai')
+ }
+ : undefined
+ )
}
)
watch(
diff --git a/src/components/Shell/AppToast.vue b/src/components/Shell/AppToast.vue
index f96a66478..4a4b2627b 100644
--- a/src/components/Shell/AppToast.vue
+++ b/src/components/Shell/AppToast.vue
@@ -42,6 +42,14 @@ function toastClass(tone: ToastVariant) {
<ToastDescription class="min-w-0 flex-1 select-text">
{{ t.message }}<span v-if="t.count > 1" class="ml-1.5 opacity-70">×{{ t.count }}</span>
</ToastDescription>
+ <button
+ v-if="t.action"
+ type="button"
+ class="shrink-0 cursor-pointer rounded px-1.5 py-0.5 text-[10px] font-medium underline-offset-2 hover:underline"
+ @click="t.action.run()"
+ >
+ {{ t.action.label }}
+ </button>
<Tip
v-if="t.variant !== 'default'"
:label="copied ? common.copiedExclamation : common.copyMessage"
diff --git a/tests/e2e/chat/responses.spec.ts b/tests/e2e/chat/responses.spec.ts
index 92324b0b9..710a599bb 100644
--- a/tests/e2e/chat/responses.spec.ts
+++ b/tests/e2e/chat/responses.spec.ts
@@ -33,6 +33,20 @@ test('tool calls render their result', async ({ configuredChat: chat }) => {
await expect(chat.assistantMessage().getByText('Created a frame', { exact: false })).toBeVisible()
})
+test('authentication errors explain the cause and link to Settings', async ({
+ configuredChat: chat
+}) => {
+ await chat.submit('Trigger expired key error')
+
+ const toast = chat.page.getByTestId('toast-item').filter({
+ hasText: 'Your provider API key is invalid or expired. Replace it in Settings.'
+ })
+ await expect(toast).toBeVisible()
+ await expect(chat.page.getByTestId('toast-item')).toHaveCount(1)
+ await toast.getByRole('button', { name: 'Open settings' }).click()
+ await expect(chat.page.getByTestId('app-settings-dialog')).toBeVisible()
+})
+
test('transport errors show a safe localized toast', async ({ configuredChat: chat }) => {
await chat.submit('Trigger missing agent error')
await expect(
diff --git a/tests/engine/app/ai/failure.test.ts b/tests/engine/app/ai/failure.test.ts
index df372f0d3..d9f6842ac 100644
--- a/tests/engine/app/ai/failure.test.ts
+++ b/tests/engine/app/ai/failure.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, test } from 'bun:test'
+import { APICallError } from 'ai'
+
import {
classifyAIChatError,
classifyAIChatFinish,
@@ -19,12 +21,48 @@ describe('AI chat failures', () => {
expect(classifyAIChatFinish('stop')).toBeNull()
})
+ test('classifies actionable provider failures', () => {
+ const apiError = (statusCode: number, message: string) =>
+ new APICallError({
+ message,
+ url: 'https://provider.example/v1/chat',
+ requestBodyValues: {},
+ statusCode
+ })
+
+ expect(classifyAIChatError(apiError(401, 'API key expired.'))).toMatchObject({
+ reason: 'authentication',
+ statusCode: 401,
+ retryable: false
+ })
+ expect(classifyAIChatError(apiError(403, 'Forbidden'))).toMatchObject({
+ reason: 'forbidden',
+ statusCode: 403
+ })
+ expect(classifyAIChatError(apiError(404, 'Model not found'))).toMatchObject({
+ reason: 'model-not-found',
+ statusCode: 404
+ })
+ expect(classifyAIChatError(apiError(429, 'Too many requests'))).toMatchObject({
+ reason: 'rate-limit',
+ statusCode: 429,
+ retryable: true
+ })
+ })
+
+ test('classifies provider messages without exposing them as presentation copy', () => {
+ expect(classifyAIChatError(new Error('API key expired.')).reason).toBe('authentication')
+ expect(classifyAIChatError(new Error('Invalid API key.')).reason).toBe('authentication')
+ expect(classifyAIChatError(new Error('Failed to fetch provider')).reason).toBe('network')
+ expect(classifyAIChatError(new Error('Provider unavailable')).reason).toBe('request-failed')
+ })
+
test('retains request details for diagnostics', () => {
- expect(classifyAIChatError(new Error('Payment required'))).toEqual({
+ expect(classifyAIChatError(new Error('Payment required'))).toMatchObject({
reason: 'insufficient-credit',
detail: 'Payment required'
})
- expect(classifyAIChatError(new Error('Provider unavailable'))).toEqual({
+ expect(classifyAIChatError(new Error('Provider unavailable'))).toMatchObject({
reason: 'request-failed',
detail: 'Provider unavailable'
})
diff --git a/tests/helpers/chat/transport.ts b/tests/helpers/chat/transport.ts
index c1b1fcdcc..eaaee94e4 100644
--- a/tests/helpers/chat/transport.ts
+++ b/tests/helpers/chat/transport.ts
@@ -23,6 +23,14 @@ export async function injectMockChatTransport(page: Page): Promise<void> {
const multipleParts = normalized.includes('multiple parts')
const reasoning = normalized.includes('reasoning')
+ if (normalized.includes('expired key')) {
+ return new ReadableStream({
+ start(controller) {
+ controller.enqueue({ type: 'error', errorText: 'API key expired.' })
+ controller.close()
+ }
+ })
+ }
if (normalized.includes('missing agent')) {
throw new Error('Mock agent unavailable')
}
diff --git a/tools/i18n/mixed-script-baseline.txt b/tools/i18n/mixed-script-baseline.txt
index 1e148e315..26e82b576 100644
--- a/tools/i18n/mixed-script-baseline.txt
+++ b/tools/i18n/mixed-script-baseline.txt
@@ -3,6 +3,9 @@ ja:ai.apiKey
ja:ai.apiType
ja:ai.baseURL
ja:ai.baseURLPlaceholder
+ja:ai.chatAuthenticationFailed
+ja:ai.chatForbidden
+ja:ai.chatNetworkFailed
ja:ai.connectionTestAPITypeMismatch
ja:ai.connectionTestAuthFailed
ja:ai.connectionTestBrowserNetworkFailed
@@ -135,6 +138,9 @@ ja:variableTypes.booleanHint
zh-cn:ai.apiKey
zh-cn:ai.apiType
zh-cn:ai.baseURLPlaceholder
+zh-cn:ai.chatAuthenticationFailed
+zh-cn:ai.chatForbidden
+zh-cn:ai.chatNetworkFailed
zh-cn:ai.chatOutputLimit
zh-cn:ai.connectionTestAPITypeMismatch
zh-cn:ai.connectionTestAuthFailed