Skip to content

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

fix(ai): surface silent provider failures

Danila Poyarkov9e93884e7fe7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b52a2c164..571440404 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
### Fixed
+- Report exhausted provider credit, request failures, and output-token limits through chat toasts and copied diagnostics, and allow provider-specific reasoning effort on model profiles. (#451, #454)
- Fixed Windows desktop crashes when loading large system fonts for non-Latin text by using Tauri's binary IPC path and resolving native script fallbacks without parsing full font files in JavaScript.
- Preserve open vector segments when the same vector network also contains filled regions. (#450).
diff --git a/packages/vue/src/i18n/locales/de/dialogs.json b/packages/vue/src/i18n/locales/de/dialogs.json
index 2650570fc..b4c80d6fe 100644
--- a/packages/vue/src/i18n/locales/de/dialogs.json
+++ b/packages/vue/src/i18n/locales/de/dialogs.json
@@ -30,6 +30,7 @@
"connectionTestMissingModel": "Gib vor dem Testen eine Modell-ID ein.",
"connectionTestInvalidBaseURL": "Die Basis-URL ist ungültig. Verwende eine vollständige URL wie https://api.example.com/v1.",
"connectionTestAuthFailed": "Authentifizierung fehlgeschlagen. Prüfe deinen API-Schlüssel.",
+ "connectionTestInsufficientCredit": "Das Anbieterkonto hat nicht genügend Guthaben oder Kontingent. Lade es auf und versuche es erneut.",
"connectionTestModelNotFound": "Modell nicht gefunden. Prüfe die Modell-ID.",
"connectionTestAPITypeMismatch": "Dieser Endpunkt scheint den ausgewählten API-Typ nicht zu unterstützen. Versuche Completions oder Responses.",
"connectionTestBrowserNetworkFailed": "Dieser Endpunkt ist vom Browser aus nicht erreichbar. Versuche die Desktop-App oder einen Endpunkt mit aktiviertem CORS.",
@@ -146,10 +147,16 @@
"advancedModelSettings": "Erweiterte Einstellungen",
"outputLimit": "Ausgabelimit",
"outputLimitAutomatic": "Automatische Empfehlung",
+ "reasoningEffort": "Schlussfolgerungsaufwand",
+ "reasoningEffortPlaceholder": "z. B. low, high, none",
+ "reasoningEffortDescription": "Optionaler anbieterspezifischer Wert.",
"supported": "Unterstützt",
"unsupported": "Nicht unterstützt",
"tokens": "Token",
"maxOutputTokens": "Max output tokens",
+ "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.",
"clear": "Clear",
"keySavedReplace": "Key saved — enter new to replace",
"getAPIKeyGeneric": "Get API key →",
diff --git a/packages/vue/src/i18n/locales/es/dialogs.json b/packages/vue/src/i18n/locales/es/dialogs.json
index c3c695866..00eb152a8 100644
--- a/packages/vue/src/i18n/locales/es/dialogs.json
+++ b/packages/vue/src/i18n/locales/es/dialogs.json
@@ -30,6 +30,7 @@
"connectionTestMissingModel": "Introduce un ID de modelo antes de probar.",
"connectionTestInvalidBaseURL": "La URL base no es válida. Usa una URL completa como https://api.example.com/v1.",
"connectionTestAuthFailed": "Error de autenticación. Comprueba tu clave API.",
+ "connectionTestInsufficientCredit": "La cuenta del proveedor no tiene suficiente saldo o cuota. Recárgala e inténtalo de nuevo.",
"connectionTestModelNotFound": "No se ha encontrado el modelo. Comprueba el ID del modelo.",
"connectionTestAPITypeMismatch": "Este endpoint no parece admitir el tipo de API seleccionado. Prueba Completions o Responses.",
"connectionTestBrowserNetworkFailed": "No se ha podido acceder a este endpoint desde el navegador. Prueba la aplicación de escritorio o usa un endpoint con CORS habilitado.",
@@ -146,10 +147,16 @@
"advancedModelSettings": "Ajustes avanzados",
"outputLimit": "Límite de salida",
"outputLimitAutomatic": "Recomendación automática",
+ "reasoningEffort": "Esfuerzo de razonamiento",
+ "reasoningEffortPlaceholder": "p. ej. low, high, none",
+ "reasoningEffortDescription": "Valor opcional específico del proveedor.",
"supported": "Compatible",
"unsupported": "No compatible",
"tokens": "tokens",
"maxOutputTokens": "Tokens de salida máx.",
+ "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.",
"clear": "Limpiar",
"keySavedReplace": "Clave guardada - introduce una nueva para reemplazarla",
"getAPIKeyGeneric": "Obtener clave API →",
diff --git a/packages/vue/src/i18n/locales/fr/dialogs.json b/packages/vue/src/i18n/locales/fr/dialogs.json
index d7687bd11..2b7d492fd 100644
--- a/packages/vue/src/i18n/locales/fr/dialogs.json
+++ b/packages/vue/src/i18n/locales/fr/dialogs.json
@@ -30,6 +30,7 @@
"connectionTestMissingModel": "Saisissez un ID de modèle avant le test.",
"connectionTestInvalidBaseURL": "L’URL de base est invalide. Utilisez une URL complète comme https://api.example.com/v1.",
"connectionTestAuthFailed": "Échec de l’authentification. Vérifiez votre clé API.",
+ "connectionTestInsufficientCredit": "Le compte du fournisseur n’a pas assez de crédit ou de quota. Rechargez-le et réessayez.",
"connectionTestModelNotFound": "Modèle introuvable. Vérifiez son ID.",
"connectionTestAPITypeMismatch": "Ce point de terminaison ne semble pas prendre en charge le type d’API sélectionné. Essayez Completions ou Responses.",
"connectionTestBrowserNetworkFailed": "Impossible d’atteindre ce point de terminaison depuis le navigateur. Essayez l’application de bureau ou un point de terminaison avec CORS activé.",
@@ -146,10 +147,16 @@
"advancedModelSettings": "Paramètres avancés",
"outputLimit": "Limite de sortie",
"outputLimitAutomatic": "Recommandation automatique",
+ "reasoningEffort": "Effort de raisonnement",
+ "reasoningEffortPlaceholder": "p. ex. low, high, none",
+ "reasoningEffortDescription": "Valeur facultative propre au fournisseur.",
"supported": "Pris en charge",
"unsupported": "Non pris en charge",
"tokens": "jetons",
"maxOutputTokens": "Max output tokens",
+ "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.",
"clear": "Clear",
"keySavedReplace": "Key saved — enter new to replace",
"getAPIKeyGeneric": "Get API key →",
diff --git a/packages/vue/src/i18n/locales/it/dialogs.json b/packages/vue/src/i18n/locales/it/dialogs.json
index 8eec346f9..8579f6d87 100644
--- a/packages/vue/src/i18n/locales/it/dialogs.json
+++ b/packages/vue/src/i18n/locales/it/dialogs.json
@@ -30,6 +30,7 @@
"connectionTestMissingModel": "Inserisci un ID modello prima della verifica.",
"connectionTestInvalidBaseURL": "L’URL di base non è valido. Usa un URL completo come https://api.example.com/v1.",
"connectionTestAuthFailed": "Autenticazione non riuscita. Controlla la chiave API.",
+ "connectionTestInsufficientCredit": "L’account del provider non dispone di credito o quota sufficiente. Ricaricalo e riprova.",
"connectionTestModelNotFound": "Modello non trovato. Controlla l’ID modello.",
"connectionTestAPITypeMismatch": "Questo endpoint non sembra supportare il tipo di API selezionato. Prova Completions o Responses.",
"connectionTestBrowserNetworkFailed": "Impossibile raggiungere questo endpoint dal browser. Prova l’app desktop o usa un endpoint con CORS abilitato.",
@@ -146,10 +147,16 @@
"advancedModelSettings": "Impostazioni avanzate",
"outputLimit": "Limite di output",
"outputLimitAutomatic": "Raccomandazione automatica",
+ "reasoningEffort": "Impegno di ragionamento",
+ "reasoningEffortPlaceholder": "es. low, high, none",
+ "reasoningEffortDescription": "Valore facoltativo specifico del provider.",
"supported": "Supportato",
"unsupported": "Non supportato",
"tokens": "token",
"maxOutputTokens": "Max output tokens",
+ "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.",
"clear": "Clear",
"keySavedReplace": "Key saved — enter new to replace",
"getAPIKeyGeneric": "Get API key →",
diff --git a/packages/vue/src/i18n/locales/ja/dialogs.json b/packages/vue/src/i18n/locales/ja/dialogs.json
index cb0d034d0..a975ef8a0 100644
--- a/packages/vue/src/i18n/locales/ja/dialogs.json
+++ b/packages/vue/src/i18n/locales/ja/dialogs.json
@@ -30,6 +30,7 @@
"connectionTestMissingModel": "テストする前にモデルIDを入力してください。",
"connectionTestInvalidBaseURL": "ベースURLが無効です。https://api.example.com/v1 のような完全なURLを使用してください。",
"connectionTestAuthFailed": "認証に失敗しました。APIキーを確認してください。",
+ "connectionTestInsufficientCredit": "プロバイダーのアカウントに十分なクレジットまたは割り当てがありません。チャージして再試行してください。",
"connectionTestModelNotFound": "モデルが見つかりません。モデルIDを確認してください。",
"connectionTestAPITypeMismatch": "このエンドポイントは選択したAPIタイプに対応していないようです。CompletionsまたはResponsesをお試しください。",
"connectionTestBrowserNetworkFailed": "ブラウザからこのエンドポイントに接続できませんでした。デスクトップアプリを試すか、CORSが有効なエンドポイントを使用してください。",
@@ -146,10 +147,16 @@
"advancedModelSettings": "詳細設定",
"outputLimit": "出力上限",
"outputLimitAutomatic": "自動推奨値",
+ "reasoningEffort": "推論の強度",
+ "reasoningEffortPlaceholder": "例: low, high, none",
+ "reasoningEffortDescription": "プロバイダー固有の任意の値です。",
"supported": "対応",
"unsupported": "非対応",
"tokens": "トークン",
"maxOutputTokens": "最大出力トークン数",
+ "chatInsufficientCredit": "プロバイダーのアカウントに十分なクレジットまたは割り当てがありません。チャージして再試行してください。",
+ "chatOutputLimit": "推論中にモデルの出力トークンが上限に達しました。最大出力トークンを増やすか、推論の強度を下げてください。",
+ "chatRequestFailed": "モデルへのリクエストに失敗しました。プロバイダー設定を確認して再試行してください。",
"clear": "クリア",
"keySavedReplace": "キーが保存されました - 上書きするには新しいキーを入力してください",
"getAPIKeyGeneric": "APIキーを取得 →",
diff --git a/packages/vue/src/i18n/locales/pl/dialogs.json b/packages/vue/src/i18n/locales/pl/dialogs.json
index 8c36a4962..41103b392 100644
--- a/packages/vue/src/i18n/locales/pl/dialogs.json
+++ b/packages/vue/src/i18n/locales/pl/dialogs.json
@@ -30,6 +30,7 @@
"connectionTestMissingModel": "Wprowadź identyfikator modelu przed rozpoczęciem testu.",
"connectionTestInvalidBaseURL": "Bazowy adres URL jest nieprawidłowy. Użyj pełnego adresu, np. https://api.example.com/v1.",
"connectionTestAuthFailed": "Uwierzytelnianie nie powiodło się. Sprawdź klucz API.",
+ "connectionTestInsufficientCredit": "Konto dostawcy nie ma wystarczających środków lub limitu. Doładuj je i spróbuj ponownie.",
"connectionTestModelNotFound": "Nie znaleziono modelu. Sprawdź jego identyfikator.",
"connectionTestAPITypeMismatch": "Ten punkt końcowy prawdopodobnie nie obsługuje wybranego typu API. Spróbuj Completions lub Responses.",
"connectionTestBrowserNetworkFailed": "Nie udało się połączyć z tym punktem końcowym z przeglądarki. Spróbuj użyć aplikacji komputerowej lub punktu końcowego z włączonym CORS.",
@@ -146,10 +147,16 @@
"advancedModelSettings": "Ustawienia zaawansowane",
"outputLimit": "Limit wyjścia",
"outputLimitAutomatic": "Automatyczna rekomendacja",
+ "reasoningEffort": "Poziom rozumowania",
+ "reasoningEffortPlaceholder": "np. low, high, none",
+ "reasoningEffortDescription": "Opcjonalna wartość zależna od dostawcy.",
"supported": "Obsługiwane",
"unsupported": "Nieobsługiwane",
"tokens": "tokenów",
"maxOutputTokens": "Max output tokens",
+ "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.",
"clear": "Clear",
"keySavedReplace": "Key saved — enter new to replace",
"getAPIKeyGeneric": "Get API key →",
diff --git a/packages/vue/src/i18n/locales/ru/dialogs.json b/packages/vue/src/i18n/locales/ru/dialogs.json
index e0811266f..66563b167 100644
--- a/packages/vue/src/i18n/locales/ru/dialogs.json
+++ b/packages/vue/src/i18n/locales/ru/dialogs.json
@@ -30,6 +30,7 @@
"connectionTestMissingModel": "Введите ID модели перед проверкой.",
"connectionTestInvalidBaseURL": "Недопустимый базовый URL. Используйте полный URL, например https://api.example.com/v1.",
"connectionTestAuthFailed": "Не удалось пройти аутентификацию. Проверьте API-ключ.",
+ "connectionTestInsufficientCredit": "На счёте провайдера недостаточно средств или квоты. Пополните его и повторите попытку.",
"connectionTestModelNotFound": "Модель не найдена. Проверьте ID модели.",
"connectionTestAPITypeMismatch": "Эта конечная точка, вероятно, не поддерживает выбранный тип API. Попробуйте Completions или Responses.",
"connectionTestBrowserNetworkFailed": "Не удалось подключиться к этой конечной точке из браузера. Попробуйте настольное приложение или конечную точку с поддержкой CORS.",
@@ -146,10 +147,16 @@
"advancedModelSettings": "Расширенные настройки",
"outputLimit": "Лимит вывода",
"outputLimitAutomatic": "Автоматическая рекомендация",
+ "reasoningEffort": "Глубина рассуждения",
+ "reasoningEffortPlaceholder": "например, low, high, none",
+ "reasoningEffortDescription": "Необязательное значение, зависящее от провайдера.",
"supported": "Поддерживается",
"unsupported": "Не поддерживается",
"tokens": "токенов",
"maxOutputTokens": "Max output tokens",
+ "chatInsufficientCredit": "На счёте провайдера недостаточно средств или квоты. Пополните его и повторите попытку.",
+ "chatOutputLimit": "Модель исчерпала лимит выходных токенов во время рассуждения. Увеличьте максимум выходных токенов или снизьте глубину рассуждения.",
+ "chatRequestFailed": "Запрос к модели завершился ошибкой. Проверьте настройки провайдера и повторите попытку.",
"clear": "Clear",
"keySavedReplace": "Key saved — enter new to replace",
"getAPIKeyGeneric": "Get API key →",
diff --git a/packages/vue/src/i18n/locales/zh-cn/dialogs.json b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
index e1ce341d4..cd34cb94c 100644
--- a/packages/vue/src/i18n/locales/zh-cn/dialogs.json
+++ b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
@@ -30,6 +30,7 @@
"connectionTestMissingModel": "请在测试前输入模型 ID。",
"connectionTestInvalidBaseURL": "基础 URL 无效。请使用完整 URL,例如 https://api.example.com/v1。",
"connectionTestAuthFailed": "身份验证失败。请检查 API 密钥。",
+ "connectionTestInsufficientCredit": "提供商账户的余额或配额不足。请充值后重试。",
"connectionTestModelNotFound": "找不到模型。请检查模型 ID。",
"connectionTestAPITypeMismatch": "此端点似乎不支持所选的 API 类型。请尝试 Completions 或 Responses。",
"connectionTestBrowserNetworkFailed": "无法从浏览器访问此端点。请尝试桌面应用,或使用已启用 CORS 的端点。",
@@ -146,10 +147,16 @@
"advancedModelSettings": "高级设置",
"outputLimit": "输出限制",
"outputLimitAutomatic": "自动建议",
+ "reasoningEffort": "推理强度",
+ "reasoningEffortPlaceholder": "例如 low、high、none",
+ "reasoningEffortDescription": "可选的提供商特定值。",
"supported": "支持",
"unsupported": "不支持",
"tokens": "token",
"maxOutputTokens": "最大输出 token 数",
+ "chatInsufficientCredit": "提供商账户的余额或配额不足。请充值后重试。",
+ "chatOutputLimit": "模型在推理时耗尽了输出 token。请提高最大输出 token 数或降低推理强度。",
+ "chatRequestFailed": "模型请求失败。请检查提供商设置后重试。",
"clear": "清除",
"keySavedReplace": "密钥已保存,输入新密钥以替换",
"getAPIKeyGeneric": "获取 API 密钥 →",
diff --git a/packages/vue/src/i18n/messages/dialogs.ts b/packages/vue/src/i18n/messages/dialogs.ts
index d351c1f89..da99ac45b 100644
--- a/packages/vue/src/i18n/messages/dialogs.ts
+++ b/packages/vue/src/i18n/messages/dialogs.ts
@@ -116,6 +116,8 @@ export const dialogMessageDefaults = {
connectionTestInvalidBaseURL:
'Base URL is invalid. Use a full URL like https://api.example.com/v1.',
connectionTestAuthFailed: 'Authentication failed. Check your API key.',
+ connectionTestInsufficientCredit:
+ 'The provider account has insufficient credit or quota. Top it up and try again.',
connectionTestModelNotFound: 'Model not found. Check the model ID.',
connectionTestAPITypeMismatch:
'This endpoint does not appear to support the selected API type. Try Completions or Responses.',
@@ -222,9 +224,17 @@ export const dialogMessageDefaults = {
advancedModelSettings: 'Advanced settings',
outputLimit: 'Output limit',
outputLimitAutomatic: 'Automatic recommendation',
+ reasoningEffort: 'Reasoning effort',
+ reasoningEffortPlaceholder: 'e.g. low, high, none',
+ reasoningEffortDescription: 'Optional provider-specific value.',
supported: 'Supported',
unsupported: 'Not supported',
tokens: 'tokens',
+ 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.',
+ chatRequestFailed: 'The model request failed. Check the provider settings and try again.',
maxOutputTokens: 'Max output tokens',
clear: 'Clear',
keySavedReplace: 'Key saved — enter new to replace',
diff --git a/src/app/ai/chat/connection-test.ts b/src/app/ai/chat/connection-test.ts
index 66fa5f696..3a57e88c2 100644
--- a/src/app/ai/chat/connection-test.ts
+++ b/src/app/ai/chat/connection-test.ts
@@ -1,5 +1,6 @@
import { generateText } from 'ai'
+import { isInsufficientCreditError, providerErrorStatus } from '@/app/ai/chat/failure'
import { createLanguageModel, resolveLanguageModelID, type ModelConfig } from '@/app/ai/chat/model'
import { isTauri } from '@/app/tauri/env'
@@ -13,6 +14,7 @@ export type ProviderConnectionTestFailureReason =
| 'missing-model'
| 'invalid-base-url'
| 'auth'
+ | 'insufficient-credit'
| 'model-not-found'
| 'api-type'
| 'browser-network'
@@ -38,37 +40,6 @@ function validateConfig(config: ModelConfig): ProviderConnectionTestFailureReaso
return null
}
-type ProviderErrorShape = {
- statusCode?: unknown
- status?: unknown
- responseStatusCode?: unknown
- responseStatus?: unknown
- code?: unknown
- response?: { status?: unknown }
-}
-
-function isProviderErrorShape(error: unknown): error is ProviderErrorShape {
- return typeof error === 'object' && error !== null
-}
-
-function statusNumber(value: unknown): number | null {
- if (typeof value === 'number') return value
- if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value)
- return null
-}
-
-function errorStatus(error: unknown): number | null {
- if (!isProviderErrorShape(error)) return null
- return (
- statusNumber(error.statusCode) ??
- statusNumber(error.status) ??
- statusNumber(error.responseStatusCode) ??
- statusNumber(error.responseStatus) ??
- statusNumber(error.code) ??
- statusNumber(error.response?.status)
- )
-}
-
function errorText(error: unknown): string {
if (error instanceof Error) return `${error.name}: ${error.message}`
return String(error)
@@ -113,8 +84,9 @@ function classifyMessage(text: string): ProviderConnectionTestFailureReason | nu
}
function classifyError(error: unknown): ProviderConnectionTestFailureReason {
+ if (isInsufficientCreditError(error)) return 'insufficient-credit'
const text = errorText(error).toLowerCase()
- return classifyStatus(errorStatus(error), text) ?? classifyMessage(text) ?? 'unknown'
+ return classifyStatus(providerErrorStatus(error), text) ?? classifyMessage(text) ?? 'unknown'
}
export async function testProviderConnection(
diff --git a/src/app/ai/chat/failure.ts b/src/app/ai/chat/failure.ts
new file mode 100644
index 000000000..99937f841
--- /dev/null
+++ b/src/app/ai/chat/failure.ts
@@ -0,0 +1,65 @@
+export type AIChatFailureReason = 'insufficient-credit' | 'output-limit' | 'request-failed'
+
+export type AIChatFailure = {
+ reason: AIChatFailureReason
+ detail?: string
+}
+
+export type ProviderErrorShape = {
+ statusCode?: unknown
+ status?: unknown
+ responseStatusCode?: unknown
+ responseStatus?: unknown
+ code?: unknown
+ response?: { status?: unknown }
+}
+
+function statusNumber(value: unknown): number | null {
+ if (typeof value === 'number') return value
+ if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value)
+ return null
+}
+
+export function providerErrorStatus(error: unknown): number | null {
+ if (typeof error !== 'object' || error === null) return null
+ const value = error as ProviderErrorShape
+ return (
+ statusNumber(value.statusCode) ??
+ statusNumber(value.status) ??
+ statusNumber(value.responseStatusCode) ??
+ statusNumber(value.responseStatus) ??
+ statusNumber(value.code) ??
+ statusNumber(value.response?.status)
+ )
+}
+
+function errorText(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
+
+export function isInsufficientCreditError(error: unknown): boolean {
+ if (providerErrorStatus(error) === 402) return true
+ const text = errorText(error).toLowerCase()
+ return [
+ 'insufficient credit',
+ 'insufficient balance',
+ 'insufficient quota',
+ 'credit balance',
+ 'payment required',
+ 'quota exceeded',
+ 'billing quota',
+ 'top up',
+ 'top-up'
+ ].some((phrase) => text.includes(phrase))
+}
+
+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)
+ }
+}
diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.ts
index da1cff0ea..aa840e570 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -1,11 +1,17 @@
import { Chat } from '@ai-sdk/vue'
import { DirectChatTransport, stepCountIs, ToolLoopAgent } from 'ai'
-import type { ChatTransport, LanguageModel, UIMessage } from 'ai'
+import type { ChatTransport, FinishReason, LanguageModel, UIMessage } from 'ai'
import type { ComputedRef, Ref } from 'vue'
+import { ref } from 'vue'
import { ACP_AGENTS } from '@open-pencil/core/constants'
import type { ACPAgentID, AIProviderID } from '@open-pencil/core/constants'
+import {
+ classifyAIChatError,
+ classifyAIChatFinish,
+ type AIChatFailure
+} from '@/app/ai/chat/failure'
import { resolveLanguageModelID } from '@/app/ai/chat/model'
import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt.md?raw'
import { createAIModelRuntime } from '@/app/ai/models'
@@ -28,6 +34,7 @@ type ToolLoopTransportOptions = {
model: LanguageModel
effectiveModelID: string
maxOutputTokens: number
+ reasoningEffort: string
}
const ANTHROPIC_CACHE_CONTROL = {
@@ -42,6 +49,31 @@ function supportsAnthropicCaching(providerID: AIProviderID, modelID: string): bo
)
}
+type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }
+type AIProviderOptions = Record<string, { [key: string]: JSONValue }>
+
+export function buildReasoningProviderOptions(
+ providerID: AIProviderID,
+ reasoningEffort: string
+): AIProviderOptions | undefined {
+ if (!reasoningEffort) return undefined
+ if (providerID === 'openrouter') {
+ return { openrouter: { reasoning: { effort: reasoningEffort } } }
+ }
+ if (providerID === 'openai' || providerID === 'openai-compatible') {
+ return { openai: { reasoningEffort } }
+ }
+ return undefined
+}
+
+function mergeProviderOptions(
+ cacheOptions: typeof ANTHROPIC_CACHE_CONTROL | undefined,
+ reasoningOptions: AIProviderOptions | undefined
+): AIProviderOptions | undefined {
+ if (!cacheOptions && !reasoningOptions) return undefined
+ return { ...cacheOptions, ...reasoningOptions }
+}
+
export async function createACPTransport(providerID: AIProviderID) {
const agentId = providerID.replace('acp:', '') as ACPAgentID
const agentDef = ACP_AGENTS.find((a) => a.id === agentId)
@@ -57,12 +89,17 @@ export function createToolLoopTransport({
providerID,
model,
effectiveModelID,
- maxOutputTokens
+ maxOutputTokens,
+ reasoningEffort
}: ToolLoopTransportOptions) {
const tools = createAITools(store)
const cacheProviderOptions = supportsAnthropicCaching(providerID, effectiveModelID)
? ANTHROPIC_CACHE_CONTROL
: undefined
+ const providerOptions = mergeProviderOptions(
+ cacheProviderOptions,
+ buildReasoningProviderOptions(providerID, reasoningEffort)
+ )
const agent = new ToolLoopAgent({
model,
@@ -70,13 +107,13 @@ export function createToolLoopTransport({
tools,
stopWhen: stepCountIs(MAX_AGENT_STEPS),
maxOutputTokens,
- providerOptions: cacheProviderOptions,
+ providerOptions,
prepareCall: (options) => {
resetRunSteps(store)
return {
...options,
maxOutputTokens,
- providerOptions: cacheProviderOptions
+ providerOptions
}
},
onStepFinish: ({ usage }) => {
@@ -103,6 +140,7 @@ export function createChatSessionManager({
credentialsReady,
getActiveEditorStore
}: ChatSessionOptions) {
+ const failure = ref<AIChatFailure | null>(null)
let transportDirty = false
let currentChatStore: EditorStore | null = null
let currentChatMessages = new WeakMap<EditorStore, UIMessage[]>()
@@ -110,6 +148,22 @@ export function createChatSessionManager({
let acpTransportInstance: { destroy(): Promise<void> } | null = null
let overrideTransport: (() => ChatTransport<UIMessage>) | null = null
+ function handleChatFinish({
+ finishReason,
+ isAbort,
+ isError
+ }: {
+ finishReason?: FinishReason
+ isAbort: boolean
+ isError: boolean
+ }): void {
+ if (!isAbort && !isError) failure.value = classifyAIChatFinish(finishReason)
+ }
+
+ function clearFailure(): void {
+ failure.value = null
+ }
+
function markTransportDirty() {
transportDirty = true
currentChatStore = null
@@ -142,7 +196,8 @@ export function createChatSessionManager({
modelID: runtime.role.profile.modelID,
customModelID: runtime.role.profile.customModelID
}),
- maxOutputTokens: runtime.role.profile.maxOutputTokens
+ maxOutputTokens: runtime.role.profile.maxOutputTokens,
+ reasoningEffort: runtime.role.profile.reasoningEffort ?? ''
})
}
@@ -160,7 +215,14 @@ export function createChatSessionManager({
const transport: ChatTransport<UIMessage> = isACPProvider.value
? await createActiveACPTransport()
: await createTransport(store)
- chat = new Chat<UIMessage>({ transport, messages })
+ chat = new Chat<UIMessage>({
+ transport,
+ messages,
+ onError: (error) => {
+ failure.value = classifyAIChatError(error)
+ },
+ onFinish: handleChatFinish
+ })
currentChatStore = store
transportDirty = false
}
@@ -169,6 +231,7 @@ export function createChatSessionManager({
function resetChat() {
if (currentChatStore) currentChatMessages.delete(currentChatStore)
+ failure.value = null
chat = null
currentChatStore = null
transportDirty = false
@@ -179,5 +242,5 @@ export function createChatSessionManager({
markTransportDirty()
}
- return { ensureChat, resetChat, markTransportDirty, setOverrideTransport }
+ return { ensureChat, resetChat, markTransportDirty, setOverrideTransport, failure, clearFailure }
}
diff --git a/src/app/ai/chat/use.ts b/src/app/ai/chat/use.ts
index c0b2ea867..86cd621a0 100644
--- a/src/app/ai/chat/use.ts
+++ b/src/app/ai/chat/use.ts
@@ -67,6 +67,8 @@ export function useAIChat() {
activeTab,
isConfigured,
ensureChat: chatSession.ensureChat,
- resetChat: chatSession.resetChat
+ resetChat: chatSession.resetChat,
+ chatFailure: chatSession.failure,
+ clearChatFailure: chatSession.clearFailure
}
}
diff --git a/src/app/ai/debug/index.ts b/src/app/ai/debug/index.ts
index e0883805f..a1c7932f7 100644
--- a/src/app/ai/debug/index.ts
+++ b/src/app/ai/debug/index.ts
@@ -4,6 +4,7 @@ import { buildDebugLog } from '@open-pencil/core/tools'
import type { ToolDebugLog, ToolLogEntry } from '@open-pencil/core/tools'
import type { JSONObject } from '@open-pencil/scene-graph/primitives'
+import type { AIChatFailure } from '@/app/ai/chat/failure'
import { getStepUsages, getToolLogEntries } from '@/app/ai/tools'
export function formatTokenUsage(): string {
@@ -205,7 +206,7 @@ function formatMessageStats(messages: UIMessage[]): string {
return lines.join('\n')
}
-export function serializeChatLog(messages: UIMessage[]): string {
+export function serializeChatLog(messages: UIMessage[], failure?: AIChatFailure | null): string {
const sections: string[] = []
const toolLog = getToolLogEntries()
@@ -225,6 +226,14 @@ export function serializeChatLog(messages: UIMessage[]): string {
sections.push(formatDiagnostics(debugLog))
sections.push('')
+ sections.push('=== ERRORS ===')
+ if (failure) {
+ sections.push(` ${failure.reason}${failure.detail ? `: ${failure.detail}` : ''}`)
+ } else {
+ sections.push(' (none recorded)')
+ }
+ sections.push('')
+
sections.push('=== MESSAGE STATS ===')
sections.push(formatMessageStats(messages))
sections.push('')
@@ -270,7 +279,7 @@ export function serializeChatLog(messages: UIMessage[]): string {
return sections.join('\n\n')
}
-export function copyChatLog(messages: UIMessage[]): Promise<void> {
- const text = serializeChatLog(messages)
+export function copyChatLog(messages: UIMessage[], failure?: AIChatFailure | null): Promise<void> {
+ const text = serializeChatLog(messages, failure)
return navigator.clipboard.writeText(text)
}
diff --git a/src/app/ai/models/store.ts b/src/app/ai/models/store.ts
index f5f21396f..30583c085 100644
--- a/src/app/ai/models/store.ts
+++ b/src/app/ai/models/store.ts
@@ -87,6 +87,7 @@ function parseProfile(value: unknown, connectionIds: Set<string>): AIModelProfil
modelID: stringValue(value.modelID),
customModelID: stringValue(value.customModelID),
maxOutputTokens: normalizedMaxOutputTokens(value.maxOutputTokens),
+ reasoningEffort: stringValue(value.reasoningEffort).trim() || undefined,
capabilities: [...new Set(capabilities)]
}
}
@@ -277,6 +278,7 @@ function draftForProfile(
customBaseURL: connection.customBaseURL,
customAPIType: connection.customAPIType,
maxOutputTokens: profile.maxOutputTokens,
+ reasoningEffort: profile.reasoningEffort ?? '',
capabilities: [...profile.capabilities]
}
}
@@ -294,6 +296,7 @@ function newProfileDraft(connection: AIModelConnection | null): AIModelProfileDr
customBaseURL: connection?.customBaseURL ?? '',
customAPIType: connection?.customAPIType ?? 'completions',
maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
+ reasoningEffort: '',
capabilities: ['tools']
}
}
@@ -327,6 +330,7 @@ export function saveModelProfileDraft(draft: AIModelProfileDraft): AIModelProfil
modelID: draft.modelID.trim() || provider?.defaultModel || '',
customModelID: draft.customModelID.trim(),
maxOutputTokens: normalizedMaxOutputTokens(draft.maxOutputTokens),
+ reasoningEffort: draft.reasoningEffort.trim() || undefined,
capabilities: [...new Set(draft.capabilities)]
}
const index = aiModelSettings.value.models.findIndex((model) => model.id === profile.id)
diff --git a/src/app/ai/models/types.ts b/src/app/ai/models/types.ts
index 3c6cc3589..3f6b7e2cf 100644
--- a/src/app/ai/models/types.ts
+++ b/src/app/ai/models/types.ts
@@ -24,6 +24,7 @@ export type AIModelProfile = {
modelID: string
customModelID: string
maxOutputTokens: number
+ reasoningEffort?: string
capabilities: AIModelCapability[]
}
@@ -51,6 +52,7 @@ export type AIModelProfileDraft = {
customBaseURL: string
customAPIType: 'completions' | 'responses'
maxOutputTokens: number
+ reasoningEffort: string
capabilities: AIModelCapability[]
}
diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vue
index 851d90aeb..9b8622ba3 100644
--- a/src/components/ChatPanel.vue
+++ b/src/components/ChatPanel.vue
@@ -23,7 +23,7 @@ import type { JSONObject } from '@open-pencil/scene-graph/primitives'
const IS_DEV = import.meta.env.DEV
-const { isConfigured, ensureChat, resetChat } = useAIChat()
+const { isConfigured, ensureChat, resetChat, chatFailure, clearChatFailure } = useAIChat()
const { copy } = useClipboard()
const { dialogs } = useI18n()
@@ -42,6 +42,18 @@ const debugCopied = refAutoReset(false, 1500)
const acpLogCopied = refAutoReset(false, 1500)
const messages = computed(() => chat.value?.messages ?? [])
+const failureMessage = computed(() => {
+ switch (chatFailure.value?.reason) {
+ case 'insufficient-credit':
+ return dialogs.value.chatInsufficientCredit
+ case 'output-limit':
+ return dialogs.value.chatOutputLimit
+ case 'request-failed':
+ return dialogs.value.chatRequestFailed
+ default:
+ return null
+ }
+})
const status = computed(() => chat.value?.status ?? 'ready')
const isThinking = computed(() => {
const s = status.value
@@ -72,12 +84,9 @@ function scrollToBottom() {
}
watch(messages, scrollToBottom, { deep: true })
-watch(
- () => chat.value?.error,
- (error) => {
- if (error) toast.error(error.message)
- }
-)
+watch(failureMessage, (message) => {
+ if (message) toast.error(message)
+})
watch(
() => activeTab.value?.id,
async () => {
@@ -88,6 +97,7 @@ watch(
async function handleSubmit(text: string) {
if (status.value === 'streaming' || status.value === 'submitted') return
+ clearChatFailure()
try {
const c = await ensureChat()
if (c) chat.value = markRaw(c)
@@ -107,7 +117,7 @@ function handleStop() {
}
async function handleCopyDebug() {
- await copyChatLog(messages.value)
+ await copyChatLog(messages.value, chatFailure.value)
debugCopied.value = true
}
@@ -119,6 +129,7 @@ async function handleCopyACPLog() {
}
function handleClearChat() {
+ clearChatFailure()
chat.value = null
resetChat()
clearToolLogEntries()
diff --git a/src/components/chat/ProviderConnectionTestButton.vue b/src/components/chat/ProviderConnectionTestButton.vue
index 79d073b8a..698403be5 100644
--- a/src/components/chat/ProviderConnectionTestButton.vue
+++ b/src/components/chat/ProviderConnectionTestButton.vue
@@ -32,6 +32,8 @@ const resultMessage = computed(() => {
return dialogs.value.connectionTestInvalidBaseURL
case 'auth':
return dialogs.value.connectionTestAuthFailed
+ case 'insufficient-credit':
+ return dialogs.value.connectionTestInsufficientCredit
case 'model-not-found':
return dialogs.value.connectionTestModelNotFound
case 'api-type':
diff --git a/src/components/settings/models/ProfileEditor.vue b/src/components/settings/models/ProfileEditor.vue
index ba0b9d008..866266b9a 100644
--- a/src/components/settings/models/ProfileEditor.vue
+++ b/src/components/settings/models/ProfileEditor.vue
@@ -430,6 +430,15 @@ void refreshKeyStatus()
</div>
</div>
+ <ProviderSettingsField :label="dialogs.reasoningEffort">
+ <ProviderSettingsInput
+ v-model="draft.reasoningEffort"
+ :aria-label="dialogs.reasoningEffort"
+ :placeholder="dialogs.reasoningEffortPlaceholder"
+ />
+ <p class="mt-1 text-[10px] text-muted">{{ dialogs.reasoningEffortDescription }}</p>
+ </ProviderSettingsField>
+
<div class="border-t border-border pt-2.5">
<p class="text-[11px] font-medium text-surface">{{ dialogs.outputLimit }}</p>
<p class="mt-0.5 text-[10px] text-muted">
diff --git a/tests/engine/app/ai/debug-log.test.ts b/tests/engine/app/ai/debug-log.test.ts
new file mode 100644
index 000000000..76f436927
--- /dev/null
+++ b/tests/engine/app/ai/debug-log.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { UIMessage } from 'ai'
+
+import { serializeChatLog } from '@/app/ai/debug'
+import { setActiveEditorStore } from '@/app/editor/active-store'
+import { createEditorStore } from '@/app/editor/session'
+
+const messages: UIMessage[] = [
+ { id: 'user-1', role: 'user', parts: [{ type: 'text', text: 'Create a card' }] }
+]
+
+describe('AI debug log', () => {
+ setActiveEditorStore(createEditorStore())
+
+ test('records request-level failures', () => {
+ const log = serializeChatLog(messages, {
+ reason: 'insufficient-credit',
+ detail: '402 Payment Required'
+ })
+
+ expect(log).toContain('=== ERRORS ===')
+ expect(log).toContain('insufficient-credit: 402 Payment Required')
+ })
+
+ test('reports when no request failure was recorded', () => {
+ expect(serializeChatLog(messages)).toContain('=== ERRORS ===\n\n (none recorded)')
+ })
+})
diff --git a/tests/engine/app/ai/failure.test.ts b/tests/engine/app/ai/failure.test.ts
new file mode 100644
index 000000000..df372f0d3
--- /dev/null
+++ b/tests/engine/app/ai/failure.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ classifyAIChatError,
+ classifyAIChatFinish,
+ isInsufficientCreditError
+} from '@/app/ai/chat/failure'
+
+describe('AI chat failures', () => {
+ test('recognizes provider credit and quota failures', () => {
+ expect(isInsufficientCreditError({ statusCode: 402 })).toBe(true)
+ expect(isInsufficientCreditError(new Error('Insufficient balance. Please top up.'))).toBe(true)
+ expect(isInsufficientCreditError(new Error('Quota exceeded for this account'))).toBe(true)
+ expect(isInsufficientCreditError(new Error('Rate limit reached'))).toBe(false)
+ })
+
+ test('classifies output-limit finishes', () => {
+ expect(classifyAIChatFinish('length')).toEqual({ reason: 'output-limit' })
+ expect(classifyAIChatFinish('stop')).toBeNull()
+ })
+
+ test('retains request details for diagnostics', () => {
+ expect(classifyAIChatError(new Error('Payment required'))).toEqual({
+ reason: 'insufficient-credit',
+ detail: 'Payment required'
+ })
+ expect(classifyAIChatError(new Error('Provider unavailable'))).toEqual({
+ reason: 'request-failed',
+ detail: 'Provider unavailable'
+ })
+ })
+})
diff --git a/tests/engine/app/ai/model-roles.test.ts b/tests/engine/app/ai/model-roles.test.ts
index 02f4b52ae..c2263f59d 100644
--- a/tests/engine/app/ai/model-roles.test.ts
+++ b/tests/engine/app/ai/model-roles.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+import { buildReasoningProviderOptions } from '@/app/ai/chat/transports'
import {
aiModelSettings,
createAIModelRuntime,
@@ -177,6 +178,24 @@ describe('AI model profiles and role assignments', () => {
expect(saveModelProfileDraft(draft).maxOutputTokens).toBe(16_384)
})
+ test('persists provider-specific reasoning effort', () => {
+ const draft = createModelProfileDraft('model-fast')
+ draft.reasoningEffort = 'none'
+ expect(saveModelProfileDraft(draft).reasoningEffort).toBe('none')
+ expect(createModelProfileDraft('model-fast').reasoningEffort).toBe('none')
+ })
+
+ test('maps reasoning effort to supported provider options', () => {
+ expect(buildReasoningProviderOptions('openai-compatible', 'none')).toEqual({
+ openai: { reasoningEffort: 'none' }
+ })
+ expect(buildReasoningProviderOptions('openrouter', 'high')).toEqual({
+ openrouter: { reasoning: { effort: 'high' } }
+ })
+ expect(buildReasoningProviderOptions('google', 'high')).toBeUndefined()
+ expect(buildReasoningProviderOptions('openai', '')).toBeUndefined()
+ })
+
test('repairs assignments when removing a model', () => {
removeModelProfile('model-design')
const settings = modelSettingsSnapshot()