Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(settings): make the enhancement template, model, and reasoning configurable
zhangsiqiang007889e2d368
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex 5a3fd3d18..d7c3f9a92 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -1,4 +1,4 @@-import { IPC, ErrorCodes, isGlobalPermissionMode, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest } from "@pi-desktop/shared";+import { IPC, ErrorCodes, isGlobalPermissionMode, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, type ThinkingLevel } from "@pi-desktop/shared";import type { FinishTurn } from "../runtime/plans";import { expandSlashInvocation, enhancePromptDraft, summarizeSessionTitle, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";@@ -13,6 +13,7 @@ import type { Logger } from "../logger";import type { PersistenceOutbox } from "../persistence-outbox";import type { ComposerCommandService } from "./composer-ipc";import type { IpcRegistrar } from "./types";+import { withPromptEnhancementTimeout } from "../prompt-enhancement-timeout";export type AgentIpcDependencies = {registrar: IpcRegistrar;@@ -123,29 +124,72 @@ export function registerAgentIpc({}const settings = await host.call<any>("settings.get");const launchSessionId = sessionId || `prompt-enhancement:${crypto.randomUUID()}`;- const launch = await resolveAgentRuntimeLaunch(- launchSessionId,- session ?? {},- settings,- {+ // A pinned enhancement model is a preference, not a hard requirement: a+ // pin whose provider was disabled, whose account was signed out, or whose+ // binding no longer exists must not take the action down. Try the pin,+ // fall back to the Composer's current model, and record why (ADR 0121).+ const pinnedProviderId =+ typeof settings?.promptEnhancementProviderId === "string"+ ? settings.promptEnhancementProviderId.trim()+ : "";+ const pinnedModelId =+ typeof settings?.promptEnhancementModelId === "string"+ ? settings.promptEnhancementModelId.trim()+ : "";+ const composerProviderId =+ typeof req.providerId === "string" ? req.providerId.trim() : undefined;+ const composerModelId =+ typeof req.modelId === "string" ? req.modelId.trim() : undefined;+ // The enhancement carries its own reasoning level and never follows the+ // conversation's: an unset value means "off", because a rewrite rarely+ // benefits from reasoning and reasoning is the slow path.+ const enhancementThinkingLevel =+ typeof settings?.promptEnhancementThinkingLevel === "string"+ ? settings.promptEnhancementThinkingLevel.trim()+ : "";+ const launchFor = (providerId?: string, modelId?: string) =>+ resolveAgentRuntimeLaunch(launchSessionId, session ?? {}, settings, {mode: "agent",- providerId:- typeof req.providerId === "string" ? req.providerId.trim() : undefined,- modelId: typeof req.modelId === "string" ? req.modelId.trim() : undefined,- thinkingLevel: req.thinkingLevel,- },- );+ providerId,+ modelId,+ thinkingLevel: (enhancementThinkingLevel || "off") as ThinkingLevel,+ });+ let launch: Awaited<ReturnType<typeof launchFor>>;+ if (pinnedProviderId) {+ try {+ launch = await launchFor(pinnedProviderId, pinnedModelId || undefined);+ } catch (error) {+ logger.app("session", "warn", "prompt enhancement model unavailable", {+ data: {+ pinnedProviderId,+ pinnedModelId: pinnedModelId || undefined,+ error: error instanceof Error ? error.message : String(error),+ },+ });+ launch = await launchFor(composerProviderId, composerModelId);+ }+ } else {+ launch = await launchFor(composerProviderId, composerModelId);+ }const runtimeProvider = {...launch.sidecarParams.provider,...(launch.sidecarParams.provider.authKind === OAUTH_AUTH_KIND? { resolveAuth: () => vendorOAuth.resolveAuth(launch.providerId) }: {}),} as RuntimeProviderConfig;- const enhancedDraft = await enhancePromptDraft(- runtimeProvider,- draft,- launch.sidecarParams.thinkingLevel,- { sessionId: launchSessionId },+ // A pin, a slow gateway, or a stalled connection would otherwise hold this+ // promise open indefinitely. The transport only consults the signal between+ // provider retries, so aborting is best-effort cancellation; racing the+ // promise is what actually guarantees the caller is released on time.+ const enhancedDraft = await withPromptEnhancementTimeout(+ enhancePromptDraft(runtimeProvider, draft, launch.sidecarParams.thinkingLevel, {+ sessionId: launchSessionId,+ customTemplate: settings?.promptEnhancementCustomTemplate === true,+ userTemplate:+ typeof settings?.promptEnhancementUserTemplate === "string"+ ? settings.promptEnhancementUserTemplate+ : undefined,+ }),);logger.app("session", "info", "prompt enhanced", {sessionId: sessionId || undefined,diff --git a/apps/desktop/electron/main/prompt-enhancement-timeout.ts b/apps/desktop/electron/main/prompt-enhancement-timeout.tsnew file mode 100644index 000000000..54155d145--- /dev/null+++ b/apps/desktop/electron/main/prompt-enhancement-timeout.ts@@ -0,0 +1,57 @@+/**+ * Bound one prompt-enhancement request.+ *+ * The transport only consults its abort signal between provider retries, so+ * aborting is best-effort cancellation. Racing the promise is what actually+ * guarantees the caller is released: without it a stalled connection or a slow+ * gateway holds the renderer's promise open indefinitely, and the provider+ * retry budget alone can already spend about a minute before giving up.+ *+ * Kept in its own module (no Electron or pi-ai imports) so the behavior is+ * directly testable.+ */++/** Hard ceiling for one enhancement request. */+export const PROMPT_ENHANCEMENT_TIMEOUT_MS = 60_000;++/** Classified timeout failure the renderer renders as a dismissible error. */+export type PromptEnhancementTimeoutError = Error & {+ errorCode: "TIMEOUT";+};++export function promptEnhancementTimeoutError(+ timeoutMs: number,+): PromptEnhancementTimeoutError {+ return Object.assign(+ new Error(+ `Prompt enhancement timed out after ${Math.round(timeoutMs / 1000)}s. Try again, or set the enhancement model to follow the session in Settings.`,+ ),+ { errorCode: "TIMEOUT" as const },+ );+}++/**+ * Resolve with `work`, or reject with a `TIMEOUT` error after `timeoutMs`.+ *+ * A failure from `work` itself passes through unchanged; only an unanswered+ * request becomes a timeout. The rejection is never retried on another model:+ * the user chose this one, and a hidden second attempt would double the wait.+ */+export function withPromptEnhancementTimeout<T>(+ work: Promise<T>,+ timeoutMs: number = PROMPT_ENHANCEMENT_TIMEOUT_MS,+): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => reject(promptEnhancementTimeoutError(timeoutMs)), timeoutMs);+ work.then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ (error) => {+ clearTimeout(timer);+ reject(error);+ },+ );+ });+}diff --git a/apps/desktop/src/components/settings/EnhancementModelCard.tsx b/apps/desktop/src/components/settings/EnhancementModelCard.tsxnew file mode 100644index 000000000..dc951ca99--- /dev/null+++ b/apps/desktop/src/components/settings/EnhancementModelCard.tsx@@ -0,0 +1,304 @@+/**+ * Enhancement prompt model and reasoning (ADR 0121).+ *+ * Which model rewrites the Composer draft, and with how much reasoning, are+ * model decisions, so they live on this page next to the default model. They get+ * their own card rather than joining the Defaults card: that card's rows pair a+ * short value with one control, and the enhancement model needs a title, the+ * current value, and a picker — the same shape as the default-model row, which+ * has a card of its own for exactly that reason.+ *+ * The picker reuses the default-model anchored menu so the page offers one kind+ * of model picker, and the reasoning row reuses the shared settings menu select.+ */+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ THINKING_LEVELS,+ modelIdsMatch,+ type AppSettings,+ type ThinkingLevel,+} from "@pi-desktop/shared";+import {+ thinkingLevelForProvider,+ thinkingProviderForModel,+} from "../../features/chat/composer/model";+import { useAppStore } from "../../stores/app-store";+import { api } from "../../lib/api";+import { Button, Input, cx } from "../ui";+import { IconCheck, IconChevronDown, IconSearch } from "../icons";+import { AnchoredMenu } from "./AnchoredMenu";+import { SettingsMenuSelect } from "./SettingsMenuSelect";+import { SettingsRow } from "../../features/settings/primitives";+import { defaultModelOptions } from "./default-model";+import {+ groupSubagentModelChoices,+ subagentModelChoices,+ subagentModelOrphanPin,+ subagentModelSelectValue,+} from "./subagent-models";++export function EnhancementModelCard() {+ const { t } = useTranslation();+ const providers = useAppStore((state) => state.providers);+ const providerModels = useAppStore((state) => state.providerModels);+ const settings = useAppStore((state) => state.settings);+ const showToast = useAppStore((state) => state.showToast);+ const [picking, setPicking] = useState(false);+ const [query, setQuery] = useState("");++ const choices = useMemo(() => subagentModelChoices(providers), [providers]);+ const groups = useMemo(() => groupSubagentModelChoices(choices), [choices]);+ const pinnedValue = useMemo(() => {+ if (!settings?.promptEnhancementProviderId || !settings?.promptEnhancementModelId) return "";+ return subagentModelSelectValue(+ `${settings.promptEnhancementProviderId}/${settings.promptEnhancementModelId}`,+ choices,+ );+ }, [choices, settings?.promptEnhancementProviderId, settings?.promptEnhancementModelId]);+ const orphanPin = useMemo(+ () => subagentModelOrphanPin(pinnedValue, choices),+ [pinnedValue, choices],+ );+ // The menu lists runnable providers, same set the Composer would offer.+ const options = useMemo(+ () => defaultModelOptions(providers.filter((provider) => provider.enabled)),+ [providers],+ );+ const visible = useMemo(() => {+ const needle = query.trim().toLowerCase();+ if (!needle) return options;+ return options.filter(({ provider, modelId }) =>+ `${provider.name} ${modelId}`.toLowerCase().includes(needle),+ );+ }, [options, query]);++ const pinnedProviderId = settings?.promptEnhancementProviderId ?? "";+ const pinnedModelId = settings?.promptEnhancementModelId ?? "";+ const pinnedProvider =+ providers.find((provider) => provider.id === pinnedProviderId) ?? null;+ /**+ * The repository resolves a model's real reasoning ladder from its binding's+ * `thinkingLevels`, then the live catalog, then the provider default. Reusing+ * it keeps this row honest: a model without reasoning offers only `off`+ * instead of the full canonical list, which is what this row showed before.+ */+ const reasoningProvider = useMemo(() => {+ if (!pinnedProviderId || !pinnedModelId) return null;+ return thinkingProviderForModel(+ pinnedProvider,+ pinnedModelId,+ providerModels[pinnedProviderId],+ );+ }, [pinnedProvider, providerModels, pinnedProviderId, pinnedModelId]);+ const reasoningLevels = useMemo(+ () =>+ reasoningProvider?.supportsReasoning+ ? THINKING_LEVELS.filter((level) =>+ (reasoningProvider.supportedThinkingLevels ?? []).includes(level),+ )+ : [],+ [reasoningProvider],+ );+ // A pinned model defines the ladder; with no pin the request follows the+ // session's model, whose ladder is not knowable here, so offer the full list.+ const levelOptions = reasoningProvider ? reasoningLevels : [...THINKING_LEVELS];+ const storedReasoning = settings?.promptEnhancementThinkingLevel ?? "off";+ const reasoning = useMemo(() => {+ if (!reasoningProvider) return storedReasoning;+ return thinkingLevelForProvider(reasoningProvider, storedReasoning);+ }, [reasoningProvider, storedReasoning]);++ // Every hook runs before this: `settings` arrives after the first bootstrap,+ // so an early return above them would change the hook count between renders.+ if (!settings) return null;++ const save = async (patch: Partial<AppSettings>) => {+ const next = { ...settings, ...patch };+ try {+ await api.setSettings(next);+ useAppStore.setState({ settings: next });+ } catch (error) {+ showToast(error instanceof Error ? error.message : String(error), {+ variant: "error",+ });+ }+ };++ const pickModel = async (providerId: string, modelId: string) => {+ // Switching model can change the reasoning ladder (a model without+ // reasoning has none), so re-clamp the stored level onto the new model.+ const nextProvider = providerId+ ? thinkingProviderForModel(+ providers.find((provider) => provider.id === providerId) ?? null,+ modelId,+ providerModels[providerId],+ )+ : null;+ const stored = settings.promptEnhancementThinkingLevel ?? "off";+ await save({+ promptEnhancementProviderId: providerId,+ promptEnhancementModelId: modelId,+ promptEnhancementThinkingLevel: nextProvider+ ? thinkingLevelForProvider(nextProvider, stored)+ : stored,+ });+ setPicking(false);+ };++ return (+ <section className="settings-card-block">+ <div className="model-config-section-head">+ <h3 className="settings-card-heading">{t("settings.promptEnhancementModelTitle")}</h3>+ </div>+ <div className="settings-panel model-default-panel">+ <SettingsRow+ title={t("settings.promptEnhancementModel")}+ description={+ pinnedProvider && settings.promptEnhancementModelId ? (+ <span className="model-default-value">+ <span className="model-default-provider">{pinnedProvider.name}</span>+ <span className="model-default-sep" aria-hidden>+ ·+ </span>+ <span className="model-default-model font-mono">+ {settings.promptEnhancementModelId}+ </span>+ </span>+ ) : (+ <span className="model-default-empty">+ {t("settings.promptEnhancementModelFollow")}+ </span>+ )+ }+ >+ <AnchoredMenu+ className="model-default-anchor"+ open={picking}+ onClose={() => setPicking(false)}+ menuClassName="model-default-menu"+ label={t("settings.promptEnhancementModel")}+ align="end"+ trigger={(ref) => (+ <Button+ ref={ref}+ className="settings-text-action model-default-trigger"+ variant="ghost"+ disabled={groups.length === 0 && !orphanPin}+ onClick={() => {+ setQuery("");+ setPicking((current) => !current);+ }}+ aria-haspopup="listbox"+ aria-expanded={picking}+ >+ {t("settings.changeDefaultModel")}+ <IconChevronDown+ className="model-default-trigger-chevron"+ size={13}+ aria-hidden+ />+ </Button>+ )}+ >+ <div className="model-default-search">+ <IconSearch size={14} aria-hidden />+ <Input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder={t("settings.defaultModelSearch")}+ aria-label={t("settings.defaultModelSearch")}+ autoFocus+ />+ </div>+ <div className="model-default-results" role="presentation">+ {visible.length === 0 ? (+ <div className="model-default-no-results">{t("settings.noModelMatches")}</div>+ ) : null}+ <ul className="model-default-list">+ <li>+ <button+ type="button"+ role="option"+ aria-selected={!settings.promptEnhancementProviderId}+ aria-label={t("settings.promptEnhancementModelFollow")}+ className={cx(+ "model-default-option",+ !settings.promptEnhancementProviderId && "is-current",+ )}+ onClick={() => void pickModel("", "")}+ >+ <span className="model-default-option-check" aria-hidden>+ {!settings.promptEnhancementProviderId ? <IconCheck size={12} /> : null}+ </span>+ <span className="model-default-option-model">+ {t("settings.promptEnhancementModelFollow")}+ </span>+ </button>+ </li>+ {visible.map(({ provider, modelId }, index) => {+ const isCurrent =+ settings.promptEnhancementProviderId === provider.id &&+ modelIdsMatch(settings.promptEnhancementModelId ?? "", modelId);+ const previous = visible[index - 1];+ const startsGroup = !previous || previous.provider.id !== provider.id;+ return (+ <li key={`${provider.id}:${modelId}`}>+ {startsGroup ? (+ <div+ className={cx(+ "model-default-provider-group",+ index > 0 && "has-divider",+ )}+ >+ {provider.name}+ </div>+ ) : null}+ <button+ type="button"+ role="option"+ aria-selected={isCurrent}+ aria-label={`${provider.name} · ${modelId}`}+ className={cx("model-default-option", isCurrent && "is-current")}+ onClick={() => void pickModel(provider.id, modelId)}+ >+ <span className="model-default-option-check" aria-hidden>+ {isCurrent ? <IconCheck size={12} /> : null}+ </span>+ <span className="model-default-option-model font-mono">{modelId}</span>+ </button>+ </li>+ );+ })}+ </ul>+ </div>+ </AnchoredMenu>+ </SettingsRow>++ <SettingsRow+ title={t("settings.promptEnhancementThinking")}+ description={t("settings.promptEnhancementThinkingDesc")}+ >+ <SettingsMenuSelect+ label={t("settings.promptEnhancementThinking")}+ value={reasoning}+ disabled={levelOptions.length === 0}+ options={levelOptions.map((level) => ({+ id: level,+ label: level === "off" ? t("settings.promptEnhancementThinkingOff") : level,+ }))}+ onChange={(id) =>+ void save({+ // Clamp through the same resolver the row displays, so the value+ // stored is always one this model can run.+ promptEnhancementThinkingLevel: reasoningProvider+ ? thinkingLevelForProvider(reasoningProvider, id as ThinkingLevel)+ : (id as ThinkingLevel),+ })+ }+ />+ </SettingsRow>+ </div>+ </section>+ );+}diff --git a/apps/desktop/src/components/settings/ModelConfigPage.tsx b/apps/desktop/src/components/settings/ModelConfigPage.tsxindex 30488287c..0303b77ac 100644--- a/apps/desktop/src/components/settings/ModelConfigPage.tsx+++ b/apps/desktop/src/components/settings/ModelConfigPage.tsx@@ -38,6 +38,7 @@ import {} from "./default-model";import { copyProviderConfiguration, type ProviderCopyDraft } from "./provider-copy";import { ProviderSetupDialog } from "./ProviderSetupDialog";+import { EnhancementModelCard } from "./EnhancementModelCard";import { VendorAccountsSection } from "./VendorAccountsSection";const DELETE_CONFIRM_MS = 3000;@@ -126,6 +127,7 @@ export function ModelConfigPage() {);}, [defaultModelOptionsList, defaultModelQuery]);+if (!settings) return null;const defaultProvider =@@ -134,6 +136,7 @@ export function ModelConfigPage() {setupFor ? providers.find((provider) => provider.id === setupFor) ?? null : null;const defaultProviderReady = defaultProvider !== null && providerReady(defaultProvider);+const setDefaultModel = async (provider: ProviderPublic, modelId: string) => {setBusyId(provider.id);try {@@ -415,6 +418,8 @@ export function ModelConfigPage() {</div></section>+ <EnhancementModelCard />+<section className="settings-card-block"><div className="model-config-section-head"><div className="settings-card-heading-line">diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsxindex 5b85d54c7..1d1452eaa 100644--- a/apps/desktop/src/features/settings/SettingsPage.tsx+++ b/apps/desktop/src/features/settings/SettingsPage.tsx@@ -54,6 +54,7 @@ import {ImportSection,UpdatesRow,} from "./agent-sections";+import { PromptEnhancementCard } from "./prompt-enhancement-card";import { VoiceSettingsCard } from "./voice-settings";import { CloseBehaviorSection, DeveloperSection } from "./developer-sections";import { PluginSettingsDestination } from "../../components/settings/PluginSettingsDestination";@@ -427,6 +428,11 @@ export function SettingsPage() {saveSettings={saveSettings}/></SettingsCard>++ <PromptEnhancementCard+ settings={settings}+ saveSettings={saveSettings}+ /></div>)}diff --git a/apps/desktop/src/features/settings/prompt-enhancement-card.tsx b/apps/desktop/src/features/settings/prompt-enhancement-card.tsxnew file mode 100644index 000000000..0df91eef7--- /dev/null+++ b/apps/desktop/src/features/settings/prompt-enhancement-card.tsx@@ -0,0 +1,285 @@+/**+ * Prompt-enhancement settings (ADR 0121).+ *+ * This card owns the prompt itself: a switch that chooses between the built-in+ * user template and a saved one, and the settings icon button that opens the+ * template editor. Which model runs the rewrite, and with how much reasoning,+ * is a model decision and lives on the Model configuration page.+ *+ * What is deliberately not editable: the system prompt. It carries the rewrite+ * contract the feature is verified against (proper-noun preservation, language+ * following without meta notes, the output contract), so it stays a built-in+ * default and host-core drops any stored override.+ *+ * The template field shows the built-in default text when no override is saved,+ * so the editor opens on the value in force, and "restore default" is+ * self-explanatory. Editing the field back to the exact default text clears the+ * override rather than storing a frozen copy, so a later product improvement to+ * the default still reaches users who never customized it.+ */+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import type { AppSettings } from "@pi-desktop/shared";+import {+ PROMPT_ENHANCEMENT_DEFAULT_USER_TEMPLATE,+ PROMPT_ENHANCEMENT_DRAFT_VARIABLE,+ isValidPromptEnhancementUserTemplate,+} from "@pi-desktop/shared";+import { useAppStore } from "../../stores/app-store";+import { Button, Field, TooltipButton, cx, portalOverlay } from "../../components/ui";+import { IconPencil, IconX } from "../../components/icons";+import { SettingsCard, SettingsRow } from "./primitives";++export function PromptEnhancementCard({+ settings,+ saveSettings,+}: {+ settings: AppSettings;+ saveSettings: (patch: Partial<AppSettings>) => Promise<void>;+}) {+ const { t } = useTranslation();+ const [editorOpen, setEditorOpen] = useState(false);+ const customTemplate = settings.promptEnhancementCustomTemplate === true;+ // A saved, usable template is what makes the switch meaningful.+ const hasCustomTemplate = isValidPromptEnhancementUserTemplate(+ settings.promptEnhancementUserTemplate,+ );++ return (+ <SettingsCard title={t("settings.promptEnhancementTitle")}>+ <SettingsRow+ title={t("settings.promptEnhancementCustomTemplate")}+ description={t("settings.promptEnhancementCustomTemplateDesc")}+ >+ {/*+ The switch selects between a saved custom template and the built-in+ one, so it means nothing until a template has been saved. It is+ disabled rather than hidden: the user can see that the choice exists+ and that editing is what unlocks it.+ */}+ <button+ type="button"+ className={cx("settings-toggle", customTemplate && "on")}+ role="switch"+ aria-checked={customTemplate}+ aria-disabled={!hasCustomTemplate}+ disabled={!hasCustomTemplate}+ aria-label={t("settings.promptEnhancementCustomTemplate")}+ title={+ hasCustomTemplate+ ? undefined+ : t("settings.promptEnhancementCustomTemplateNeedsTemplate")+ }+ onClick={() =>+ void saveSettings({ promptEnhancementCustomTemplate: !customTemplate })+ }+ >+ <span className="settings-toggle-thumb" />+ </button>+ {/*+ The subagent list's edit affordance: a tooltipped icon button, so the+ row keeps one control cluster instead of three competing labels.+ */}+ <TooltipButton+ type="button"+ className="settings-icon-button"+ ariaLabel={t("settings.promptEnhancementEdit")}+ tooltip={t("settings.promptEnhancementEdit")}+ onClick={() => setEditorOpen(true)}+ >+ <IconPencil size={15} />+ </TooltipButton>+ </SettingsRow>++ {editorOpen ? (+ <PromptEnhancementEditorSheet+ settings={settings}+ saveSettings={saveSettings}+ onClose={() => setEditorOpen(false)}+ />+ ) : null}+ </SettingsCard>+ );+}++/**+ * The editor itself. Drafts are local until Save, so closing the sheet abandons+ * the edit — the same contract as the subagent editor.+ */+function PromptEnhancementEditorSheet({+ settings,+ saveSettings,+ onClose,+}: {+ settings: AppSettings;+ saveSettings: (patch: Partial<AppSettings>) => Promise<void>;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const savedTemplate = settings.promptEnhancementUserTemplate ?? "";+ const [templateDraft, setTemplateDraft] = useState(+ savedTemplate || PROMPT_ENHANCEMENT_DEFAULT_USER_TEMPLATE,+ );+ const [saving, setSaving] = useState(false);+ const [saveError, setSaveError] = useState(false);+ const templateRef = useRef<HTMLTextAreaElement | null>(null);++ const templateMissingVariable =+ templateDraft.trim().length > 0 &&+ !isValidPromptEnhancementUserTemplate(templateDraft);+ const dirty =+ templateDraft !== (savedTemplate || PROMPT_ENHANCEMENT_DEFAULT_USER_TEMPLATE);++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ // Escape closes only when nothing is in flight, so a save cannot be+ // abandoned halfway through.+ if (event.key === "Escape" && !saving) onClose();+ };+ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, [saving, onClose]);++ const insertDraftVariable = () => {+ const element = templateRef.current;+ if (!element) {+ setTemplateDraft((current) => `${current}${PROMPT_ENHANCEMENT_DRAFT_VARIABLE}`);+ return;+ }+ const start = element.selectionStart ?? templateDraft.length;+ const end = element.selectionEnd ?? start;+ setTemplateDraft(+ `${templateDraft.slice(0, start)}${PROMPT_ENHANCEMENT_DRAFT_VARIABLE}${templateDraft.slice(end)}`,+ );+ const caret = start + PROMPT_ENHANCEMENT_DRAFT_VARIABLE.length;+ requestAnimationFrame(() => {+ element.focus();+ element.setSelectionRange(caret, caret);+ });+ };++ const restoreTemplateDefault = () => {+ setTemplateDraft(PROMPT_ENHANCEMENT_DEFAULT_USER_TEMPLATE);+ };++ const save = async () => {+ if (templateMissingVariable || saving) return;+ setSaving(true);+ setSaveError(false);+ try {+ // The default text is never persisted, so a later change to the default+ // still reaches a user who left the field at its default value.+ const savedTemplateValue =+ templateDraft === PROMPT_ENHANCEMENT_DEFAULT_USER_TEMPLATE+ ? ""+ : templateDraft;+ const templateChanged = savedTemplateValue !== savedTemplate;+ await saveSettings({+ promptEnhancementUserTemplate: savedTemplateValue,+ // Saving a template switches it on, because the user just wrote one.+ promptEnhancementCustomTemplate: templateChanged+ ? Boolean(savedTemplateValue.trim())+ : settings.promptEnhancementCustomTemplate === true,+ });+ onClose();+ } catch {+ setSaveError(true);+ } finally {+ setSaving(false);+ }+ };++ return portalOverlay(+ <div+ className="overlay ext-sheet-overlay"+ role="presentation"+ onMouseDown={(event) => {+ if (event.target === event.currentTarget && !saving) onClose();+ }}+ >+ <div+ className="dialog ext-sheet"+ role="dialog"+ aria-modal+ aria-labelledby="prompt-enhancement-sheet-title"+ >+ <div className="ext-sheet-head">+ <div>+ <h3 id="prompt-enhancement-sheet-title" className="ext-sheet-title">+ {t("settings.promptEnhancementTitle")}+ </h3>+ <div className="ext-sheet-sub">{t("settings.promptEnhancementDesc")}</div>+ </div>+ <TooltipButton+ type="button"+ className="ext-sheet-close"+ ariaLabel={t("common.close")}+ tooltip={t("common.close")}+ onClick={onClose}+ >+ <IconX size={14} />+ </TooltipButton>+ </div>++ <div className="ext-sheet-body">+ <Field+ label={t("settings.promptEnhancementUserTemplate")}+ hint={t("settings.promptEnhancementUserTemplateDesc")}+ >+ {/* A plain textarea: the shared Textarea wrapper does not forward a+ ref, and the insert action needs one to place the caret. */}+ <textarea+ ref={templateRef}+ className="field-textarea ext-skill-body"+ value={templateDraft}+ rows={8}+ onChange={(event) => setTemplateDraft(event.target.value)}+ aria-label={t("settings.promptEnhancementUserTemplate")}+ aria-invalid={templateMissingVariable}+ spellCheck={false}+ autoCorrect="off"+ autoCapitalize="off"+ />+ </Field>++ {templateMissingVariable ? (+ <span className="settings-command-shell-state error" role="status">+ {t("settings.promptEnhancementMissingDraftVariable")}+ </span>+ ) : null}++ <div className="settings-panel-actions">+ <Button variant="secondary" type="button" onClick={insertDraftVariable}>+ {t("settings.promptEnhancementInsertDraft")}+ </Button>+ <Button variant="secondary" type="button" onClick={restoreTemplateDefault}>+ {t("settings.promptEnhancementRestore")}+ </Button>+ </div>++ {saveError ? (+ <span className="settings-command-shell-state error" role="status">+ {t("settings.promptEnhancementSaveError")}+ </span>+ ) : null}+ </div>++ <div className="ext-sheet-actions">+ <div className="ext-sheet-actions-end">+ <Button variant="ghost" type="button" disabled={saving} onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button+ variant="primary"+ type="button"+ disabled={!dirty || saving || templateMissingVariable}+ onClick={() => void save()}+ >+ {saving ? t("common.saving") : t("common.save")}+ </Button>+ </div>+ </div>+ </div>+ </div>,+ );+}diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.tsindex 9ca4aeb3d..5d5a08d3b 100644--- a/apps/desktop/src/lib/settings-search.ts+++ b/apps/desktop/src/lib/settings-search.ts@@ -92,6 +92,11 @@ export const SETTINGS_NAV: SettingsNavEntry[] = ["settings.contextUsageDisplay","settings.contextUsageDisplayRemaining","settings.contextUsageDisplayUsed",+ "settings.promptEnhancementTitle",+ "settings.promptEnhancementDesc",+ "settings.promptEnhancementCustomTemplate",+ "settings.promptEnhancementEdit",+ "settings.promptEnhancementUserTemplate","settings.largePasteThreshold",],},@@ -124,6 +129,10 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [titleKey: "settings.configuration",group: "agent",keywordKeys: [+ "settings.promptEnhancementModelTitle",+ "settings.promptEnhancementModel",+ "settings.promptEnhancementModelFollow",+ "settings.promptEnhancementThinking","settings.providers","settings.models","settings.defaultModel",diff --git a/apps/desktop/src/styles/settings.css b/apps/desktop/src/styles/settings.cssindex f9d1e0d6f..c2441a050 100644--- a/apps/desktop/src/styles/settings.css+++ b/apps/desktop/src/styles/settings.css@@ -393,6 +393,14 @@align-items: stretch;}+/*+ A toggle paired with an icon action (prompt enhancement). The control column+ has no gap of its own, so the two would otherwise touch.+*/+.settings-row-control:has(> .settings-toggle + .settings-icon-button) {+ gap: 8px;+}+.settings-speech-fields {display: flex;flex-direction: column;@@ -702,6 +710,23 @@box-shadow: 0 0 0 2px color-mix(in oklab, var(--ds-accent) 24%, transparent);}+/*+ A disabled switch still reads as a switch: dimmed, not restyled, and the+ cursor says why clicking does nothing.+*/+.settings-toggle:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.settings-toggle:disabled:hover {+ background: var(--ds-switch-track-off);+}++.settings-toggle.on:disabled:hover {+ background: var(--ds-accent);+}+.settings-toggle.is-busy .settings-toggle-thumb {animation: settings-toggle-pending 900ms ease-in-out infinite alternate;}diff --git a/apps/desktop/test/prompt-enhancement.test.mjs b/apps/desktop/test/prompt-enhancement.test.mjsindex fc6101c1d..4c09c2909 100644--- a/apps/desktop/test/prompt-enhancement.test.mjs+++ b/apps/desktop/test/prompt-enhancement.test.mjs@@ -2,6 +2,10 @@ import { readComposerSource, readMainSource } from "./helpers/source-contracts.mimport assert from "node:assert/strict";import { readFile } from "node:fs/promises";import test from "node:test";+import {+ PROMPT_ENHANCEMENT_TIMEOUT_MS,+ withPromptEnhancementTimeout,+} from "../electron/main/prompt-enhancement-timeout.ts";const read = (path) => readFile(new URL(path, import.meta.url), "utf8");@@ -22,6 +26,10 @@ test("prompt enhancement uses the typed main-process bridge", () => {assert.match(api, /IPC\.invoke\.promptEnhance/);assert.match(main, /handle\(IPC\.invoke\.promptEnhance/);assert.match(main, /enhancePromptDraft\(/);+ // The handler bounds the request through the dedicated timeout module.+ assert.match(main, /withPromptEnhancementTimeout/);+ assert.match(main, /enhancementThinkingLevel \|\| "off"/);+ assert.match(main, /from "\.\.\/prompt-enhancement-timeout"/);assert.match(main, /sessionId: launchSessionId/);assert.match(main, /resolveAuth: \(\) => vendorOAuth\.resolveAuth/);assert.match(runtime, /completeOneShot\(/);@@ -62,3 +70,164 @@ test("prompt enhancement has complete English-first locale coverage", () => {assert.match(source, /dismissEnhancementError:/);}});++test("prompt-enhancement settings expose templates, restore, and the draft variable", async () => {+ const card = await read("../src/features/settings/prompt-enhancement-card.tsx");+ const settingsPage = await read("../src/features/settings/SettingsPage.tsx");+ const shared = await read("../../../packages/shared/src/prompt-enhancement.ts");+ const hostCore = await read("../../../crates/host-core/src/rpc/mod.rs");++ // The card is reachable from the AI settings tab.+ assert.match(settingsPage, /PromptEnhancementCard/);+ assert.match(card, /PROMPT_ENHANCEMENT_DEFAULT_USER_TEMPLATE/);+ assert.match(card, /promptEnhancementUserTemplate/);+ // The system prompt is not overridable; the card must not offer a field for it.+ assert.doesNotMatch(card, /promptEnhancementSystemPrompt/);+ // Editing happens in a sheet, opened from the card, matching the subagent editor.+ assert.match(card, /ext-sheet-overlay/);+ assert.match(card, /ext-sheet-actions/);+ assert.match(card, /portalOverlay/);+ assert.match(card, /promptEnhancementCustomTemplate/);+ // The switch is the standard settings toggle, and Edit is the subagent+ // list's icon button rather than a labelled action in the row.+ assert.match(card, /settings-toggle/);+ assert.match(card, /role="switch"/);+ // The switch is usable only once a template has been saved, and saving one+ // turns it on.+ assert.match(card, /hasCustomTemplate/);+ assert.match(card, /disabled=\{!hasCustomTemplate\}/);+ assert.match(card, /promptEnhancementCustomTemplateNeedsTemplate/);+ assert.match(card, /promptEnhancementCustomTemplate: templateChanged/);+ assert.match(card, /const templateChanged = savedTemplateValue !== savedTemplate/);+ assert.match(card, /settings-icon-button/);+ assert.match(card, /IconPencil/);+ // The model and reasoning rows live on the Model configuration page, not here.+ assert.doesNotMatch(card, /promptEnhancementProviderId/);+ assert.doesNotMatch(card, /promptEnhancementThinkingLevel/);+ assert.doesNotMatch(card, /promptEnhancementModelId/);+ assert.doesNotMatch(card, /SubagentModelPicker/);+ // A save that would drop the draft variable is refused before it is sent.+ assert.match(card, /templateMissingVariable/);+ assert.match(card, /isValidPromptEnhancementUserTemplate/);++ // The defaults live in shared so the settings page can display the same text+ // the runtime sends, and the placeholder is substituted literally.+ assert.match(shared, /export const PROMPT_ENHANCEMENT_DRAFT_VARIABLE/);+ assert.match(shared, /renderPromptEnhancementUserPrompt/);+ assert.match(shared, /resolvePromptEnhancementTemplates/);+ assert.doesNotMatch(shared, /\.replace\(PROMPT_ENHANCEMENT_DRAFT_VARIABLE, draft\)/);++ // host-core validates before persisting, so no other writer can store a+ // template that would silently drop the draft.+ assert.match(hostCore, /fn prompt_enhancement_template_error/);+ assert.match(hostCore, /MAX_PROMPT_ENHANCEMENT_TEMPLATE_CHARS/);+ assert.match(hostCore, /promptEnhancementUserTemplate must contain/);++ // The one-shot keeps its boundary: no history, no tools.+ assert.match(runtime, /promptEnhancementContext/);+ assert.match(oneShot, /createProviderRetryStream/);+});++test("prompt-enhancement locale coverage includes the settings copy", () => {+ for (const source of [en, zh]) {+ for (const key of [+ "promptEnhancementTitle",+ "promptEnhancementEdit",+ "promptEnhancementUserTemplate",+ "promptEnhancementInsertDraft",+ "promptEnhancementCustomTemplate",+ "promptEnhancementCustomTemplateDesc",+ "promptEnhancementCustomTemplateNeedsTemplate",+ "promptEnhancementMissingDraftVariable",+ "promptEnhancementSaveError",+ ]) {+ assert.match(source, new RegExp(`${key}:`));+ }+ }+});++test("an enhancement request is released when the provider never answers", async () => {+ const started = Date.now();+ // A promise that never settles is exactly the hang the transport cannot bound+ // on its own: the abort signal is only consulted between provider retries.+ const never = new Promise(() => {});+ await assert.rejects(+ withPromptEnhancementTimeout(never, 40),+ (error) => {+ assert.equal(error.errorCode, "TIMEOUT");+ assert.match(error.message, /timed out after/);+ return true;+ },+ );+ assert.ok(Date.now() - started < 2000, "the caller must be released promptly");+});++test("a completed enhancement is not turned into a timeout", async () => {+ assert.equal(await withPromptEnhancementTimeout(Promise.resolve("ok"), 5000), "ok");+ await assert.rejects(+ withPromptEnhancementTimeout(Promise.reject(new Error("provider 500")), 5000),+ /provider 500/,+ );+});++test("the default ceiling is about a minute", () => {+ assert.equal(PROMPT_ENHANCEMENT_TIMEOUT_MS, 60_000);+});++test("the enhancement model and reasoning live on their own Model-page card", async () => {+ const modelPage = await read("../src/components/settings/ModelConfigPage.tsx");+ const card = await read("../src/components/settings/EnhancementModelCard.tsx");++ // The Models page mounts the dedicated card rather than inlining the rows.+ assert.match(modelPage, /EnhancementModelCard/);+ assert.doesNotMatch(modelPage, /promptEnhancementProviderId/);++ // Card title and row title are separate strings (B3: both read "Default model").+ assert.match(card, /promptEnhancementModelTitle/);+ assert.match(card, /t\("settings\.promptEnhancementModel"\)/);++ // Same control as the default-model row: one anchored menu, one search field.+ assert.match(card, /AnchoredMenu/);+ assert.match(card, /model-default-anchor/);+ assert.match(card, /promptEnhancementProviderId/);+ assert.match(card, /promptEnhancementModelId/);+ assert.match(card, /promptEnhancementModelFollow/);+ assert.match(card, /pickModel/);++ // The rows use the shared settings row, not an ad-hoc layout.+ assert.match(card, /SettingsRow/);+});++test("the reasoning row follows the selected model's real ladder", async () => {+ const card = await read("../src/components/settings/EnhancementModelCard.tsx");++ // Reuse the Composer's model-aware resolution instead of the canonical list.+ assert.match(card, /thinkingProviderForModel/);+ assert.match(card, /thinkingLevelForProvider/);+ assert.match(card, /reasoningProvider/);+ assert.match(card, /levelOptions/);+ // A pinned model narrows the list; only an unpinned model falls back to all.+ assert.match(card, /reasoningProvider \? reasoningLevels : \[\.\.\.THINKING_LEVELS\]/);+ // A model without reasoning disables the row rather than offering levels.+ assert.match(card, /disabled=\{levelOptions\.length === 0\}/);+ // Switching model re-clamps the stored level onto the new model.+ const pickModel = card.slice(card.indexOf("const pickModel"), card.indexOf("return ("));+ assert.match(pickModel, /thinkingLevelForProvider\(nextProvider, stored\)/);+ // No follow-the-session option in this row.+ assert.doesNotMatch(card, /promptEnhancementThinkingFollow/);+});++test("the model-page copy exists in both reference locales", () => {+ for (const source of [en, zh]) {+ for (const key of [+ "promptEnhancementModelTitle",+ "promptEnhancementModel",+ "promptEnhancementModelFollow",+ "promptEnhancementThinking",+ "promptEnhancementThinkingDesc",+ "promptEnhancementThinkingOff",+ ]) {+ assert.match(source, new RegExp(`${key}:`));+ }+ }+});diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 2ee2ab4dc..57b0186c4 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -575,6 +575,36 @@ fn drop_session_side_data(st: &AppState, id: &str) {const DEFAULT_LARGE_PASTE_THRESHOLD: i64 = 600;const MIN_LARGE_PASTE_THRESHOLD: i64 = 1;const MAX_LARGE_PASTE_THRESHOLD: i64 = 1_000_000;+/// Upper bound for one stored prompt-enhancement template, in characters.+/// Mirrored by `PROMPT_ENHANCEMENT_TEMPLATE_MAX_LENGTH` in+/// `packages/shared/src/prompt-enhancement.ts`; keep the two in step.+const MAX_PROMPT_ENHANCEMENT_TEMPLATE_CHARS: usize = 8000;+/// The placeholder a usable user template must carry.+const PROMPT_ENHANCEMENT_DRAFT_VARIABLE: &str = "{{draft}}";++/// A template override is either absent, blank (meaning "use the default"), or+/// a non-blank string within the length bound; a user template must also carry+/// the draft variable, or the draft never reaches the model.+fn prompt_enhancement_template_error(field: &str, value: &Value) -> Option<String> {+ let Some(text) = value.as_str() else {+ return Some(format!("{field} must be a string"));+ };+ if text.trim().is_empty() {+ return None;+ }+ if text.chars().count() > MAX_PROMPT_ENHANCEMENT_TEMPLATE_CHARS {+ return Some(format!(+ "{field} must not exceed {MAX_PROMPT_ENHANCEMENT_TEMPLATE_CHARS} characters"+ ));+ }+ if field == "promptEnhancementUserTemplate" && !text.contains(PROMPT_ENHANCEMENT_DRAFT_VARIABLE)+ {+ return Some(format!(+ "promptEnhancementUserTemplate must contain {PROMPT_ENHANCEMENT_DRAFT_VARIABLE}"+ ));+ }+ None+}fn normalize_settings_value(mut value: Value) -> Value {if let Some(object) = value.as_object_mut() {@@ -604,6 +634,25 @@ fn normalize_settings_value(mut value: Value) -> Value {Value::Number(DEFAULT_LARGE_PASTE_THRESHOLD.into()),);}+ // A blank override means "use the built-in default", and an unusable+ // one (wrong type, oversized, or a user template without the draft+ // variable) falls back to the default too, rather than leaving a+ // prompt that would silently drop the user's draft.+ // The system prompt is part of the feature contract, not a preference:+ // an override written by an older build is dropped so the store cannot+ // hold a value that would never be read.+ object.remove("promptEnhancementSystemPrompt");+ let template_field = "promptEnhancementUserTemplate";+ let unusable_template = match object.get(template_field) {+ None => false,+ Some(value) => match prompt_enhancement_template_error(template_field, value) {+ Some(_) => true,+ None => value.as_str().is_some_and(|text| text.trim().is_empty()),+ },+ };+ if unusable_template {+ object.remove(template_field);+ }}value}@@ -633,6 +682,13 @@ fn validate_settings_value(value: &Value) -> Result<(), JsonRpcError> {let Some(object) = value.as_object() else {return Ok(());};+ if let Some(template_value) = object.get("promptEnhancementUserTemplate") {+ if let Some(message) =+ prompt_enhancement_template_error("promptEnhancementUserTemplate", template_value)+ {+ return Err(rpc_err(1002, message, "INVALID_PARAMS"));+ }+ }if let Some(threshold_value) = object.get("largePasteThreshold") {let Some(threshold) = threshold_value.as_i64() else {return Err(rpc_err(@@ -5858,6 +5914,108 @@ mod tests {assert!(catalog["effective"].is_object() || catalog["effective"].is_null());}+ #[tokio::test]+ async fn prompt_enhancement_templates_round_trip_and_validate() {+ let data_dir = tempfile::tempdir().unwrap();+ let mut app_state = AppState::open(data_dir.path()).unwrap();+ app_state.handshook = true;+ let state = Arc::new(Mutex::new(app_state));+ let (tx, _rx) = mpsc::unbounded_channel();++ // Nothing stored yet: the field is absent, so the renderer falls back+ // to the built-in default.+ let settings = handle_request(state.clone(), "settings.get", json!({}), tx.clone())+ .await+ .unwrap();+ assert!(settings.get("promptEnhancementUserTemplate").is_none());++ // A custom template and its switch persist unchanged.+ handle_request(+ state.clone(),+ "settings.set",+ json!({+ "promptEnhancementCustomTemplate": true,+ "promptEnhancementUserTemplate": "before {{draft}} after",+ }),+ tx.clone(),+ )+ .await+ .unwrap();+ let stored = handle_request(state.clone(), "settings.get", json!({}), tx.clone())+ .await+ .unwrap();+ assert_eq!(+ stored["promptEnhancementUserTemplate"],+ "before {{draft}} after"+ );+ assert_eq!(stored["promptEnhancementCustomTemplate"], true);++ // A user template without the draft variable would silently drop the+ // draft, so the write is rejected rather than normalized.+ let missing_variable = handle_request(+ state.clone(),+ "settings.set",+ json!({ "promptEnhancementUserTemplate": "no placeholder" }),+ tx.clone(),+ )+ .await+ .unwrap_err();+ assert_eq!(+ missing_variable.data.unwrap()["errorCode"],+ "INVALID_PARAMS"+ );++ // An oversized template is rejected too.+ let oversized = handle_request(+ state.clone(),+ "settings.set",+ json!({ "promptEnhancementUserTemplate": "x".repeat(8001) }),+ tx.clone(),+ )+ .await+ .unwrap_err();+ assert_eq!(oversized.data.unwrap()["errorCode"], "INVALID_PARAMS");++ // The system prompt is not overridable: a write carrying one is dropped+ // by normalization, so the store cannot hold a value that would never+ // be read.+ handle_request(+ state.clone(),+ "settings.set",+ json!({ "promptEnhancementSystemPrompt": "custom system" }),+ tx.clone(),+ )+ .await+ .unwrap();+ assert!(+ handle_request(state.clone(), "settings.get", json!({}), tx.clone())+ .await+ .unwrap()+ .get("promptEnhancementSystemPrompt")+ .is_none()+ );++ // Writing a blank value means "restore the default": the override is+ // dropped rather than persisted as an empty string.+ handle_request(+ state.clone(),+ "settings.set",+ json!({ "promptEnhancementUserTemplate": " " }),+ tx,+ )+ .await+ .unwrap();+ let cleared = handle_request(+ state,+ "settings.get",+ json!({}),+ mpsc::unbounded_channel().0,+ )+ .await+ .unwrap();+ assert!(cleared.get("promptEnhancementUserTemplate").is_none());+ }+#[tokio::test]async fn settings_set_round_trips_an_explicitly_disabled_shortcut() {let data_dir = tempfile::tempdir().unwrap();diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 0b7be4a46..97eaad79f 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -1152,6 +1152,30 @@ sklm: {"fontSizeXl": "Trenta","fontSizeScale": "Textgrößenskala","fontSizePercent": "{{value}}%",+ "promptEnhancementTitle": "Prompt-Verbesserung",+ "promptEnhancementDesc":+ "Gilt für die Aktion „Prompt verbessern“ im Composer. Der System-Prompt ist eingebaut; Nutzervorlage und Modell sind anpassbar.",+ "promptEnhancementCustomTemplate": "Eigene Vorlage verwenden",+ "promptEnhancementCustomTemplateDesc":+ "Ersetzt die eingebaute Nutzervorlage durch Ihre eigene. Der System-Prompt bleibt eingebaut.",+ "promptEnhancementCustomTemplateNeedsTemplate":+ "Speichern Sie zuerst eine eigene Vorlage; der Schalter wählt dann zwischen ihr und der eingebauten Vorlage.",+ "promptEnhancementEdit": "Bearbeiten",+ "promptEnhancementModelTitle": "Prompt-Verbesserung",+ "promptEnhancementModel": "Standardmodell",+ "promptEnhancementThinking": "Denkaufwand",+ "promptEnhancementThinkingDesc":+ "Denkaufwand für die Umschreibung. Standard ist Aus und am schnellsten.",+ "promptEnhancementThinkingOff": "Aus (kein Denken)",+ "promptEnhancementModelFollow": "Aktuellem Modell folgen",+ "promptEnhancementUserTemplate": "Benutzer-Vorlage",+ "promptEnhancementUserTemplateDesc":+ "Umschließt den Entwurf. Muss die Entwurfsvariable enthalten; fügen Sie sie über die Schaltfläche ein.",+ "promptEnhancementInsertDraft": "Entwurfsvariable einfügen",+ "promptEnhancementRestore": "Standard wiederherstellen",+ "promptEnhancementMissingDraftVariable":+ "Die Benutzer-Vorlage muss die Entwurfsvariable enthalten, sonst kann der Entwurf nicht gesendet werden.",+ "promptEnhancementSaveError": "Die Prompt-Verbesserungseinstellungen konnten nicht gespeichert werden.",},"project": {"open": "Projekt öffnen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex e648e74c1..be2aa9f7d 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1168,6 +1168,30 @@ sklm: {fontSizeXl: "Trenta",fontSizeScale: "Text size scale",fontSizePercent: "{{value}}%",+ promptEnhancementTitle: "Prompt enhancement",+ promptEnhancementDesc:+ "Applies to the Composer's Enhance prompt action. The system prompt is built in; the user template and the enhancement model can be customized.",+ promptEnhancementCustomTemplate: "Use a custom template",+ promptEnhancementCustomTemplateDesc:+ "Replaces the built-in user template with your own. The system prompt stays built in.",+ promptEnhancementCustomTemplateNeedsTemplate:+ "Save a custom template first; the switch then chooses between it and the built-in template.",+ promptEnhancementEdit: "Edit",+ promptEnhancementModelTitle: "Enhancement prompt",+ promptEnhancementModel: "Default model",+ promptEnhancementThinking: "Reasoning",+ promptEnhancementThinkingDesc:+ "Reasoning effort for the rewrite. Off is the default and the fastest.",+ promptEnhancementThinkingOff: "Off (no reasoning)",+ promptEnhancementModelFollow: "Follow the current model",+ promptEnhancementUserTemplate: "User template",+ promptEnhancementUserTemplateDesc:+ "Wraps the draft. It must include the draft variable; use the insert button to place it.",+ promptEnhancementInsertDraft: "Insert draft variable",+ promptEnhancementRestore: "Restore default",+ promptEnhancementMissingDraftVariable:+ "The user template must contain the draft variable, or the draft cannot be sent.",+ promptEnhancementSaveError: "Couldn't save the prompt-enhancement settings.",},project: {open: "Open project",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex b79a8a82a..efbd82ee3 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -1152,6 +1152,30 @@ sklm: {"fontSizeXl": "Trenta","fontSizeScale": "Escala de tamaño de texto","fontSizePercent": "{{value}}%",+ "promptEnhancementTitle": "Mejora de prompts",+ "promptEnhancementDesc":+ "Se aplica a la acción «Mejorar prompt» del compositor. El prompt del sistema es integrado; la plantilla y el modelo se pueden personalizar.",+ "promptEnhancementCustomTemplate": "Usar una plantilla propia",+ "promptEnhancementCustomTemplateDesc":+ "Reemplaza la plantilla de usuario integrada por la suya. El prompt del sistema sigue integrado.",+ "promptEnhancementCustomTemplateNeedsTemplate":+ "Guarde primero una plantilla propia; el interruptor elegirá entonces entre ella y la plantilla integrada.",+ "promptEnhancementEdit": "Editar",+ "promptEnhancementModelTitle": "Mejora de prompts",+ "promptEnhancementModel": "Modelo predeterminado",+ "promptEnhancementThinking": "Esfuerzo de razonamiento",+ "promptEnhancementThinkingDesc":+ "Esfuerzo de razonamiento para la reescritura. Desactivado es el valor predeterminado y el más rápido.",+ "promptEnhancementThinkingOff": "Desactivado",+ "promptEnhancementModelFollow": "Seguir el modelo actual",+ "promptEnhancementUserTemplate": "Plantilla de usuario",+ "promptEnhancementUserTemplateDesc":+ "Envuelve el borrador. Debe incluir la variable del borrador; use el botón de inserción.",+ "promptEnhancementInsertDraft": "Insertar variable del borrador",+ "promptEnhancementRestore": "Restaurar predeterminado",+ "promptEnhancementMissingDraftVariable":+ "La plantilla de usuario debe contener la variable del borrador; de lo contrario el borrador no puede enviarse.",+ "promptEnhancementSaveError": "No se pudo guardar la configuración de mejora de prompts.",},"project": {"open": "Abrir proyecto",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 69dad8f70..479d2c17c 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -1152,6 +1152,30 @@ sklm: {"fontSizeXl": "Trenta","fontSizeScale": "Échelle de taille du texte","fontSizePercent": "{{value}}%",+ "promptEnhancementTitle": "Amélioration du prompt",+ "promptEnhancementDesc":+ "S'applique à l'action « Améliorer le prompt » du compositeur. Le prompt système est intégré ; le modèle et le modèle de texte sont personnalisables.",+ "promptEnhancementCustomTemplate": "Utiliser un modèle personnalisé",+ "promptEnhancementCustomTemplateDesc":+ "Remplace le modèle utilisateur intégré par le vôtre. Le prompt système reste intégré.",+ "promptEnhancementCustomTemplateNeedsTemplate":+ "Enregistrez d'abord un modèle personnalisé ; l'interrupteur choisit ensuite entre celui-ci et le modèle intégré.",+ "promptEnhancementEdit": "Modifier",+ "promptEnhancementModelTitle": "Amélioration du prompt",+ "promptEnhancementModel": "Modèle par défaut",+ "promptEnhancementThinking": "Effort de raisonnement",+ "promptEnhancementThinkingDesc":+ "Effort de raisonnement pour la réécriture. Désactivé est la valeur par défaut et la plus rapide.",+ "promptEnhancementThinkingOff": "Désactivé",+ "promptEnhancementModelFollow": "Suivre le modèle actuel",+ "promptEnhancementUserTemplate": "Modèle utilisateur",+ "promptEnhancementUserTemplateDesc":+ "Encadre le brouillon. Doit contenir la variable de brouillon ; utilisez le bouton d'insertion.",+ "promptEnhancementInsertDraft": "Insérer la variable de brouillon",+ "promptEnhancementRestore": "Rétablir la valeur par défaut",+ "promptEnhancementMissingDraftVariable":+ "Le modèle utilisateur doit contenir la variable de brouillon, sinon le brouillon ne peut pas être envoyé.",+ "promptEnhancementSaveError": "Impossible d'enregistrer les paramètres d'amélioration du prompt.",},"project": {"open": "Ouvrir le projet",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 1a22aaf15..b4966e04a 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -1169,6 +1169,30 @@ sklm: {fontSizeXl: "Trenta",fontSizeScale: "텍스트 크기 배율",fontSizePercent: "{{value}}%",+ promptEnhancementTitle: "프롬프트 향상",+ promptEnhancementDesc:+ "입력창의 '프롬프트 향상' 동작에 적용됩니다. 시스템 프롬프트는 내장이며 사용자 템플릿과 모델을 사용자 지정할 수 있습니다.",+ promptEnhancementCustomTemplate: "사용자 템플릿 사용",+ promptEnhancementCustomTemplateDesc:+ "내장 사용자 템플릿을 직접 만든 템플릿으로 교체합니다. 시스템 프롬프트는 내장으로 유지됩니다.",+ promptEnhancementCustomTemplateNeedsTemplate:+ "먼저 사용자 템플릿을 저장하세요. 저장한 뒤에는 스위치로 내장 템플릿과 사용자 템플릿을 전환할 수 있습니다.",+ promptEnhancementEdit: "편집",+ promptEnhancementModelTitle: "프롬프트 향상",+ promptEnhancementModel: "기본 모델",+ promptEnhancementThinking: "추론 강도",+ promptEnhancementThinkingDesc:+ "재작성에 사용할 추론 강도입니다. 기본값은 끄기이며 가장 빠릅니다.",+ promptEnhancementThinkingOff: "끄기(추론 없음)",+ promptEnhancementModelFollow: "현재 모델 따르기",+ promptEnhancementUserTemplate: "사용자 템플릿",+ promptEnhancementUserTemplateDesc:+ "초안을 감쌉니다. 초안 변수를 반드시 포함해야 하며, 삽입 버튼으로 넣으세요.",+ promptEnhancementInsertDraft: "초안 변수 삽입",+ promptEnhancementRestore: "기본값 복원",+ promptEnhancementMissingDraftVariable:+ "사용자 템플릿에 초안 변수가 있어야 하며, 없으면 초안을 보낼 수 없습니다.",+ promptEnhancementSaveError: "프롬프트 향상 설정을 저장하지 못했습니다.",},project: {open: "프로젝트 열기",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 2bebe5f25..f5d297f17 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -1169,6 +1169,30 @@ sklm: {fontSizeXl: "Trenta",fontSizeScale: "Metin ölçeği",fontSizePercent: "%{{value}}",+ promptEnhancementTitle: "Prompt iyileştirme",+ promptEnhancementDesc:+ "Bestekinin Promtu iyileştir eylemi için geçerlidir. Sistem promptu yerleşiktir; kullanıcı şablonu ve model özelleştirilebilir.",+ promptEnhancementCustomTemplate: "Özel şablon kullan",+ promptEnhancementCustomTemplateDesc:+ "Yerleşik kullanıcı şablonunu kendi şablonunuzla değiştirir. Sistem promptu yerleşik kalır.",+ promptEnhancementCustomTemplateNeedsTemplate:+ "Önce özel bir şablon kaydedin; ardından anahtar yerleşik şablon ile kendi şablonunuz arasında geçiş yapar.",+ promptEnhancementEdit: "Düzenle",+ promptEnhancementModelTitle: "Prompt iyileştirme",+ promptEnhancementModel: "Varsayılan model",+ promptEnhancementThinking: "Akıl yürütme",+ promptEnhancementThinkingDesc:+ "Yeniden yazma için akıl yürütme düzeyi. Varsayılan kapalıdır ve en hızlısıdır.",+ promptEnhancementThinkingOff: "Kapalı (akıl yürütme yok)",+ promptEnhancementModelFollow: "Geçerli modeli izle",+ promptEnhancementUserTemplate: "Kullanıcı şablonu",+ promptEnhancementUserTemplateDesc:+ "Taslağı sarar. Taslak değişkenini içermelidir; ekleme düğmesini kullanın.",+ promptEnhancementInsertDraft: "Taslak değişkenini ekle",+ promptEnhancementRestore: "Varsayılanı geri yükle",+ promptEnhancementMissingDraftVariable:+ "Kullanıcı şablonu taslak değişkenini içermelidir, aksi halde taslak gönderilemez.",+ promptEnhancementSaveError: "Prompt iyileştirme ayarları kaydedilemedi.",},project: {open: "Proje aç",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 17b8bca5d..c52a38a73 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -1153,6 +1153,30 @@ sklm: {fontSizeXl: "超超大杯",fontSizeScale: "文字缩放比例",fontSizePercent: "{{value}}%",+ promptEnhancementTitle: "提示词增强",+ promptEnhancementDesc:+ "作用于输入框的「增强提示词」操作。系统提示词为内置,可自定义用户模板与增强模型。",+ promptEnhancementCustomTemplate: "使用自定义提示词",+ promptEnhancementCustomTemplateDesc:+ "用你自己的用户模板替换内置模板。系统提示词保持内置。",+ promptEnhancementCustomTemplateNeedsTemplate:+ "请先保存自定义模板;保存后即可用开关在内置模板与自定义模板之间切换。",+ promptEnhancementEdit: "编辑",+ promptEnhancementModelTitle: "增强提示词",+ promptEnhancementModel: "默认模型",+ promptEnhancementThinking: "思考强度",+ promptEnhancementThinkingDesc:+ "改写时使用的思考强度。默认关闭,最快。",+ promptEnhancementThinkingOff: "关闭思考",+ promptEnhancementModelFollow: "跟随当前模型",+ promptEnhancementUserTemplate: "用户模板",+ promptEnhancementUserTemplateDesc:+ "用于包裹草稿。必须包含草稿变量,请用插入按钮写入。",+ promptEnhancementInsertDraft: "插入草稿变量",+ promptEnhancementRestore: "恢复默认",+ promptEnhancementMissingDraftVariable:+ "用户模板必须包含草稿变量,否则草稿无法发送给模型。",+ promptEnhancementSaveError: "无法保存提示词增强设置。",},project: {open: "打开项目",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 035f7a13f..ab3ed89c7 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -1153,6 +1153,30 @@ sklm: {fontSizeXl: "超超大杯",fontSizeScale: "文字縮放比例",fontSizePercent: "{{value}}%",+ promptEnhancementTitle: "提示詞增強",+ promptEnhancementDesc:+ "作用於輸入框的「增強提示詞」操作。系統提示詞為內建,可自訂使用者範本與增強模型。",+ promptEnhancementCustomTemplate: "使用自訂提示詞",+ promptEnhancementCustomTemplateDesc:+ "用你自己的使用者範本取代內建範本。系統提示詞維持內建。",+ promptEnhancementCustomTemplateNeedsTemplate:+ "請先儲存自訂範本;儲存後即可用開關在內建範本與自訂範本之間切換。",+ promptEnhancementEdit: "編輯",+ promptEnhancementModelTitle: "增強提示詞",+ promptEnhancementModel: "預設模型",+ promptEnhancementThinking: "思考強度",+ promptEnhancementThinkingDesc:+ "改寫時使用的思考強度。預設關閉,最快。",+ promptEnhancementThinkingOff: "關閉思考",+ promptEnhancementModelFollow: "跟隨目前模型",+ promptEnhancementUserTemplate: "使用者範本",+ promptEnhancementUserTemplateDesc:+ "用於包裹草稿。必須包含草稿變數,請用插入按鈕寫入。",+ promptEnhancementInsertDraft: "插入草稿變數",+ promptEnhancementRestore: "恢復預設",+ promptEnhancementMissingDraftVariable:+ "使用者範本必須包含草稿變數,否則草稿無法傳送給模型。",+ promptEnhancementSaveError: "無法儲存提示詞增強設定。",},project: {open: "開啟專案",diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.tsindex b1bd6b3b9..cb2d96d4f 100644--- a/packages/shared/src/types/settings.ts+++ b/packages/shared/src/types/settings.ts@@ -7,6 +7,7 @@ import type { Mode } from "./common.js";import type { GlobalPermissionMode } from "./permissions.js";import type { PluginMarketSource } from "./plugins.js";import type { SpeechSettings } from "./speech.js";+import type { ThinkingLevel } from "./models.js";export type ThemePreference = "system" | "light" | "dark" | `plugin:${string}`;@@ -28,7 +29,37 @@ export type AppSettings = {defaultMode: Mode;/** Configured command shell for the agent Bash protocol tool. */defaultCommandShell?: CommandShellId;- /** Global permission mode default; sessions with `inherit` follow this. */+ /**+ * Whether the stored user template replaces the built-in one (ADR 0121).+ * Absent means off. Turning it off keeps `promptEnhancementUserTemplate` so+ * toggling back on restores the user's text instead of discarding it.+ */+ promptEnhancementCustomTemplate?: boolean;+ /**+ * Composer prompt-enhancement user-template override (ADR 0121). Applied only+ * while `promptEnhancementCustomTemplate` is on. Host-core rejects a non-blank+ * value without `{{draft}}` and any value beyond+ * `PROMPT_ENHANCEMENT_TEMPLATE_MAX_LENGTH`.+ *+ * The system prompt is intentionally not overridable: it carries the rewrite+ * contract the feature is specified against.+ */+ promptEnhancementUserTemplate?: string;+ /**+ * Model the one-shot enhancement runs on. Absent means "follow the Composer's+ * current model". When the pinned pair is unusable, main falls back to the+ * Composer model and logs a warning (ADR 0121).+ */+ promptEnhancementProviderId?: string;+ promptEnhancementModelId?: string;+ /**+ * Reasoning effort for the one-shot enhancement. Absent means `off`: the+ * enhancement never inherits the session's level, because a rewrite rarely+ * benefits from reasoning and reasoning is the slow path. The value is clamped+ * onto the resolved model's ladder, and switching model re-clamps it, so a+ * stored level is always one the model can run.+ */+ promptEnhancementThinkingLevel?: ThinkingLevel;defaultPermissionMode?: GlobalPermissionMode;theme: ThemePreference;/** UI language; `auto` (and absent) follows the OS locale. */