AI-native design editor. Open-source Figma alternative.
feat(ai): choose a thinking level per message (#809)
Danila Poyarkov0ff6b414e37f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4353b1dd3..7c7307dd3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@### Added- Jump between pages from the command palette: it lists the pages you visited recently in the tab, **Go to page…** lists every page, and typing a page name finds it.+- Choose how much an AI model thinks for each message from the chat composer, from Off to Extra high or the provider default. Anthropic, Google, DeepSeek, OpenAI, OpenRouter, and compatible models apply it, where reasoning effort previously reached only OpenAI and OpenRouter models. A model profile's thinking level, which replaces its free-text reasoning effort, sets the starting choice, and finished reasoning shows how long the model thought.- Preview designs progressively on the canvas as direct AI providers stream JSX, without saving partial designs or adding intermediate undo steps. A preview stays with its page: it hides while you view another page and returns when you come back.- Write design trees as TSX with `@open-pencil/design-jsx` as the JSX import source, and render them with `renderTree`.- Swap the component behind an instance with `instance.swapComponent(component)` in the plugin API, as in Figma.diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex c0af50f9f..ad6d48337 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -28,6 +28,7 @@"removeNodeContext": "Knoten aus dem Kontext entfernen","thinking": "Denkt nach…","reasoning": "Überlegungen",+ "thoughtFor": "Nachgedacht: {seconds} s","copyResponse": "Antwort kopieren","responseCopied": "Antwort kopiert","toolFinished": "Fertig",@@ -57,13 +58,15 @@"selectDesignModel": "Designmodell auswählen","modelNeedsCredential": "Schlüssel fehlt","modelAgentConnection": "Agent",- "harnessThinkingLevel": "Denkstufe",- "harnessThinkingOff": "Aus",- "harnessThinkingMinimal": "Minimal",- "harnessThinkingLow": "Niedrig",- "harnessThinkingMedium": "Mittel",- "harnessThinkingHigh": "Hoch",- "harnessThinkingExtraHigh": "Sehr hoch",+ "thinkingLevel": "Denkstufe",+ "thinkingLevelDescription": "Wie viel das Modell vor der Antwort nachdenkt. Im Chat lässt sich die Stufe für jede Nachricht ändern.",+ "thinkingDefault": "Standard",+ "thinkingOff": "Aus",+ "thinkingMinimal": "Minimal",+ "thinkingLow": "Niedrig",+ "thinkingMedium": "Mittel",+ "thinkingHigh": "Hoch",+ "thinkingExtraHigh": "Sehr hoch","harnessToolPermissions": "Tool-Berechtigungen","harnessPermissionReads": "Vor Änderungen und Befehlen fragen","harnessPermissionEdits": "Vor Befehlen fragen",@@ -94,9 +97,6 @@"advancedModelSettings": "Erweiterte Einstellungen","outputLimit": "Ausgabelimit","outputLimitAutomatic": "Automatische Empfehlung",- "reasoningEffort": "Schlussfolgerungsaufwand",- "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.",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex 016186e8b..e39348fe5 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -28,6 +28,7 @@"removeNodeContext": "Quitar nodo del contexto","thinking": "Pensando…","reasoning": "Razonamiento",+ "thoughtFor": "Razonó durante {seconds} s","copyResponse": "Copiar respuesta","responseCopied": "Respuesta copiada","toolFinished": "Hecho",@@ -57,13 +58,15 @@"selectDesignModel": "Seleccionar modelo de diseño","modelNeedsCredential": "Falta la clave","modelAgentConnection": "Agente",- "harnessThinkingLevel": "Nivel de razonamiento",- "harnessThinkingOff": "Desactivado",- "harnessThinkingMinimal": "Mínimo",- "harnessThinkingLow": "Bajo",- "harnessThinkingMedium": "Medio",- "harnessThinkingHigh": "Alto",- "harnessThinkingExtraHigh": "Muy alto",+ "thinkingLevel": "Nivel de razonamiento",+ "thinkingLevelDescription": "Cuánto razona el modelo antes de responder. Puedes cambiarlo para cada mensaje en el chat.",+ "thinkingDefault": "Predeterminado",+ "thinkingOff": "Desactivado",+ "thinkingMinimal": "Mínimo",+ "thinkingLow": "Bajo",+ "thinkingMedium": "Medio",+ "thinkingHigh": "Alto",+ "thinkingExtraHigh": "Muy alto","harnessToolPermissions": "Permisos de herramientas","harnessPermissionReads": "Preguntar antes de editar y ejecutar comandos","harnessPermissionEdits": "Preguntar antes de ejecutar comandos",@@ -100,9 +103,6 @@"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.","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.",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex 77fe36076..bd8942c55 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -28,6 +28,7 @@"removeNodeContext": "Retirer le nœud du contexte","thinking": "Réflexion…","reasoning": "Raisonnement",+ "thoughtFor": "Réflexion : {seconds} s","copyResponse": "Copier la réponse","responseCopied": "Réponse copiée","toolFinished": "Terminé",@@ -57,13 +58,15 @@"selectDesignModel": "Sélectionner le modèle de conception","modelNeedsCredential": "Clé requise","modelAgentConnection": "Agent",- "harnessThinkingLevel": "Niveau de réflexion",- "harnessThinkingOff": "Désactivé",- "harnessThinkingMinimal": "Minimal",- "harnessThinkingLow": "Faible",- "harnessThinkingMedium": "Moyen",- "harnessThinkingHigh": "Élevé",- "harnessThinkingExtraHigh": "Très élevé",+ "thinkingLevel": "Niveau de réflexion",+ "thinkingLevelDescription": "Quantité de réflexion du modèle avant de répondre. Vous pouvez la modifier pour chaque message dans le chat.",+ "thinkingDefault": "Par défaut",+ "thinkingOff": "Désactivé",+ "thinkingMinimal": "Minimal",+ "thinkingLow": "Faible",+ "thinkingMedium": "Moyen",+ "thinkingHigh": "Élevé",+ "thinkingExtraHigh": "Très élevé","harnessToolPermissions": "Autorisations des outils","harnessPermissionReads": "Demander avant les modifications et les commandes","harnessPermissionEdits": "Demander avant les commandes",@@ -94,9 +97,6 @@"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.","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.",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex 810cc1a6e..c30a09fb7 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -28,6 +28,7 @@"removeNodeContext": "Rimuovi nodo dal contesto","thinking": "Elaborazione…","reasoning": "Ragionamento",+ "thoughtFor": "Ragionato per {seconds} s","copyResponse": "Copia risposta","responseCopied": "Risposta copiata","toolFinished": "Fine",@@ -57,13 +58,15 @@"selectDesignModel": "Seleziona modello di progettazione","modelNeedsCredential": "Chiave necessaria","modelAgentConnection": "Agente",- "harnessThinkingLevel": "Livello di ragionamento",- "harnessThinkingOff": "Disattivato",- "harnessThinkingMinimal": "Minimo",- "harnessThinkingLow": "Basso",- "harnessThinkingMedium": "Medio",- "harnessThinkingHigh": "Alto",- "harnessThinkingExtraHigh": "Molto alto",+ "thinkingLevel": "Livello di ragionamento",+ "thinkingLevelDescription": "Quanto ragiona il modello prima di rispondere. Puoi cambiarlo per ogni messaggio nella chat.",+ "thinkingDefault": "Predefinito",+ "thinkingOff": "Disattivato",+ "thinkingMinimal": "Minimo",+ "thinkingLow": "Basso",+ "thinkingMedium": "Medio",+ "thinkingHigh": "Alto",+ "thinkingExtraHigh": "Molto alto","harnessToolPermissions": "Autorizzazioni degli strumenti","harnessPermissionReads": "Chiedi prima di modifiche e comandi","harnessPermissionEdits": "Chiedi prima dei comandi",@@ -100,9 +103,6 @@"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.","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.",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex c74f974a8..5d103ff4a 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -28,6 +28,7 @@"removeNodeContext": "コンテキストからノードを削除","thinking": "思考中…","reasoning": "推論",+ "thoughtFor": "{seconds}秒間思考","copyResponse": "回答をコピー","responseCopied": "回答をコピーしました","toolFinished": "完了",@@ -57,13 +58,15 @@"selectDesignModel": "デザインモデルを選択","modelNeedsCredential": "キーが必要","modelAgentConnection": "エージェント",- "harnessThinkingLevel": "思考レベル",- "harnessThinkingOff": "オフ",- "harnessThinkingMinimal": "最小",- "harnessThinkingLow": "低",- "harnessThinkingMedium": "中",- "harnessThinkingHigh": "高",- "harnessThinkingExtraHigh": "最高",+ "thinkingLevel": "思考レベル",+ "thinkingLevelDescription": "回答前にモデルが推論する量です。チャットでメッセージごとに変更できます。",+ "thinkingDefault": "既定",+ "thinkingOff": "オフ",+ "thinkingMinimal": "最小",+ "thinkingLow": "低",+ "thinkingMedium": "中",+ "thinkingHigh": "高",+ "thinkingExtraHigh": "最高","harnessToolPermissions": "ツール権限","harnessPermissionReads": "編集とコマンドの前に確認","harnessPermissionEdits": "コマンドの前に確認",@@ -100,9 +103,6 @@"advancedModelSettings": "詳細設定","outputLimit": "出力上限","outputLimitAutomatic": "自動推奨値",- "reasoningEffort": "推論の強度",- "reasoningEffortPlaceholder": "例: low, high, none",- "reasoningEffortDescription": "プロバイダー固有の任意の値です。","maxOutputTokens": "最大出力トークン数","chatAuthenticationFailed": "プロバイダーのAPIキーが無効か期限切れです。設定で置き換えてください。","chatForbidden": "このAPIキーでは選択したモデルを使用できません。モデルへのアクセス権を確認してください。",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex ff6d44aee..efd73a76a 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -28,6 +28,7 @@"removeNodeContext": "Usuń węzeł z kontekstu","thinking": "Myślenie…","reasoning": "Rozumowanie",+ "thoughtFor": "Rozumowanie: {seconds} s","copyResponse": "Kopiuj odpowiedź","responseCopied": "Skopiowano odpowiedź","toolFinished": "Gotowe",@@ -57,13 +58,15 @@"selectDesignModel": "Wybierz model projektowy","modelNeedsCredential": "Brak klucza","modelAgentConnection": "Agent",- "harnessThinkingLevel": "Poziom rozumowania",- "harnessThinkingOff": "Wyłączony",- "harnessThinkingMinimal": "Minimalny",- "harnessThinkingLow": "Niski",- "harnessThinkingMedium": "Średni",- "harnessThinkingHigh": "Wysoki",- "harnessThinkingExtraHigh": "Bardzo wysoki",+ "thinkingLevel": "Poziom rozumowania",+ "thinkingLevelDescription": "Ile model rozumuje przed odpowiedzią. Możesz to zmienić dla każdej wiadomości na czacie.",+ "thinkingDefault": "Domyślny",+ "thinkingOff": "Wyłączony",+ "thinkingMinimal": "Minimalny",+ "thinkingLow": "Niski",+ "thinkingMedium": "Średni",+ "thinkingHigh": "Wysoki",+ "thinkingExtraHigh": "Bardzo wysoki","harnessToolPermissions": "Uprawnienia narzędzi","harnessPermissionReads": "Pytaj przed zmianami i poleceniami","harnessPermissionEdits": "Pytaj przed poleceniami",@@ -94,9 +97,6 @@"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.","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.",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex bffbab8b9..1e233b35e 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -28,6 +28,7 @@"removeNodeContext": "Удалить узел из контекста","thinking": "Размышляет…","reasoning": "Рассуждение",+ "thoughtFor": "Рассуждал {seconds} с","copyResponse": "Копировать ответ","responseCopied": "Ответ скопирован","toolFinished": "Готово",@@ -57,13 +58,15 @@"selectDesignModel": "Выбрать модель для дизайна","modelNeedsCredential": "Нужен ключ","modelAgentConnection": "Агент",- "harnessThinkingLevel": "Уровень рассуждений",- "harnessThinkingOff": "Выключен",- "harnessThinkingMinimal": "Минимальный",- "harnessThinkingLow": "Низкий",- "harnessThinkingMedium": "Средний",- "harnessThinkingHigh": "Высокий",- "harnessThinkingExtraHigh": "Очень высокий",+ "thinkingLevel": "Уровень рассуждений",+ "thinkingLevelDescription": "Насколько глубоко модель рассуждает перед ответом. В чате уровень можно менять для каждого сообщения.",+ "thinkingDefault": "По умолчанию",+ "thinkingOff": "Выключен",+ "thinkingMinimal": "Минимальный",+ "thinkingLow": "Низкий",+ "thinkingMedium": "Средний",+ "thinkingHigh": "Высокий",+ "thinkingExtraHigh": "Очень высокий","harnessToolPermissions": "Разрешения инструментов","harnessPermissionReads": "Спрашивать перед изменениями и командами","harnessPermissionEdits": "Спрашивать перед командами",@@ -94,9 +97,6 @@"advancedModelSettings": "Расширенные настройки","outputLimit": "Лимит вывода","outputLimitAutomatic": "Автоматическая рекомендация",- "reasoningEffort": "Глубина рассуждения",- "reasoningEffortPlaceholder": "например, low, high, none",- "reasoningEffortDescription": "Необязательное значение, зависящее от провайдера.","maxOutputTokens": "Максимум выходных токенов","chatAuthenticationFailed": "API-ключ провайдера недействителен или истёк. Замените его в настройках.","chatForbidden": "Этот API-ключ не может использовать выбранную модель. Проверьте доступ к модели.",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex 4bf625263..1bc67eb74 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -28,6 +28,7 @@"removeNodeContext": "从上下文中移除节点","thinking": "思考中…","reasoning": "推理",+ "thoughtFor": "思考了 {seconds} 秒","copyResponse": "复制回答","responseCopied": "已复制回答","toolFinished": "完成",@@ -57,13 +58,15 @@"selectDesignModel": "选择设计模型","modelNeedsCredential": "需要密钥","modelAgentConnection": "代理",- "harnessThinkingLevel": "思考级别",- "harnessThinkingOff": "关闭",- "harnessThinkingMinimal": "最低",- "harnessThinkingLow": "低",- "harnessThinkingMedium": "中",- "harnessThinkingHigh": "高",- "harnessThinkingExtraHigh": "极高",+ "thinkingLevel": "思考级别",+ "thinkingLevelDescription": "模型在回答前进行推理的程度。可以在聊天中为每条消息单独更改。",+ "thinkingDefault": "默认",+ "thinkingOff": "关闭",+ "thinkingMinimal": "最低",+ "thinkingLow": "低",+ "thinkingMedium": "中",+ "thinkingHigh": "高",+ "thinkingExtraHigh": "极高","harnessToolPermissions": "工具权限","harnessPermissionReads": "编辑和执行命令前询问","harnessPermissionEdits": "执行命令前询问",@@ -100,9 +103,6 @@"advancedModelSettings": "高级设置","outputLimit": "输出限制","outputLimitAutomatic": "自动建议",- "reasoningEffort": "推理强度",- "reasoningEffortPlaceholder": "例如 low、high、none",- "reasoningEffortDescription": "可选的提供商特定值。","maxOutputTokens": "最大输出词元数","chatAuthenticationFailed": "提供商API密钥无效或已过期。请在设置中替换。","chatForbidden": "此API密钥无法使用所选模型。请检查模型访问权限。",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex 38ce13161..0bef4ccbf 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -70,6 +70,7 @@ export const aiMessageDefaults = {removeNodeContext: 'Remove node from context',thinking: 'Thinking…',reasoning: 'Reasoning',+ thoughtFor: params('Thought for {seconds}s'),copyResponse: 'Copy response',responseCopied: 'Response copied',toolFinished: 'Done',@@ -101,13 +102,16 @@ export const aiMessageDefaults = {selectDesignModel: 'Select design model',modelNeedsCredential: 'Needs key',modelAgentConnection: 'Agent',- harnessThinkingLevel: 'Thinking level',- harnessThinkingOff: 'Off',- harnessThinkingMinimal: 'Minimal',- harnessThinkingLow: 'Low',- harnessThinkingMedium: 'Medium',- harnessThinkingHigh: 'High',- harnessThinkingExtraHigh: 'Extra high',+ thinkingLevel: 'Thinking level',+ thinkingLevelDescription:+ 'How much the model reasons before answering. You can change it for each message in the chat.',+ thinkingDefault: 'Default',+ thinkingOff: 'Off',+ thinkingMinimal: 'Minimal',+ thinkingLow: 'Low',+ thinkingMedium: 'Medium',+ thinkingHigh: 'High',+ thinkingExtraHigh: 'Extra high',harnessToolPermissions: 'Tool permissions',harnessPermissionReads: 'Ask before edits and commands',harnessPermissionEdits: 'Ask before commands',@@ -144,9 +148,6 @@ export const aiMessageDefaults = {advancedModelSettings: 'Advanced settings',outputLimit: 'Output limit',outputLimitAutomatic: 'Automatic recommendation',- reasoningEffort: 'Reasoning effort',- 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.',diff --git a/src/app/ai/attachment/image/analyze.ts b/src/app/ai/attachment/image/analyze.tsindex 500d2e6a5..8397de67c 100644--- a/src/app/ai/attachment/image/analyze.ts+++ b/src/app/ai/attachment/image/analyze.ts@@ -4,7 +4,7 @@ import { computeContentBounds } from '@open-pencil/core/io'import { IMAGE_ATTACHMENT_MAX_EDGE } from '@/app/ai/attachment/image/prepare'import type { PreparedImageAttachment } from '@/app/ai/attachment/image/types'-import { buildReasoningProviderOptions } from '@/app/ai/chat/reasoning'+import { reasoningCallSettings } from '@/app/ai/chat/reasoning'import { createAIModelRuntime } from '@/app/ai/models'import { boundedImageScale } from '@/app/ai/tools/vision'import type { VisionModelDependencies } from '@/app/ai/vision-runtime'@@ -70,9 +70,9 @@ export async function analyzeAttachedImages(const result = await dependencies.inspect({model: runtime.model,maxOutputTokens: Math.min(runtime.role.profile.maxOutputTokens, MAX_IMAGE_ANALYSIS_TOKENS),- providerOptions: buildReasoningProviderOptions(+ ...reasoningCallSettings(runtime.role.connection.providerID,- runtime.role.profile.reasoningEffort ?? ''+ runtime.role.profile.thinkingLevel),messages: [{ role: 'user', content }]})diff --git a/src/app/ai/chat/reasoning.ts b/src/app/ai/chat/reasoning.tsindex ada3c38cf..c4e8d4244 100644--- a/src/app/ai/chat/reasoning.ts+++ b/src/app/ai/chat/reasoning.ts@@ -1,18 +1,29 @@+import type { LanguageModelCallOptions } from 'ai'+import type { AIProviderID } from '@open-pencil/core/constants'+import type { ThinkingLevel } from '@/app/ai/models/types'+type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue }export type AIProviderOptions = Record<string, { [key: string]: JSONValue }>-export function buildReasoningProviderOptions(+export type ReasoningCallSettings = {+ reasoning?: LanguageModelCallOptions['reasoning']+ providerOptions?: AIProviderOptions+}++/**+ * AI SDK providers map the standard `reasoning` level to their own thinking options.+ * OpenRouter's provider ignores it, so it receives the equivalent provider option.+ */+export function reasoningCallSettings(providerID: AIProviderID,- reasoningEffort: string-): AIProviderOptions | undefined {- if (!reasoningEffort) return undefined+ level: ThinkingLevel+): ReasoningCallSettings {+ if (level === 'default') return {}+ const reasoning = level === 'off' ? 'none' : levelif (providerID === 'openrouter') {- return { openrouter: { reasoning: { effort: reasoningEffort } } }- }- if (providerID === 'openai' || providerID === 'openai-compatible') {- return { openai: { reasoningEffort } }+ return { providerOptions: { openrouter: { reasoning: { effort: reasoning } } } }}- return undefined+ return { reasoning }}diff --git a/src/app/ai/chat/thinking.ts b/src/app/ai/chat/thinking.tsnew file mode 100644index 000000000..efe5d0e87--- /dev/null+++ b/src/app/ai/chat/thinking.ts@@ -0,0 +1,23 @@+import { computed, shallowRef } from 'vue'++import { designModelProfile } from '@/app/ai/models'+import type { AIModelProfileId, ThinkingLevel } from '@/app/ai/models/types'++/** The composer's choice applies to the Design profile it was made for; switching profiles drops it. */+const composerChoice = shallowRef<{+ profileId: AIModelProfileId | null+ level: ThinkingLevel+} | null>(null)++/** The level the next direct-model message uses. */+export const chatThinkingLevel = computed<ThinkingLevel>({+ get: () => {+ const profile = designModelProfile.value+ const choice = composerChoice.value+ if (choice?.profileId === (profile?.id ?? null)) return choice.level+ return profile?.thinkingLevel ?? 'default'+ },+ set: (level) => {+ composerChoice.value = { profileId: designModelProfile.value?.id ?? null, level }+ }+})diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.tsindex 11f2ea490..f454036d4 100644--- a/src/app/ai/chat/transports.ts+++ b/src/app/ai/chat/transports.ts@@ -15,9 +15,11 @@ import type { ACPAgentID, AIProviderID } from '@open-pencil/core/constants'import { classifyAIChatError, type AIChatFailure } from '@/app/ai/chat/failure'import { resolveLanguageModelID } from '@/app/ai/chat/model'-import { buildReasoningProviderOptions, type AIProviderOptions } from '@/app/ai/chat/reasoning'+import { reasoningCallSettings, type AIProviderOptions } from '@/app/ai/chat/reasoning'import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'+import { chatThinkingLevel } from '@/app/ai/chat/thinking'import { createAIModelRuntime, resolveModelConnectionAPIKey } from '@/app/ai/models'+import type { ThinkingLevel } from '@/app/ai/models/types'import { createCanvasJSXPreview } from '@/app/ai/preview/canvas'import { createAITools, recordStep, runPageId, startRun } from '@/app/ai/tools'import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'@@ -50,7 +52,8 @@ export type ToolLoopTransportOptions = {model: LanguageModeleffectiveModelID: stringmaxOutputTokens: number- reasoningEffort: string+ /** Read per request, so the composer's level applies to the next message. */+ thinkingLevel: () => ThinkingLevelonError?: (error: unknown) => voiddiagnosticContext?: AIDiagnosticContext}@@ -75,6 +78,15 @@ function mergeProviderOptions(return { ...cacheOptions, ...reasoningOptions }}+function callSettings(+ providerID: AIProviderID,+ cacheOptions: typeof ANTHROPIC_CACHE_CONTROL | undefined,+ thinkingLevel: ThinkingLevel+) {+ const { reasoning, providerOptions } = reasoningCallSettings(providerID, thinkingLevel)+ return { reasoning, providerOptions: mergeProviderOptions(cacheOptions, providerOptions) }+}+export async function createACPTransport(providerID: AIProviderID) {const agentId = providerID.replace('acp:', '') as ACPAgentIDconst agentDef = ACP_AGENTS.find((a) => a.id === agentId)@@ -91,7 +103,7 @@ export function createToolLoopTransport({model,effectiveModelID,maxOutputTokens,- reasoningEffort,+ thinkingLevel,onError,diagnosticContext = {}}: ToolLoopTransportOptions) {@@ -106,17 +118,11 @@ export function createToolLoopTransport({const cacheProviderOptions = supportsAnthropicCaching(providerID, effectiveModelID)? ANTHROPIC_CACHE_CONTROL: undefined- const providerOptions = mergeProviderOptions(- cacheProviderOptions,- buildReasoningProviderOptions(providerID, reasoningEffort)- )-const agent = new ToolLoopAgent({model,instructions: SYSTEM_PROMPT,tools,maxOutputTokens,- providerOptions,prepareCall: (options) => {const stepLimit = maxAgentSteps.valueconst enabledNames = new Set(@@ -130,7 +136,7 @@ export function createToolLoopTransport({// Keep the full catalog for validating history; offer only enabled tools to this request.tools: Object.fromEntries(Object.entries(tools).filter(([name]) => enabledNames.has(name))),maxOutputTokens,- providerOptions+ ...callSettings(providerID, cacheProviderOptions, thinkingLevel())}},onFinish: () => preview.clear(),@@ -261,7 +267,9 @@ export function createChatSessionManager({sandbox: 'just-bash',model,settings: {- thinkingLevel: runtime.role.profile.harnessThinkingLevel ?? 'medium',+ ...(runtime.role.profile.thinkingLevel !== 'default' && {+ thinkingLevel: runtime.role.profile.thinkingLevel+ }),permissionMode: runtime.role.profile.harnessPermissionMode ?? 'allow-edits'},instructions: SYSTEM_PROMPT,@@ -292,7 +300,7 @@ export function createChatSessionManager({customModelID: runtime.role.profile.customModelID}),maxOutputTokens: runtime.role.profile.maxOutputTokens,- reasoningEffort: runtime.role.profile.reasoningEffort ?? '',+ thinkingLevel: () => chatThinkingLevel.value,onError: captureProviderError,diagnosticContext})diff --git a/src/app/ai/models/settings/profile-editor/selection.ts b/src/app/ai/models/settings/profile-editor/selection.tsindex 9d44e5925..b0818a253 100644--- a/src/app/ai/models/settings/profile-editor/selection.ts+++ b/src/app/ai/models/settings/profile-editor/selection.ts@@ -11,6 +11,7 @@ import type { AIModelProfileDraft, AIModelCapability } from '@/app/ai/models'import { resolveModelsDevModel } from '@/app/ai/models/catalog'import { useProviderModelCatalog } from '@/app/ai/models/catalog/use'import { modelPickerOptions, type ModelPickerLabels } from '@/app/ai/models/picker/options'+import { supportsThinkingLevel } from '@/app/ai/models/thinking'export function useProfileModelSelection(draft: AIModelProfileDraft,@@ -31,9 +32,7 @@ export function useProfileModelSelection(const { models: availableModels } = useProviderModelCatalog(catalogProviderID, fallbackModels)const isACP = computed(() => draft.providerID.startsWith('acp:'))const isHarness = computed(() => draft.providerID === 'harness:pi')- const supportsReasoningEffort = computed(() =>- ['openai', 'openai-compatible', 'openrouter'].includes(draft.providerID)- )+ const supportsThinking = computed(() => supportsThinkingLevel(draft.providerID))const providerDisplayName = computed(() => {if (!isACP.value) return providerDef.value.name@@ -171,7 +170,7 @@ export function useProfileModelSelection(isACP,isHarness,customModelSelected,- supportsReasoningEffort,+ supportsThinking,providerDisplayName,modelOptions,selectedModelValue,diff --git a/src/app/ai/models/settings/profile-editor/use.ts b/src/app/ai/models/settings/profile-editor/use.tsindex 7c4c8b80f..688b2be8a 100644--- a/src/app/ai/models/settings/profile-editor/use.ts+++ b/src/app/ai/models/settings/profile-editor/use.ts@@ -35,7 +35,7 @@ export function useModelProfileEditor({ profileId, keyInput, labels: ai }: ProfiproviderDef,isACP,isHarness,- supportsReasoningEffort,+ supportsThinking,providerDisplayName,modelOptions,selectedModelValue,@@ -157,7 +157,7 @@ export function useModelProfileEditor({ profileId, keyInput, labels: ai }: ProfiproviderDef,isACP,isHarness,- supportsReasoningEffort,+ supportsThinking,providerDisplayName,modelOptions,selectedModelValue,diff --git a/src/app/ai/models/store.ts b/src/app/ai/models/store.tsindex e9ed71abe..544e713c7 100644--- a/src/app/ai/models/store.ts+++ b/src/app/ai/models/store.ts@@ -14,7 +14,7 @@ import {} from '@/app/ai/models/storage'import {HARNESS_PERMISSION_MODES,- HARNESS_THINKING_LEVELS,+ THINKING_LEVELS,type AIModelCapability,type AIModelConnection,type AIModelProfile,@@ -26,7 +26,7 @@ import {type OptionalAIModelRole,type ResolvedAIModelRole,type HarnessPermissionMode,- type HarnessThinkingLevel+ type ThinkingLevel} from '@/app/ai/models/types'const LEGACY_CONNECTION_ID = 'connection-default'@@ -48,10 +48,18 @@ function isAPIType(value: unknown): value is 'completions' | 'responses' {return value === 'completions' || value === 'responses'}-function isHarnessThinkingLevel(value: unknown): value is HarnessThinkingLevel {- return (- typeof value === 'string' && HARNESS_THINKING_LEVELS.includes(value as HarnessThinkingLevel)- )+function isThinkingLevel(value: unknown): value is ThinkingLevel {+ return typeof value === 'string' && THINKING_LEVELS.includes(value as ThinkingLevel)+}++/** Profiles saved before thinking levels kept a Pi level or a free-text provider effort. */+function parseThinkingLevel(value: Record<string, unknown>): ThinkingLevel {+ if (isThinkingLevel(value.thinkingLevel)) return value.thinkingLevel+ if (isThinkingLevel(value.harnessThinkingLevel)) return value.harnessThinkingLevel+ const effort = stringValue(value.reasoningEffort).trim().toLowerCase()+ if (effort === 'none') return 'off'+ if (effort === 'max') return 'xhigh'+ return isThinkingLevel(effort) ? effort : 'default'}function isHarnessPermissionMode(value: unknown): value is HarnessPermissionMode {@@ -103,10 +111,7 @@ function parseProfile(value: unknown, connectionIds: Set<string>): AIModelProfilmodelID: stringValue(value.modelID),customModelID: stringValue(value.customModelID),maxOutputTokens: normalizedMaxOutputTokens(value.maxOutputTokens),- reasoningEffort: stringValue(value.reasoningEffort).trim() || undefined,- harnessThinkingLevel: isHarnessThinkingLevel(value.harnessThinkingLevel)- ? value.harnessThinkingLevel- : undefined,+ thinkingLevel: parseThinkingLevel(value),harnessPermissionMode: isHarnessPermissionMode(value.harnessPermissionMode)? value.harnessPermissionMode: undefined,@@ -142,7 +147,8 @@ function hydrateCuratedCapabilities(}}-function parseSettings(value: unknown): AIModelSettings | null {+/** Normalizes persisted settings, migrating fields from earlier versions. */+export function parseAIModelSettings(value: unknown): AIModelSettings | null {if (!isRecord(value) || value.version !== 1) return nullconst connections = Array.isArray(value.connections)? value.connections.map(parseConnection).filter((connection) => connection !== null)@@ -214,6 +220,7 @@ function legacySettings(): AIModelSettings {maxOutputTokens: Number.isFinite(maxOutputTokens)? maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,+ thinkingLevel: 'default',capabilities: curatedCapabilities ?? ['tools']}],@@ -227,7 +234,7 @@ function legacySettings(): AIModelSettings {}function loadSettings(): AIModelSettings {- return parseSettings(readAIModelSettingsStorage()) ?? legacySettings()+ return parseAIModelSettings(readAIModelSettingsStorage()) ?? legacySettings()}export const aiModelSettings = ref<AIModelSettings>(loadSettings())@@ -331,8 +338,7 @@ function draftForProfile(customBaseURL: connection.customBaseURL,customAPIType: connection.customAPIType,maxOutputTokens: profile.maxOutputTokens,- reasoningEffort: profile.reasoningEffort ?? '',- harnessThinkingLevel: profile.harnessThinkingLevel ?? 'medium',+ thinkingLevel: profile.thinkingLevel,harnessPermissionMode: profile.harnessPermissionMode ?? 'allow-edits',capabilities: [...profile.capabilities]}@@ -351,8 +357,7 @@ function newProfileDraft(connection: AIModelConnection | null): AIModelProfileDrcustomBaseURL: connection?.customBaseURL ?? '',customAPIType: connection?.customAPIType ?? 'completions',maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,- reasoningEffort: '',- harnessThinkingLevel: 'medium',+ thinkingLevel: 'default',harnessPermissionMode: 'allow-edits',capabilities: ['tools']}@@ -387,9 +392,7 @@ export function saveModelProfileDraft(draft: AIModelProfileDraft): AIModelProfilmodelID: draft.modelID.trim() || provider?.defaultModel || '',customModelID: draft.customModelID.trim(),maxOutputTokens: normalizedMaxOutputTokens(draft.maxOutputTokens),- reasoningEffort: draft.reasoningEffort.trim() || undefined,- harnessThinkingLevel:- draft.providerID === 'harness:pi' ? draft.harnessThinkingLevel : undefined,+ thinkingLevel: draft.thinkingLevel,harnessPermissionMode:draft.providerID === 'harness:pi' ? draft.harnessPermissionMode : undefined,capabilities: [...new Set(draft.capabilities)]diff --git a/src/app/ai/models/thinking.ts b/src/app/ai/models/thinking.tsnew file mode 100644index 000000000..9ad1be11e--- /dev/null+++ b/src/app/ai/models/thinking.ts@@ -0,0 +1,26 @@+import { THINKING_LEVELS, type ThinkingLevel } from '@/app/ai/models/types'++const LABEL_KEYS = {+ default: 'thinkingDefault',+ off: 'thinkingOff',+ minimal: 'thinkingMinimal',+ low: 'thinkingLow',+ medium: 'thinkingMedium',+ high: 'thinkingHigh',+ xhigh: 'thinkingExtraHigh'+} as const satisfies Record<ThinkingLevel, string>++export type ThinkingLevelLabels = Record<(typeof LABEL_KEYS)[ThinkingLevel], string>++export function thinkingLevelLabel(level: ThinkingLevel, labels: ThinkingLevelLabels): string {+ return labels[LABEL_KEYS[level]]+}++export function thinkingLevelOptions(labels: ThinkingLevelLabels) {+ return THINKING_LEVELS.map((value) => ({ value, label: thinkingLevelLabel(value, labels) }))+}++/** ACP agents choose their own reasoning; API models and Pi accept a level. */+export function supportsThinkingLevel(providerID: string): boolean {+ return !providerID.startsWith('acp:')+}diff --git a/src/app/ai/models/types.ts b/src/app/ai/models/types.tsindex f5c0a3f19..2c13a83bb 100644--- a/src/app/ai/models/types.ts+++ b/src/app/ai/models/types.ts@@ -2,10 +2,19 @@ import type { AIProviderID } from '@open-pencil/core/constants'export const AI_MODEL_ROLES = ['design', 'review', 'fast', 'vision'] as constexport const AI_MODEL_CAPABILITIES = ['tools', 'vision'] as const-export const HARNESS_THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh'] as const+/** `default` leaves the effort to the provider; the rest follow the AI SDK reasoning levels. */+export const THINKING_LEVELS = [+ 'default',+ 'off',+ 'minimal',+ 'low',+ 'medium',+ 'high',+ 'xhigh'+] as constexport const HARNESS_PERMISSION_MODES = ['allow-reads', 'allow-edits', 'allow-all'] as const-export type HarnessThinkingLevel = (typeof HARNESS_THINKING_LEVELS)[number]+export type ThinkingLevel = (typeof THINKING_LEVELS)[number]export type HarnessPermissionMode = (typeof HARNESS_PERMISSION_MODES)[number]export type AIModelRole = (typeof AI_MODEL_ROLES)[number]@@ -29,8 +38,7 @@ export type AIModelProfile = {modelID: stringcustomModelID: stringmaxOutputTokens: number- reasoningEffort?: string- harnessThinkingLevel?: HarnessThinkingLevel+ thinkingLevel: ThinkingLevelharnessPermissionMode?: HarnessPermissionModecapabilities: AIModelCapability[]}@@ -59,8 +67,7 @@ export type AIModelProfileDraft = {customBaseURL: stringcustomAPIType: 'completions' | 'responses'maxOutputTokens: number- reasoningEffort: string- harnessThinkingLevel: HarnessThinkingLevel+ thinkingLevel: ThinkingLevelharnessPermissionMode: HarnessPermissionModecapabilities: AIModelCapability[]}diff --git a/src/app/ai/tools/vision.ts b/src/app/ai/tools/vision.tsindex 49d149e4b..e4a5bc93a 100644--- a/src/app/ai/tools/vision.ts+++ b/src/app/ai/tools/vision.ts@@ -4,7 +4,7 @@ import * as v from 'valibot'import { computeContentBounds } from '@open-pencil/core/io'-import { buildReasoningProviderOptions } from '@/app/ai/chat/reasoning'+import { reasoningCallSettings } from '@/app/ai/chat/reasoning'import { createAIModelRuntime } from '@/app/ai/models'import { runPageId } from '@/app/ai/tools/run'import type { VisionModelDependencies } from '@/app/ai/vision-runtime'@@ -72,9 +72,9 @@ export async function inspectRenderedDesign(const result = await dependencies.inspect({model: runtime.model,maxOutputTokens: Math.min(runtime.role.profile.maxOutputTokens, MAX_VISION_OUTPUT_TOKENS),- providerOptions: buildReasoningProviderOptions(+ ...reasoningCallSettings(runtime.role.connection.providerID,- runtime.role.profile.reasoningEffort ?? ''+ runtime.role.profile.thinkingLevel),messages: [{diff --git a/src/components/chat/ChatInput.vue b/src/components/chat/ChatInput.vueindex e4d9bb3be..68789a6b8 100644--- a/src/components/chat/ChatInput.vue+++ b/src/components/chat/ChatInput.vue@@ -11,6 +11,7 @@ import { designModelProfile } from '@/app/ai/models'import { openSettingsDialog } from '@/app/settings/dialog'import ChatNodePreview from '@/components/chat/ChatNodePreview.vue'import ChatProfileSelect from '@/components/chat/ChatProfileSelect.vue'+import ChatThinkingSelect from '@/components/chat/ChatThinkingSelect.vue'import { useAttachmentDrafts } from '@/components/chat/input/useAttachments'import IconButton from '@/components/ui/button/IconButton.vue'@@ -153,18 +154,21 @@ const selectedProfileName = computed(</IconButton></template><template #model>- <div class="flex min-w-0 items-center">+ <div class="@container flex min-w-0 items-center"><template v-if="isAgentProvider"><div class="flex min-w-0 items-center gap-1 px-1.5 text-[10px] text-muted"><icon-lucide-bot class="size-3 shrink-0" /><span class="truncate">{{ agentName }}</span></div></template>- <ChatProfileSelect v-else>- <template #value>- <span class="min-w-0 truncate">{{ selectedProfileName }}</span>- </template>- </ChatProfileSelect>+ <template v-else>+ <ChatProfileSelect>+ <template #value>+ <span class="min-w-0 truncate">{{ selectedProfileName }}</span>+ </template>+ </ChatProfileSelect>+ <ChatThinkingSelect />+ </template></div></template></ChatComposer>diff --git a/src/components/chat/ChatMessage.vue b/src/components/chat/ChatMessage.vueindex 95a2f6e76..18f694793 100644--- a/src/components/chat/ChatMessage.vue+++ b/src/components/chat/ChatMessage.vue@@ -101,6 +101,7 @@ function partKey(part: UIMessagePart<UIDataTypes, UITools>, index: number): stri:streaming="part.state === 'streaming'":thinking-label="ai.thinking":reasoning-label="ai.reasoning"+ :duration-label="(seconds) => ai.thoughtFor({ seconds })"/><!-- Tool call -->diff --git a/src/components/chat/ChatPlayground.stories.ts b/src/components/chat/ChatPlayground.stories.tsindex 71b79065d..93569e534 100644--- a/src/components/chat/ChatPlayground.stories.ts+++ b/src/components/chat/ChatPlayground.stories.ts@@ -7,6 +7,7 @@ import AppSelect from '@/components/ui/select/AppSelect.vue'import ChatComposer from './ChatComposer.vue'import ChatHistory from './ChatHistory.vue'+import ChatThinkingSelect from './ChatThinkingSelect.vue'import ChatTranscript from './ChatTranscript.vue'import { useConversations } from './stories/useConversations'@@ -29,6 +30,7 @@ const meta = {components: {ChatHistory,ChatComposer,+ ChatThinkingSelect,ChatTranscript,TooltipProvider,AppSelect,@@ -78,11 +80,15 @@ const meta = {@settings="showProfileNotice"><template #model>- <AppSelect- v-model="profile"- label="Mock model profile"- :options="profileOptions"- />+ <div class="@container flex min-w-0 items-center">+ <AppSelect+ v-model="profile"+ label="Mock model profile"+ :options="profileOptions"+ :ui="{ trigger: 'min-w-0 shrink' }"+ />+ <ChatThinkingSelect />+ </div></template></ChatComposer></section>diff --git a/src/components/chat/ChatThinkingSelect.vue b/src/components/chat/ChatThinkingSelect.vuenew file mode 100644index 000000000..f91176e3a--- /dev/null+++ b/src/components/chat/ChatThinkingSelect.vue@@ -0,0 +1,38 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { chatThinkingLevel } from '@/app/ai/chat/thinking'+import { thinkingLevelLabel, thinkingLevelOptions } from '@/app/ai/models/thinking'+import ThinkingMeter from '@/components/chat/ThinkingMeter.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'+import { chatProfileTheme } from '@/theme/chat/profile'+import { chatThinkingTheme } from '@/theme/chat/thinking'++const { ai } = useI18n()+const ui = chatProfileTheme()+const thinking = chatThinkingTheme()+const options = computed(() => thinkingLevelOptions(ai.value))+const selectedLabel = computed(() => thinkingLevelLabel(chatThinkingLevel.value, ai.value))+</script>++<template>+ <AppSelect+ v-model="chatThinkingLevel"+ :label="`${ai.thinkingLevel}: ${selectedLabel}`"+ :options="options"+ data-test-id="chat-thinking-selector"+ >+ <template #trigger>+ <button type="button" :class="ui.trigger({ class: thinking.trigger() })">+ <ThinkingMeter :level="chatThinkingLevel" />+ <span :class="thinking.label()">{{ selectedLabel }}</span>+ <icon-lucide-chevron-down :class="ui.triggerChevron()" aria-hidden="true" />+ </button>+ </template>+ <template #option-end="{ option }">+ <ThinkingMeter :level="option.value" :class="thinking.option()" />+ </template>+ </AppSelect>+</template>diff --git a/src/components/chat/ReasoningBlock.vue b/src/components/chat/ReasoningBlock.vueindex 905ad8b87..25ad04298 100644--- a/src/components/chat/ReasoningBlock.vue+++ b/src/components/chat/ReasoningBlock.vue@@ -12,18 +12,28 @@ const {text,streaming = false,thinkingLabel,- reasoningLabel+ reasoningLabel,+ durationLabel} = defineProps<{display?: ReasoningDisplaytext: stringstreaming?: booleanthinkingLabel: stringreasoningLabel: string+ /** Formats the duration measured while this block streamed; restored history has none. */+ durationLabel?: (seconds: number) => string}>()const open = ref(display === 'expanded' || (display === 'while-thinking' && streaming))const userChangedOpen = ref(false)const markdownMode = computed(() => (streaming ? 'streaming' : 'static'))+const startedAt = ref(streaming ? performance.now() : null)+const durationSeconds = ref<number | null>(null)+const finishedLabel = computed(() =>+ durationSeconds.value !== null && durationLabel+ ? durationLabel(durationSeconds.value)+ : reasoningLabel+)const { start: scheduleClose, stop: cancelClose } = useTimeoutFn(() => {if (display === 'while-thinking' && !streaming && !userChangedOpen.value) open.value = false@@ -35,6 +45,9 @@ const { start: scheduleClose, stop: cancelClose } = useTimeoutFn(watch(() => streaming,(isStreaming, wasStreaming) => {+ if (isStreaming) startedAt.value ??= performance.now()+ else if (wasStreaming && startedAt.value !== null)+ durationSeconds.value = Math.max(1, Math.round((performance.now() - startedAt.value) / 1000))cancelClose()if (userChangedOpen.value) returnif (isStreaming) {@@ -73,7 +86,7 @@ function updateOpen(value: boolean): void {class="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[11px] text-muted hover:bg-hover hover:text-surface"><icon-lucide-brain class="size-3.5 shrink-0 text-accent" aria-hidden="true" />- <span class="flex-1">{{ streaming ? thinkingLabel : reasoningLabel }}</span>+ <span class="flex-1">{{ streaming ? thinkingLabel : finishedLabel }}</span><icon-lucide-loader-circlev-if="streaming"class="size-3 animate-spin motion-reduce:animate-none"diff --git a/src/components/chat/ThinkingMeter.vue b/src/components/chat/ThinkingMeter.vuenew file mode 100644index 000000000..66581b7b0--- /dev/null+++ b/src/components/chat/ThinkingMeter.vue@@ -0,0 +1,34 @@+<script setup lang="ts">+import { computed } from 'vue'++import type { ThinkingLevel } from '@/app/ai/models/types'+import { chatThinkingTheme } from '@/theme/chat/thinking'++const { level } = defineProps<{ level: ThinkingLevel }>()+const ui = chatThinkingTheme()++/** Bars per level. The provider default fills every bar in grey: the provider decides. */+const FILLED: Record<ThinkingLevel, number> = {+ default: 5,+ off: 0,+ minimal: 1,+ low: 2,+ medium: 3,+ high: 4,+ xhigh: 5+}+const BAR_HEIGHTS = ['40%', '55%', '70%', '85%', '100%']+const filled = computed(() => FILLED[level])+</script>++<template>+ <span :class="ui.meter()" :data-level="level" aria-hidden="true" data-slot="thinking-meter">+ <span+ v-for="(height, index) in BAR_HEIGHTS"+ :key="height"+ :class="ui.bar()"+ :data-filled="index < filled"+ :style="{ height }"+ />+ </span>+</template>diff --git a/src/components/settings/models/ProfileEditor.vue b/src/components/settings/models/ProfileEditor.vueindex 939e16e91..69e4b34f6 100644--- a/src/components/settings/models/ProfileEditor.vue+++ b/src/components/settings/models/ProfileEditor.vue@@ -6,6 +6,7 @@ import { useI18n } from '@open-pencil/vue'import { useModelProfileFeedback } from '@/app/ai/models/settings/profile-editor/feedback'import { useModelProfileEditor } from '@/app/ai/models/settings/profile-editor/use'+import { thinkingLevelOptions as buildThinkingLevelOptions } from '@/app/ai/models/thinking'import { useSettingsFormGuard } from '@/app/settings/navigation/use'import ProviderConnectionTestButton from '@/components/chat/ProviderConnectionTestButton.vue'import { focusInvalidField } from '@/components/settings/layout/focus'@@ -37,7 +38,7 @@ const {providerDef,isACP,isHarness,- supportsReasoningEffort,+ supportsThinking,modelOptions,selectedModelValue,knownModel,@@ -58,6 +59,7 @@ const {const feedback = useModelProfileFeedback(profile, keyInput, settings)const { errors: fieldErrors } = feedbackconst busy = computed(() => saving.value || connectionTestStatus.value === 'testing')+const thinkingLevelOptions = computed(() => buildThinkingLevelOptions(ai.value))useSettingsFormGuard({ dirty, busy, cancel: () => emit('done') })const CUSTOM_MODEL_VALUE = '__custom__'const advancedOpen = ref(Boolean(draft.customModelID.trim()))@@ -276,19 +278,13 @@ async function remove() {</div></div>- <ProviderSettingsField v-if="isHarness" :label="ai.harnessThinkingLevel">+ <ProviderSettingsField v-if="supportsThinking" :label="ai.thinkingLevel"><AppSelect- v-model="draft.harnessThinkingLevel"- :label="ai.harnessThinkingLevel"- :options="[- { value: 'off', label: ai.harnessThinkingOff },- { value: 'minimal', label: ai.harnessThinkingMinimal },- { value: 'low', label: ai.harnessThinkingLow },- { value: 'medium', label: ai.harnessThinkingMedium },- { value: 'high', label: ai.harnessThinkingHigh },- { value: 'xhigh', label: ai.harnessThinkingExtraHigh }- ]"+ v-model="draft.thinkingLevel"+ :label="ai.thinkingLevel"+ :options="thinkingLevelOptions"/>+ <p class="mt-1 text-[10px] text-muted">{{ ai.thinkingLevelDescription }}</p></ProviderSettingsField><ProviderSettingsField v-if="isHarness" :label="ai.harnessToolPermissions">@@ -303,15 +299,6 @@ async function remove() {/></ProviderSettingsField>- <ProviderSettingsField v-if="supportsReasoningEffort" :label="ai.reasoningEffort">- <ProviderSettingsInput- v-model="draft.reasoningEffort"- :aria-label="ai.reasoningEffort"- :placeholder="ai.reasoningEffortPlaceholder"- />- <p class="mt-1 text-[10px] text-muted">{{ ai.reasoningEffortDescription }}</p>- </ProviderSettingsField>-<div class="border-t border-border pt-2.5"><p class="text-[11px] font-medium text-surface">{{ ai.outputLimit }}</p><p class="mt-0.5 text-[10px] text-muted">diff --git a/src/components/ui/select/AppSelect.vue b/src/components/ui/select/AppSelect.vueindex 0f3c4f773..a1f7b7dfd 100644--- a/src/components/ui/select/AppSelect.vue+++ b/src/components/ui/select/AppSelect.vue@@ -76,6 +76,7 @@ const selectedLabel = computed(<icon-lucide-check class="size-3 text-accent" /></SelectItemIndicator><SelectItemText>{{ opt.label }}</SelectItemText>+ <slot name="option-end" :option="opt" /></SelectItem></SelectViewport><SelectScrollDownButton class="flex items-center justify-center py-0.5 text-muted">diff --git a/src/theme/chat/thinking.ts b/src/theme/chat/thinking.tsnew file mode 100644index 000000000..435801b18--- /dev/null+++ b/src/theme/chat/thinking.ts@@ -0,0 +1,14 @@+import { tv } from 'tailwind-variants'++/** Bars fill with the level and shift from cool to warm as the model thinks harder. */+export const chatThinkingTheme = tv({+ slots: {+ meter:+ 'inline-flex h-3 shrink-0 items-end gap-px text-muted data-[level=high]:text-violet-400 data-[level=low]:text-sky-400 data-[level=medium]:text-accent data-[level=minimal]:text-sky-300 data-[level=xhigh]:text-fuchsia-400',+ bar: 'w-[3px] rounded-[1px] bg-current data-[filled=false]:bg-muted/30',+ trigger: 'flex shrink-0 items-center',+ /** Narrow composers show only the meter, leaving the width to the model name. */+ label: 'hidden truncate @[16rem]:inline',+ option: 'ml-auto pl-3'+ }+})diff --git a/tests/app/ai/chat/transports.test.ts b/tests/app/ai/chat/transports.test.tsnew file mode 100644index 000000000..40980d43d--- /dev/null+++ b/tests/app/ai/chat/transports.test.ts@@ -0,0 +1,96 @@+import 'fake-indexeddb/auto'+import { expect, test } from 'bun:test'++import { simulateReadableStream } from 'ai'+import { MockLanguageModelV4 } from 'ai/test'++import { createToolLoopTransport } from '@/app/ai/chat/transports'+import type { ThinkingLevel } from '@/app/ai/models/types'+import { createEditorStore } from '@/app/editor/session/create'++import { MOCK_USAGE } from '#tests/helpers/chat/usage'++function replyModel() {+ return new MockLanguageModelV4({+ doStream: async () => ({+ stream: simulateReadableStream({+ initialDelayInMs: null,+ chunkDelayInMs: null,+ chunks: [+ { type: 'text-start', id: 'reply' },+ { type: 'text-delta', id: 'reply', delta: 'Done' },+ { type: 'text-end', id: 'reply' },+ {+ type: 'finish',+ finishReason: { unified: 'stop', raw: undefined },+ usage: MOCK_USAGE+ }+ ]+ })+ })+ })+}++async function send(transport: ReturnType<typeof createToolLoopTransport>): Promise<void> {+ const stream = await transport.sendMessages({+ trigger: 'submit-message',+ chatId: 'thinking-level',+ messageId: undefined,+ messages: [{ id: 'user', role: 'user', parts: [{ type: 'text', text: 'Hello' }] }]+ })+ const reader = stream.getReader()+ try {+ while (!(await reader.read()).done);+ } finally {+ reader.releaseLock()+ }+}++test('each message uses the thinking level chosen when it is sent', async () => {+ const store = createEditorStore()+ const model = replyModel()+ let level: ThinkingLevel = 'high'+ try {+ const transport = createToolLoopTransport({+ store,+ providerID: 'anthropic',+ model,+ effectiveModelID: 'claude-test',+ maxOutputTokens: 100,+ thinkingLevel: () => level+ })+ await send(transport)+ level = 'off'+ await send(transport)+ level = 'default'+ await send(transport)+ expect(model.doStreamCalls.map((call) => call.reasoning)).toEqual(['high', 'none', undefined])+ // Prompt caching survives alongside the reasoning level.+ expect(model.doStreamCalls[0]?.providerOptions).toEqual({+ anthropic: { cacheControl: { type: 'ephemeral' } }+ })+ } finally {+ store.dispose()+ }+})++test('OpenRouter receives the level as its own reasoning option', async () => {+ const store = createEditorStore()+ const model = replyModel()+ try {+ const transport = createToolLoopTransport({+ store,+ providerID: 'openrouter',+ model,+ effectiveModelID: 'openai/gpt-test',+ maxOutputTokens: 100,+ thinkingLevel: () => 'minimal'+ })+ await send(transport)+ expect(model.doStreamCalls[0]?.providerOptions).toEqual({+ openrouter: { reasoning: { effort: 'minimal' } }+ })+ } finally {+ store.dispose()+ }+})diff --git a/tests/app/ai/tools/run.test.ts b/tests/app/ai/tools/run.test.tsindex 87dea03e1..a38dc767b 100644--- a/tests/app/ai/tools/run.test.ts+++ b/tests/app/ai/tools/run.test.ts@@ -61,7 +61,7 @@ async function runMessage(store: EditorStore, steps: Step[]) {model,effectiveModelID: 'test',maxOutputTokens: 100,- reasoningEffort: ''+ thinkingLevel: () => 'default'})const stream = await transport.sendMessages({trigger: 'submit-message',diff --git a/tests/e2e/chat/responses.spec.ts b/tests/e2e/chat/responses.spec.tsindex 01335acbc..bee7e3a5f 100644--- a/tests/e2e/chat/responses.spec.ts+++ b/tests/e2e/chat/responses.spec.ts@@ -8,7 +8,8 @@ test('assistant responds', async ({ configuredChat: chat }) => {test('reasoning and response copy actions render', async ({ configuredChat: chat }) => {await chat.submit('Show reasoning')- const reasoning = chat.assistantMessage().getByRole('button', { name: 'Reasoning' })+ // Reasoning that streamed in this session reports how long the model thought.+ const reasoning = chat.assistantMessage().getByRole('button', { name: /^Thought for \d+s$/ })await expect(reasoning).toHaveAttribute('data-state', 'closed')await reasoning.click()await expect(reasoning).toHaveAttribute('data-state', 'open')diff --git a/tests/engine/app/ai/attachment/image.test.ts b/tests/engine/app/ai/attachment/image.test.tsindex 05163bd45..43200566b 100644--- a/tests/engine/app/ai/attachment/image.test.ts+++ b/tests/engine/app/ai/attachment/image.test.ts@@ -68,7 +68,7 @@ describe('image attachment analysis', () => {model: {} as LanguageModel,role: {requestedRole: 'vision',- profile: { maxOutputTokens: 8000, reasoningEffort: 'low' },+ profile: { maxOutputTokens: 8000, thinkingLevel: 'low' },connection: { providerID: 'openrouter' }}}) as never,diff --git a/tests/engine/app/ai/model-roles.test.ts b/tests/engine/app/ai/model-roles.test.tsindex 059abe279..eeaf1628a 100644--- a/tests/engine/app/ai/model-roles.test.ts+++ b/tests/engine/app/ai/model-roles.test.ts@@ -1,12 +1,15 @@import { afterEach, beforeEach, describe, expect, test } from 'bun:test'-import { buildReasoningProviderOptions } from '@/app/ai/chat/reasoning'+import { omit } from 'es-toolkit'++import { reasoningCallSettings } from '@/app/ai/chat/reasoning'import {aiModelSettings,createAIModelRuntime,createModelProfileDraft,designModelProfiles,modelSettingsSnapshot,+ parseAIModelSettings,removeModelProfile,canRemoveModelProfile,replaceAIModelSettings,@@ -48,6 +51,7 @@ function settingsFixture(): AIModelSettings {modelID: 'claude-sonnet-4-6-20260301',customModelID: '',maxOutputTokens: 16_384,+ thinkingLevel: 'default',capabilities: ['tools', 'vision']},{@@ -57,6 +61,7 @@ function settingsFixture(): AIModelSettings {modelID: 'gemini-3-flash-preview',customModelID: '',maxOutputTokens: 8192,+ thinkingLevel: 'default',capabilities: ['tools']}],@@ -149,7 +154,7 @@ describe('AI model profiles and role assignments', () => {providerID: 'harness:pi',modelID: '',customModelID: 'anthropic/claude-sonnet-4.6',- harnessThinkingLevel: 'medium',+ thinkingLevel: 'medium',harnessPermissionMode: 'allow-edits'})const second = createModelProfileDraft()@@ -158,7 +163,7 @@ describe('AI model profiles and role assignments', () => {providerID: 'harness:pi',modelID: '',customModelID: 'custom/provider-model',- harnessThinkingLevel: 'high',+ thinkingLevel: 'high',harnessPermissionMode: 'allow-reads'})@@ -166,8 +171,8 @@ describe('AI model profiles and role assignments', () => {const savedSecond = saveModelProfileDraft(second)expect(savedFirst.customModelID).toBe('anthropic/claude-sonnet-4.6')expect(savedSecond.customModelID).toBe('custom/provider-model')- expect(savedFirst.harnessThinkingLevel).toBe('medium')- expect(savedSecond.harnessThinkingLevel).toBe('high')+ expect(savedFirst.thinkingLevel).toBe('medium')+ expect(savedSecond.thinkingLevel).toBe('high')expect(savedFirst.harnessPermissionMode).toBe('allow-edits')expect(savedSecond.harnessPermissionMode).toBe('allow-reads')})@@ -188,6 +193,7 @@ describe('AI model profiles and role assignments', () => {modelID: '',customModelID: '',maxOutputTokens: 16_384,+ thinkingLevel: 'default',capabilities: ['tools']})replaceAIModelSettings(settings)@@ -209,22 +215,39 @@ describe('AI model profiles and role assignments', () => {expect(saveModelProfileDraft(draft).maxOutputTokens).toBe(16_384)})- test('persists provider-specific reasoning effort', () => {+ test('persists the profile thinking level', () => {const draft = createModelProfileDraft('model-fast')- draft.reasoningEffort = 'none'- expect(saveModelProfileDraft(draft).reasoningEffort).toBe('none')- expect(createModelProfileDraft('model-fast').reasoningEffort).toBe('none')+ expect(draft.thinkingLevel).toBe('default')+ draft.thinkingLevel = 'off'+ expect(saveModelProfileDraft(draft).thinkingLevel).toBe('off')+ expect(createModelProfileDraft('model-fast').thinkingLevel).toBe('off')})- test('maps reasoning effort to supported provider options', () => {- expect(buildReasoningProviderOptions('openai-compatible', 'none')).toEqual({- openai: { reasoningEffort: 'none' }+ test('migrates saved reasoning effort and Pi levels to thinking levels', () => {+ const settings = settingsFixture()+ const legacy = (profile: AIModelSettings['models'][number], fields: object) => ({+ ...omit(profile, ['thinkingLevel']),+ ...fields+ })+ const [design, fast] = settings.models+ const parsed = parseAIModelSettings({+ ...settings,+ models: [+ legacy(design, { harnessThinkingLevel: 'high' }),+ legacy(fast, { reasoningEffort: 'none' })+ ]})- expect(buildReasoningProviderOptions('openrouter', 'high')).toEqual({- openrouter: { reasoning: { effort: 'high' } }+ expect(parsed?.models.map((profile) => profile.thinkingLevel)).toEqual(['high', 'off'])+ })++ test('maps thinking levels to the AI SDK reasoning option', () => {+ expect(reasoningCallSettings('anthropic', 'high')).toEqual({ reasoning: 'high' })+ expect(reasoningCallSettings('google', 'off')).toEqual({ reasoning: 'none' })+ expect(reasoningCallSettings('openai-compatible', 'xhigh')).toEqual({ reasoning: 'xhigh' })+ expect(reasoningCallSettings('openrouter', 'low')).toEqual({+ providerOptions: { openrouter: { reasoning: { effort: 'low' } } }})- expect(buildReasoningProviderOptions('google', 'high')).toBeUndefined()- expect(buildReasoningProviderOptions('openai', '')).toBeUndefined()+ expect(reasoningCallSettings('anthropic', 'default')).toEqual({})})test('repairs assignments when removing a model', () => {diff --git a/tests/engine/app/ai/vision.test.ts b/tests/engine/app/ai/vision.test.tsindex 9d9813dac..adaf25d3c 100644--- a/tests/engine/app/ai/vision.test.ts+++ b/tests/engine/app/ai/vision.test.ts@@ -33,7 +33,7 @@ describe('isolated visual inspection', () => {model: {} as LanguageModel,role: {requestedRole: 'vision',- profile: { maxOutputTokens: 8000, reasoningEffort: 'low' },+ profile: { maxOutputTokens: 8000, thinkingLevel: 'low' },connection: { providerID: 'openrouter' }}}) as never,diff --git a/tests/engine/app/chat/step-limit.test.ts b/tests/engine/app/chat/step-limit.test.tsindex 742c594b6..157622c77 100644--- a/tests/engine/app/chat/step-limit.test.ts+++ b/tests/engine/app/chat/step-limit.test.ts@@ -85,7 +85,7 @@ test('stop condition, warnings and limit detection share the budget captured permodel,effectiveModelID: 'test',maxOutputTokens: 100,- reasoningEffort: ''+ thinkingLevel: () => 'default'})async function send() {const stream = await transport.sendMessages({diff --git a/tests/engine/app/chat/tool-access.test.ts b/tests/engine/app/chat/tool-access.test.tsindex eed47cd4b..d61dc41b5 100644--- a/tests/engine/app/chat/tool-access.test.ts+++ b/tests/engine/app/chat/tool-access.test.ts@@ -39,7 +39,7 @@ test('a reused AI transport refreshes actual request tools for each message', asmodel,effectiveModelID: 'test',maxOutputTokens: 100,- reasoningEffort: ''+ thinkingLevel: () => 'default'})async function send(history: UIMessage[] = []) {const stream = await transport.sendMessages({diff --git a/tests/helpers/chat/render-stream/browser.ts b/tests/helpers/chat/render-stream/browser.tsindex 184aacc3c..67dcbc9d1 100644--- a/tests/helpers/chat/render-stream/browser.ts+++ b/tests/helpers/chat/render-stream/browser.ts@@ -15,7 +15,7 @@ export function installBrowserRenderStream(scenario: RenderStreamScenario) {providerID: 'openrouter',effectiveModelID: 'streaming-jsx',maxOutputTokens: 4096,- reasoningEffort: ''+ thinkingLevel: () => 'default'}))return controlsdiff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 67362e475..96d1e6c0d 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -22,7 +22,6 @@ ja:ai.modelIDja:ai.modelIDPlaceholderja:ai.modelRoleDesignDescriptionja:ai.provider-ja:ai.reasoningEffortPlaceholderja:automation.addServerConnectionja:automation.aiToolAccessDescriptionja:automation.authenticationDescription@@ -158,7 +157,6 @@ zh-cn:ai.modelIDzh-cn:ai.modelIDPlaceholderzh-cn:ai.modelRoleDesignDescriptionzh-cn:ai.provider-zh-cn:ai.reasoningEffortPlaceholderzh-cn:automation.addServerConnectionzh-cn:automation.aiToolAccessDescriptionzh-cn:automation.authenticationDescriptiondiff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex 1816f0552..bd19cc699 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -1,6 +1,6 @@de:ai.chatSettingsde:ai.completions-de:ai.harnessThinkingMinimal+de:ai.thinkingMinimalde:ai.modelAgentConnectionde:ai.modelCapabilityVisionShortde:ai.modelName@@ -84,7 +84,7 @@ es:storage.providerBackblazees:storage.providerR2es:variableTypes.colorfr:ai.completions-fr:ai.harnessThinkingMinimal+fr:ai.thinkingMinimalfr:ai.modelAgentConnectionfr:ai.modelCapabilityVisionShortfr:ai.modelRoleVision