Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(composer): abort enhancement timeout and drop the 800-char cap

vastsa9a94ec9a0481
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index ae0b1c1f2..320f118f3 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -177,11 +177,12 @@ export function registerAgentIpc({
: {}),
} as RuntimeProviderConfig;
// 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(
+ // promise open indefinitely. Aborting is best-effort (the transport only
+ // consults the signal between provider retries); racing the promise is what
+ // actually guarantees the caller is released on time.
+ const enhancedDraft = await withPromptEnhancementTimeout((signal) =>
enhancePromptDraft(runtimeProvider, draft, launch.sidecarParams.thinkingLevel, {
+ signal,
sessionId: launchSessionId,
customTemplate: settings?.promptEnhancementCustomTemplate === true,
userTemplate:
diff --git a/apps/desktop/electron/main/prompt-enhancement-timeout.ts b/apps/desktop/electron/main/prompt-enhancement-timeout.ts
index 54155d145..f41621e09 100644
--- a/apps/desktop/electron/main/prompt-enhancement-timeout.ts
+++ b/apps/desktop/electron/main/prompt-enhancement-timeout.ts
@@ -7,6 +7,9 @@
* gateway holds the renderer's promise open indefinitely, and the provider
* retry budget alone can already spend about a minute before giving up.
*
+ * The helper still aborts: a timeout that only races leaves the provider call
+ * running, which burns tokens and can overlap the user's next click.
+ *
* Kept in its own module (no Electron or pi-ai imports) so the behavior is
* directly testable.
*/
@@ -24,33 +27,43 @@ export function promptEnhancementTimeoutError(
): 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.`,
+ `Prompt enhancement timed out after ${Math.round(timeoutMs / 1000)}s. Try again, or pick a faster enhancement model in Settings.`,
),
{ errorCode: "TIMEOUT" as const },
);
}
/**
- * Resolve with `work`, or reject with a `TIMEOUT` error after `timeoutMs`.
+ * Run `start` with an abort signal, or reject with `TIMEOUT` 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:
+ * A failure from `start` itself passes through unchanged; only an unanswered
+ * request becomes a timeout. Abort after timeout is best-effort; the race is
+ * what frees the caller. 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>,
+ start: (signal: AbortSignal) => Promise<T>,
timeoutMs: number = PROMPT_ENHANCEMENT_TIMEOUT_MS,
): Promise<T> {
+ const controller = new AbortController();
+ const work = start(controller.signal);
return new Promise<T>((resolve, reject) => {
- const timer = setTimeout(() => reject(promptEnhancementTimeoutError(timeoutMs)), timeoutMs);
+ let settled = false;
+ const finish = (action: () => void) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ action();
+ };
+ const timer = setTimeout(() => {
+ controller.abort();
+ finish(() => reject(promptEnhancementTimeoutError(timeoutMs)));
+ }, timeoutMs);
work.then(
- (value) => {
- clearTimeout(timer);
- resolve(value);
- },
+ (value) => finish(() => resolve(value)),
(error) => {
- clearTimeout(timer);
- reject(error);
+ if (controller.signal.aborted) return;
+ finish(() => reject(error));
},
);
});
diff --git a/apps/desktop/src/components/settings/EnhancementModelCard.tsx b/apps/desktop/src/components/settings/EnhancementModelCard.tsx
index dc951ca99..01880a076 100644
--- a/apps/desktop/src/components/settings/EnhancementModelCard.tsx
+++ b/apps/desktop/src/components/settings/EnhancementModelCard.tsx
@@ -102,7 +102,17 @@ export function EnhancementModelCard() {
);
// 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];
+ // A model without reasoning still lists `off` so the closed trigger does not
+ // show the raw id, and the row is disabled.
+ const noReasoning =
+ Boolean(reasoningProvider) && reasoningProvider?.supportsReasoning !== true;
+ const levelOptions = noReasoning
+ ? (["off"] as ThinkingLevel[])
+ : reasoningProvider
+ ? reasoningLevels.length > 0
+ ? reasoningLevels
+ : (["off"] as ThinkingLevel[])
+ : [...THINKING_LEVELS];
const storedReasoning = settings?.promptEnhancementThinkingLevel ?? "off";
const reasoning = useMemo(() => {
if (!reasoningProvider) return storedReasoning;
@@ -155,15 +165,23 @@ export function EnhancementModelCard() {
<SettingsRow
title={t("settings.promptEnhancementModel")}
description={
- pinnedProvider && settings.promptEnhancementModelId ? (
+ settings.promptEnhancementProviderId && settings.promptEnhancementModelId ? (
<span className="model-default-value">
- <span className="model-default-provider">{pinnedProvider.name}</span>
+ <span className="model-default-provider">
+ {pinnedProvider?.name ?? settings.promptEnhancementProviderId}
+ </span>
<span className="model-default-sep" aria-hidden>
·
</span>
<span className="model-default-model font-mono">
{settings.promptEnhancementModelId}
</span>
+ {!pinnedProvider || orphanPin ? (
+ <span className="model-default-empty">
+ {" "}
+ {t("settings.promptEnhancementModelUnavailable")}
+ </span>
+ ) : null}
</span>
) : (
<span className="model-default-empty">
@@ -282,7 +300,7 @@ export function EnhancementModelCard() {
<SettingsMenuSelect
label={t("settings.promptEnhancementThinking")}
value={reasoning}
- disabled={levelOptions.length === 0}
+ disabled={noReasoning}
options={levelOptions.map((level) => ({
id: level,
label: level === "off" ? t("settings.promptEnhancementThinkingOff") : level,
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
index b976e341f..7aa8bbaf3 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
@@ -164,7 +164,10 @@ export function useComposerSubmit({
}
const typed = error as Error & { code?: string };
setEnhancementError({
- message: typed.message || t("chat.enhancementFailed"),
+ message:
+ typed.code === "TIMEOUT"
+ ? t("chat.enhancementTimeout")
+ : typed.message || t("chat.enhancementFailed"),
code: typed.code || "PROMPT_ENHANCEMENT_FAILED",
});
} finally {
diff --git a/apps/desktop/src/features/settings/prompt-enhancement-card.tsx b/apps/desktop/src/features/settings/prompt-enhancement-card.tsx
index 0df91eef7..20f61b108 100644
--- a/apps/desktop/src/features/settings/prompt-enhancement-card.tsx
+++ b/apps/desktop/src/features/settings/prompt-enhancement-card.tsx
@@ -23,9 +23,9 @@ import type { AppSettings } from "@pi-desktop/shared";
import {
PROMPT_ENHANCEMENT_DEFAULT_USER_TEMPLATE,
PROMPT_ENHANCEMENT_DRAFT_VARIABLE,
+ PROMPT_ENHANCEMENT_TEMPLATE_MAX_LENGTH,
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";
@@ -127,6 +127,8 @@ function PromptEnhancementEditorSheet({
const templateMissingVariable =
templateDraft.trim().length > 0 &&
!isValidPromptEnhancementUserTemplate(templateDraft);
+ const templateTooLong =
+ [...templateDraft].length > PROMPT_ENHANCEMENT_TEMPLATE_MAX_LENGTH;
const dirty =
templateDraft !== (savedTemplate || PROMPT_ENHANCEMENT_DEFAULT_USER_TEMPLATE);
@@ -163,7 +165,7 @@ function PromptEnhancementEditorSheet({
};
const save = async () => {
- if (templateMissingVariable || saving) return;
+ if (templateMissingVariable || templateTooLong || saving) return;
setSaving(true);
setSaveError(false);
try {
@@ -215,7 +217,10 @@ function PromptEnhancementEditorSheet({
className="ext-sheet-close"
ariaLabel={t("common.close")}
tooltip={t("common.close")}
- onClick={onClose}
+ onClick={() => {
+ if (!saving) onClose();
+ }}
+ disabled={saving}
>
<IconX size={14} />
</TooltipButton>
@@ -235,7 +240,7 @@ function PromptEnhancementEditorSheet({
rows={8}
onChange={(event) => setTemplateDraft(event.target.value)}
aria-label={t("settings.promptEnhancementUserTemplate")}
- aria-invalid={templateMissingVariable}
+ aria-invalid={templateMissingVariable || templateTooLong}
spellCheck={false}
autoCorrect="off"
autoCapitalize="off"
@@ -247,6 +252,11 @@ function PromptEnhancementEditorSheet({
{t("settings.promptEnhancementMissingDraftVariable")}
</span>
) : null}
+ {templateTooLong ? (
+ <span className="settings-command-shell-state error" role="status">
+ {t("settings.promptEnhancementTooLong")}
+ </span>
+ ) : null}
<div className="settings-panel-actions">
<Button variant="secondary" type="button" onClick={insertDraftVariable}>
@@ -272,7 +282,7 @@ function PromptEnhancementEditorSheet({
<Button
variant="primary"
type="button"
- disabled={!dirty || saving || templateMissingVariable}
+ disabled={!dirty || saving || templateMissingVariable || templateTooLong}
onClick={() => void save()}
>
{saving ? t("common.saving") : t("common.save")}
diff --git a/apps/desktop/test/prompt-enhancement.test.mjs b/apps/desktop/test/prompt-enhancement.test.mjs
index 4c09c2909..c448730f3 100644
--- a/apps/desktop/test/prompt-enhancement.test.mjs
+++ b/apps/desktop/test/prompt-enhancement.test.mjs
@@ -26,10 +26,11 @@ 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, /withPromptEnhancementTimeout\(\(signal\) =>/);
+ assert.match(main, /signal,/);
assert.match(main, /sessionId: launchSessionId/);
assert.match(main, /resolveAuth: \(\) => vendorOAuth\.resolveAuth/);
assert.match(runtime, /completeOneShot\(/);
@@ -67,6 +68,7 @@ test("prompt enhancement has complete English-first locale coverage", () => {
assert.match(source, /enhancingPrompt:/);
assert.match(source, /undoEnhancement:/);
assert.match(source, /enhancementFailed:/);
+ assert.match(source, /enhancementTimeout:/);
assert.match(source, /dismissEnhancementError:/);
}
});
@@ -106,8 +108,10 @@ test("prompt-enhancement settings expose templates, restore, and the draft varia
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.
+ // A save that would drop the draft variable or exceed the host-core bound
+ // is refused before it is sent.
assert.match(card, /templateMissingVariable/);
+ assert.match(card, /templateTooLong/);
assert.match(card, /isValidPromptEnhancementUserTemplate/);
// The defaults live in shared so the settings page can display the same text
@@ -139,6 +143,7 @@ test("prompt-enhancement locale coverage includes the settings copy", () => {
"promptEnhancementCustomTemplateDesc",
"promptEnhancementCustomTemplateNeedsTemplate",
"promptEnhancementMissingDraftVariable",
+ "promptEnhancementTooLong",
"promptEnhancementSaveError",
]) {
assert.match(source, new RegExp(`${key}:`));
@@ -151,21 +156,29 @@ test("an enhancement request is released when the provider never answers", async
// 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(() => {});
+ let seenSignal;
await assert.rejects(
- withPromptEnhancementTimeout(never, 40),
+ withPromptEnhancementTimeout((signal) => {
+ seenSignal = signal;
+ return never;
+ }, 40),
(error) => {
assert.equal(error.errorCode, "TIMEOUT");
assert.match(error.message, /timed out after/);
return true;
},
);
+ assert.equal(seenSignal?.aborted, true, "timeout must abort the in-flight request");
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");
+ assert.equal(
+ await withPromptEnhancementTimeout(() => Promise.resolve("ok"), 5000),
+ "ok",
+ );
await assert.rejects(
- withPromptEnhancementTimeout(Promise.reject(new Error("provider 500")), 5000),
+ withPromptEnhancementTimeout(() => Promise.reject(new Error("provider 500")), 5000),
/provider 500/,
);
});
@@ -192,6 +205,7 @@ test("the enhancement model and reasoning live on their own Model-page card", as
assert.match(card, /promptEnhancementProviderId/);
assert.match(card, /promptEnhancementModelId/);
assert.match(card, /promptEnhancementModelFollow/);
+ assert.match(card, /promptEnhancementModelUnavailable/);
assert.match(card, /pickModel/);
// The rows use the shared settings row, not an ad-hoc layout.
@@ -206,10 +220,9 @@ test("the reasoning row follows the selected model's real ladder", async () => {
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\}/);
+ // A pinned model without reasoning still lists `off` and disables the row.
+ assert.match(card, /noReasoning/);
+ assert.match(card, /disabled=\{noReasoning\}/);
// 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\)/);
@@ -223,6 +236,7 @@ test("the model-page copy exists in both reference locales", () => {
"promptEnhancementModelTitle",
"promptEnhancementModel",
"promptEnhancementModelFollow",
+ "promptEnhancementModelUnavailable",
"promptEnhancementThinking",
"promptEnhancementThinkingDesc",
"promptEnhancementThinkingOff",
diff --git a/docs/adr/0121-one-shot-composer-prompt-enhancement.md b/docs/adr/0121-one-shot-composer-prompt-enhancement.md
index b99b7c2f4..f1eb3b234 100644
--- a/docs/adr/0121-one-shot-composer-prompt-enhancement.md
+++ b/docs/adr/0121-one-shot-composer-prompt-enhancement.md
@@ -52,11 +52,12 @@ The enhancement carries its own reasoning level through
`AppSettings.promptEnhancementThinkingLevel`, defaulting to `off`, and never
inherits the conversation's effort: a rewrite rarely benefits from reasoning and
reasoning is the slow path. The row lists only the levels the selected model
-supports and disables itself when that set is empty, resolving them exactly as a
-turn does (binding, then catalog, then provider default). The chosen level is
-clamped by that ladder, and switching model re-clamps the stored value. One request is bounded by a 60-second ceiling, because the
-provider retry budget alone can spend about a minute and the renderer has no
-cancel; expiry fails with `TIMEOUT` rather than retrying on the session model.
+supports and still shows `Off (no reasoning)` when that set is empty, resolving
+them exactly as a turn does (binding, then catalog, then provider default). The
+chosen level is clamped by that ladder, and switching model re-clamps the stored
+value. One request is bounded by a 60-second ceiling: expiry aborts the
+in-flight call (best-effort) and races the promise so the renderer is released,
+then fails with `TIMEOUT` rather than retrying on the session model.
The enhancement model and its reasoning level are configured on the Model
configuration page, in their own card titled "Enhancement prompt", because both
diff --git a/docs/spec/04-ux/12-prompt-enhancement.md b/docs/spec/04-ux/12-prompt-enhancement.md
index e4b33ba5c..5d79a753b 100644
--- a/docs/spec/04-ux/12-prompt-enhancement.md
+++ b/docs/spec/04-ux/12-prompt-enhancement.md
@@ -51,7 +51,9 @@ tags so draft text reads as content to improve rather than as instructions. The
system prompt is not user-editable and states the role, the rewrite principles,
an explicit do-not list (including leaving code, commands, file paths,
identifiers, and other proper nouns exactly as written), language-following
-rules that forbid language meta notes, a length brake, and the output contract.
+rules that forbid language meta notes, a length brake (do not expand beyond
+roughly twice the draft's length; a long draft may stay long), and the output
+contract.
No prior conversation, tools, attachments, or session state are included. The
renderer removes its inline file-reference chip tokens before the request and
@@ -62,13 +64,14 @@ the existing bounded retry controller. When the resolved provider is OpenCode Go
(or another `opencode.ai` host), the one-shot forwards the Composer session id
as `x-opencode-session`; a request with no session gets a per-call id. Model
output is consumed as plain text, has one matching pair of wrapping quotation
-marks removed, and is trimmed. Empty or whitespace-only output is a
-`PROMPT_ENHANCEMENT_EMPTY` failure.
-
-The handler bounds one request with a 60-second ceiling. The provider retry
-budget alone can spend about a minute, and the renderer offers no cancel, so on
-expiry the action fails with `TIMEOUT` and a message naming the budget and the
-setting to change. It does not silently retry on the session model: the user
+marks removed, has a leading rewrite label such as `Enhanced:` stripped, and is
+trimmed. Empty or whitespace-only output is a `PROMPT_ENHANCEMENT_EMPTY`
+failure.
+
+The handler bounds one request with a 60-second ceiling. On expiry it aborts
+the in-flight request (best-effort: the transport consults the signal between
+provider retries) and races the promise so the caller is released. The action
+fails with `TIMEOUT`. It does not silently retry on the session model: the user
chose the pinned model, and a hidden second attempt would double the wait.
## 4. Failure and race handling
@@ -145,10 +148,11 @@ The card's model row is titled `Default model` and uses the same anchored,
searchable menu as the Defaults card's row, so the page shows one kind of model
picker. Both rows therefore read `Default model`; the card heading is what
separates the conversation's default from the enhancement's. When
-`promptEnhancementProviderId` is set, main prefers that pin and logs a warning
-plus falls back to the Composer's current model if the pin cannot be resolved: a
-stale pin is a preference that cannot be honoured, never a failure that disables
-the action.
+`promptEnhancementProviderId` is set, the row still shows that pin even if the
+provider is gone or disabled, with an unavailable hint. Main prefers the pin
+and logs a warning plus falls back to the Composer's current model if it cannot
+be resolved: a stale pin is a preference that cannot be honoured, never a
+failure that disables the action.
The reasoning row lists the levels the selected model actually supports, using
the same resolution the Composer applies to a turn: the model binding's
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index a933aa49b..56be036ac 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -11078,12 +11078,6 @@ are withdrawn with ADR 0165.
chip. 2) Click `Enhance prompt`. 3) Observe the request and the updated
Composer draft. 4) Send the enhanced draft and inspect the dispatched
attachment metadata.
-- **Expected**: The Sparkles action is enabled with the image chip present.
- The one-shot request contains only the visible prompt text, completes
- successfully, and rewrites that text. The image chip remains at the front of
- the draft, remains removable, and is dispatched exactly once with the
- enhanced prompt. Enhancement does not create a transcript row or alter the
- attachment bytes.
- **Expected**: The Sparkles action is enabled with the image chip present.
The one-shot request contains only the visible prompt text, completes
successfully, and rewrites that text. The image chip remains at the front of
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index c6bdb14e3..f8be7e013 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -5995,7 +5995,7 @@ that was sitting at the bottom — including after the turn had finished.
- The default enhancement prompt moves from one conservative sentence to a
structured system prompt plus a templated user message: role, analysis,
rewrite principles, an explicit do-not list, language-following rules that
- forbid language meta notes, a length brake, and an output contract. The old
+ forbid language meta notes, a length brake (about twice the draft; no 800-character cap), and an output contract. The old
`If the draft is already good, return it with at most minor polish` clause is
removed: it made the action look inert on short drafts, which is the reported
complaint.
@@ -6049,8 +6049,9 @@ that was sitting at the bottom — including after the turn had finished.
reasoning, and reasoning is the slow path, so "follow the session" would
silently opt every enhancement on a reasoning model into the slowest setting.
The level is clamped by the resolved model's capabilities.
-- One enhancement request is bounded by a 60-second ceiling and fails with
- `TIMEOUT` naming the budget, instead of retrying on the session model. The
+- One enhancement request is bounded by a 60-second ceiling: expiry aborts the
+ in-flight call (best-effort) and races the promise so the renderer is released,
+ then fails with `TIMEOUT` instead of retrying on the session model. The
provider retry budget can already spend about a minute, the renderer has no
cancel, and a hidden second attempt would double the wait. This is a behavior
change for a slow provider: the action now fails visibly instead of hanging.
diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.md
index 283d99ae7..e6b3ac867 100644
--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md
+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md
@@ -89,7 +89,6 @@
工具栏上下文环及其弹层是以剩余容量还是已用容量为引导数值;默认为剩余。
该阈值决定纯文本粘贴何时转为会话临时文件,默认值为 600 个字符,
接受 1 至 1,000,000 的整数。
-- **提示词增强**卡控制输入框的「增强提示词」操作(ADR 0121)。卡片上有「使用自定义提示词」
- **提示词增强**卡控制输入框的「增强提示词」操作(ADR 0121)。卡片上有「使用自定义提示词」
开关,以及子智能体行所用的设置图标按钮,点击后打开编辑弹窗(沿用子智能体编辑器的
模式)。开关决定已存模板是否生效,在尚未保存模板时禁用,保存模板后自动打开;关闭
@@ -100,8 +99,9 @@
模型层面的决定,且模型选择器需要「标题/当前值/控件」的形态,而「默认项」的行形态
无法承载。其「默认模型」行使用与「默认项」卡片相同行的锚定可搜索菜单;为空表示
「跟随输入框当前模型」。因此会有两行都题为「默认模型」,靠各自卡片标题区分。思考
- 强度行是一个菜单选择器,列出所选模型实际支持的等级(不支持时该行禁用),默认「关闭
+ 强度行是一个菜单选择器,列出所选模型实际支持的等级(不支持时该行仍显示「关闭思考」并禁用),默认「关闭
思考」,且不提供「跟随会话」项。设置搜索会索引该卡与这两行。
+- **语音**卡:默认转写/朗读绑定(`AppSettings.speech`)。未配置时 Composer 对应入口禁用。Whisper / TTS 不进聊天模型列表。见 `20-speech.md`。
- **默认项**卡中的**命令 Shell**行:主机发现的本机 PowerShell 5.1、PowerShell 7、
cmd、Git Bash 和 ID 为 `windows-powershell`、`windows-pwsh`、`cmd`、`git-bash`
的 Bash 和
diff --git a/docs/zh-CN/spec/04-ux/12-prompt-enhancement.md b/docs/zh-CN/spec/04-ux/12-prompt-enhancement.md
index 42428fbf3..ff77ba18c 100644
--- a/docs/zh-CN/spec/04-ux/12-prompt-enhancement.md
+++ b/docs/zh-CN/spec/04-ux/12-prompt-enhancement.md
@@ -42,19 +42,22 @@ Electron 主进程使用与 agent 回合相同的运行时启动解析器解析
默认模板把草稿放在 `<draft>` 标签内,使草稿文本被当作待改进的内容、而不是
指令。系统提示词不可由用户编辑,它规定了角色、改写原则、明确的禁止清单(包括
代码、命令、文件路径、标识符等专有名词必须原样保留)、禁止输出语言元注释的
-语言跟随规则、长度刹车与输出契约。
+语言跟随规则、长度刹车(不要扩到草稿约两倍以上;长草稿可以保持长,不要为了短而压短)
+与输出契约。
不包含任何先前对话、工具、附件或会话状态。渲染层在请求前移除内联文件引用的
占位符 token,并在收到文本结果后按原顺序与相对位置恢复这些文件引用块;不信任
模型会保留渲染层的私有标记。所选思考等级会传给 pi-ai,提供商初始化的重试沿用
既有的有界重试控制器。当解析出的提供商为 OpenCode Go(或其他 `opencode.ai`
主机)时,一次性请求会把输入框会话 id 作为 `x-opencode-session` 转发;没有会话
-的请求会获得一个按调用生成的 id。模型输出按纯文本消费,去掉一对包裹引号后
-trim。输出为空或仅含空白字符时,记为 `PROMPT_ENHANCEMENT_EMPTY` 失败。
+的请求会获得一个按调用生成的 id。模型输出按纯文本消费,去掉一对包裹引号、去掉
+开头的 `Enhanced:` 一类改写标签后 trim。输出为空或仅含空白字符时,记为
+`PROMPT_ENHANCEMENT_EMPTY` 失败。
-处理器为单次请求设置 60 秒上限。仅提供商重试预算就可能耗掉约一分钟,而渲染层没有
-取消入口,因此超时后该操作以 `TIMEOUT` 失败,并给出写明预算与可改设置的消息。它不会
-静默改用会话模型重试:模型是用户指定的,隐藏的第二次尝试会让等待时间翻倍。
+处理器为单次请求设置 60 秒上限。超时后会 abort 进行中的请求(尽力而为:传输层只在
+提供商重试之间查看 abort 信号),并与 promise 竞速以保证调用方被释放。该操作以
+`TIMEOUT` 失败。它不会静默改用会话模型重试:模型是用户指定的,隐藏的第二次尝试会
+让等待时间翻倍。
## 4. 失败与竞态处理
@@ -112,8 +115,8 @@ trim。输出为空或仅含空白字符时,记为 `PROMPT_ENHANCEMENT_EMPTY`
| `promptEnhancementThinkingLevel` | `off` |
该卡片的模型行标题为「默认模型」,使用与「默认项」卡片相同行的锚定可搜索菜单,因此该页只呈现一种模型选择交互。
-当设置了 `promptEnhancementProviderId` 时,主进程优先使用该指定项;若无法解析,则记录
-警告并回退到输入框当前模型:过期的指定项只是无法满足的偏好,绝不会成为使该操作不可用
+当设置了 `promptEnhancementProviderId` 时,该行仍显示该指定项(提供商已消失或已禁用时附不可用提示)。
+主进程优先使用该指定项;若无法解析,则记录警告并回退到输入框当前模型:过期的指定项只是无法满足的偏好,绝不会成为使该操作不可用
的失败。
思考强度行列出的,是所选模型**实际支持**的等级,采用的解析方式与 Composer 对一次回合
diff --git a/packages/agent-runtime/src/prompt-enhancement.test.ts b/packages/agent-runtime/src/prompt-enhancement.test.ts
index c1f4fdffb..5ce46b57f 100644
--- a/packages/agent-runtime/src/prompt-enhancement.test.ts
+++ b/packages/agent-runtime/src/prompt-enhancement.test.ts
@@ -10,6 +10,7 @@ import {
import {
enhancePromptDraft,
promptEnhancementContext,
+ stripEnhancementDecorations,
stripWrappingQuotes,
} from "./prompt-enhancement.js";
import type { RuntimeProviderConfig } from "./provider-binding.js";
@@ -196,3 +197,24 @@ describe("stripWrappingQuotes", () => {
expect(stripWrappingQuotes(" plain text ")).toBe("plain text");
});
});
+
+describe("stripEnhancementDecorations", () => {
+ it("strips a leading rewrite label after unquoting", () => {
+ expect(stripEnhancementDecorations('Enhanced: fix the login bug')).toBe(
+ "fix the login bug",
+ );
+ expect(stripEnhancementDecorations('"Output: 请审查这段代码"')).toBe(
+ "请审查这段代码",
+ );
+ expect(stripEnhancementDecorations("增强:请说明要处理的对象")).toBe(
+ "请说明要处理的对象",
+ );
+ });
+
+ it("leaves a prompt that is not a label prefix unchanged", () => {
+ expect(stripEnhancementDecorations("Fix the login bug: identify the path.")).toBe(
+ "Fix the login bug: identify the path.",
+ );
+ });
+});
+
diff --git a/packages/agent-runtime/src/prompt-enhancement.ts b/packages/agent-runtime/src/prompt-enhancement.ts
index 14b2c3e33..5a39350d0 100644
--- a/packages/agent-runtime/src/prompt-enhancement.ts
+++ b/packages/agent-runtime/src/prompt-enhancement.ts
@@ -79,6 +79,17 @@ export function stripWrappingQuotes(text: string): string {
return trimmed;
}
+/**
+ * Few-shot examples used to teach `Enhanced:` / `Output:` labels. Strip a
+ * leading copy of that label so it cannot land in the Composer.
+ */
+const LEADING_REWRITE_LABEL =
+ /^(?:enhanced|output|after|rewrite|rewritten|增强(?:提示词)?|輸出|输出|改写|改寫)\s*[::]\s*/i;
+
+export function stripEnhancementDecorations(text: string): string {
+ return stripWrappingQuotes(text).replace(LEADING_REWRITE_LABEL, "").trim();
+}
+
/**
* Run one independent completion with no session history or tools.
* Provider setup retries follow the same controller as the agent runtime.
@@ -101,7 +112,7 @@ export async function enhancePromptDraft(
emptyErrorMessage: "The model returned an empty enhanced draft.",
},
);
- const stripped = stripWrappingQuotes(result.text);
+ const stripped = stripEnhancementDecorations(result.text);
if (!stripped) {
// A quote-only answer is not a usable rewrite: keep the same terminal
// classification the empty-completion path uses.
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 3796a38c6..95f07f471 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -247,6 +247,8 @@ export const de = {
"speakSaved": "Gesprochene Audio gespeichert unter {{path}}",
"undoEnhancement": "Verbesserung rückgängig machen",
"enhancementFailed": "Eingabeaufforderung zur Verbesserung fehlgeschlagen",
+ "enhancementTimeout":
+ "Die Umschreibung hat zu lange gedauert. Erneut versuchen oder in den Einstellungen ein schnelleres Modell wählen.",
"dismissEnhancementError": "Verbesserungsfehler verwerfen",
sendWhileRunning: "Folgenachricht senden · {{shortcut}} zum Lenken",
steeringUnavailable: "Diese Runde nimmt keine weiteren Eingaben an. Dein Entwurf wurde behalten.",
@@ -1197,6 +1199,8 @@ sklm: {
"Denkaufwand für die Umschreibung. Standard ist Aus und am schnellsten.",
"promptEnhancementThinkingOff": "Aus (kein Denken)",
"promptEnhancementModelFollow": "Aktuellem Modell folgen",
+ "promptEnhancementModelUnavailable":
+ "Nicht verfügbar — die Verbesserung fällt auf das aktuelle Modell zurück",
"promptEnhancementUserTemplate": "Benutzer-Vorlage",
"promptEnhancementUserTemplateDesc":
"Umschließt den Entwurf. Muss die Entwurfsvariable enthalten; fügen Sie sie über die Schaltfläche ein.",
@@ -1204,6 +1208,7 @@ sklm: {
"promptEnhancementRestore": "Standard wiederherstellen",
"promptEnhancementMissingDraftVariable":
"Die Benutzer-Vorlage muss die Entwurfsvariable enthalten, sonst kann der Entwurf nicht gesendet werden.",
+ "promptEnhancementTooLong": "Die Nutzervorlage darf höchstens 8000 Zeichen haben.",
"promptEnhancementSaveError": "Die Prompt-Verbesserungseinstellungen konnten nicht gespeichert werden.",
},
"project": {
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 944c1b43c..54af6f8a2 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -254,6 +254,8 @@ export const en = {
speakSaved: "Saved spoken audio to {{path}}",
undoEnhancement: "Undo enhancement",
enhancementFailed: "Prompt enhancement failed",
+ enhancementTimeout:
+ "The rewrite took too long. Try again, or pick a faster enhancement model in Settings.",
dismissEnhancementError: "Dismiss enhancement error",
sendWhileRunning: "Send follow-up · {{shortcut}} to steer",
steeringUnavailable: "This turn can no longer accept steering. Your draft was kept.",
@@ -1216,6 +1218,8 @@ sklm: {
"Reasoning effort for the rewrite. Off is the default and the fastest.",
promptEnhancementThinkingOff: "Off (no reasoning)",
promptEnhancementModelFollow: "Follow the current model",
+ promptEnhancementModelUnavailable:
+ "Unavailable — enhance will fall back to the current model",
promptEnhancementUserTemplate: "User template",
promptEnhancementUserTemplateDesc:
"Wraps the draft. It must include the draft variable; use the insert button to place it.",
@@ -1223,6 +1227,7 @@ sklm: {
promptEnhancementRestore: "Restore default",
promptEnhancementMissingDraftVariable:
"The user template must contain the draft variable, or the draft cannot be sent.",
+ promptEnhancementTooLong: "The user template must be at most 8000 characters.",
promptEnhancementSaveError: "Couldn't save the prompt-enhancement settings.",
},
project: {
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 6f8020e29..4101ad99c 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -247,6 +247,8 @@ export const es = {
"speakSaved": "Audio guardado en {{path}}",
"undoEnhancement": "Deshacer mejora",
"enhancementFailed": "Error en la mejora de solicitud",
+ "enhancementTimeout":
+ "La reescritura tardó demasiado. Vuelve a intentarlo o elige un modelo más rápido en Ajustes.",
"dismissEnhancementError": "Descartar error de mejora",
sendWhileRunning: "Enviar seguimiento · {{shortcut}} para orientar",
steeringUnavailable: "Este turno ya no acepta indicaciones. Se conservó el borrador.",
@@ -1197,6 +1199,8 @@ sklm: {
"Esfuerzo de razonamiento para la reescritura. Desactivado es el valor predeterminado y el más rápido.",
"promptEnhancementThinkingOff": "Desactivado",
"promptEnhancementModelFollow": "Seguir el modelo actual",
+ "promptEnhancementModelUnavailable":
+ "No disponible: la mejora usará el modelo actual",
"promptEnhancementUserTemplate": "Plantilla de usuario",
"promptEnhancementUserTemplateDesc":
"Envuelve el borrador. Debe incluir la variable del borrador; use el botón de inserción.",
@@ -1204,6 +1208,7 @@ sklm: {
"promptEnhancementRestore": "Restaurar predeterminado",
"promptEnhancementMissingDraftVariable":
"La plantilla de usuario debe contener la variable del borrador; de lo contrario el borrador no puede enviarse.",
+ "promptEnhancementTooLong": "La plantilla de usuario no puede superar los 8000 caracteres.",
"promptEnhancementSaveError": "No se pudo guardar la configuración de mejora de prompts.",
},
"project": {
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 5a8f0fa62..ff23a74f8 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -247,6 +247,8 @@ export const fr = {
"speakSaved": "Audio enregistré dans {{path}}",
"undoEnhancement": "Annuler l'amélioration",
"enhancementFailed": "L'amélioration de l'invite a échoué",
+ "enhancementTimeout":
+ "La réécriture a pris trop de temps. Réessayez, ou choisissez un modèle plus rapide dans les réglages.",
"dismissEnhancementError": "Ignorer l'erreur d'amélioration",
sendWhileRunning: "Envoyer à la suite · {{shortcut}} pour réorienter",
steeringUnavailable: "Ce tour ne peut plus recevoir de consignes. Votre brouillon a été conservé.",
@@ -1197,6 +1199,8 @@ sklm: {
"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",
+ "promptEnhancementModelUnavailable":
+ "Indisponible — l'amélioration utilisera le modèle actuel",
"promptEnhancementUserTemplate": "Modèle utilisateur",
"promptEnhancementUserTemplateDesc":
"Encadre le brouillon. Doit contenir la variable de brouillon ; utilisez le bouton d'insertion.",
@@ -1204,6 +1208,7 @@ sklm: {
"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é.",
+ "promptEnhancementTooLong": "Le modèle utilisateur ne doit pas dépasser 8000 caractères.",
"promptEnhancementSaveError": "Impossible d'enregistrer les paramètres d'amélioration du prompt.",
},
"project": {
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index ac9ea0284..98109a2f4 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -256,6 +256,8 @@ export const ko = {
speakSaved: "음성 파일을 {{path}}에 저장했습니다",
undoEnhancement: "개선 취소",
enhancementFailed: "프롬프트 개선 실패",
+ enhancementTimeout:
+ "재작성 시간이 초과되었습니다. 다시 시도하거나 설정에서 더 빠른 향상 모델로 바꾸세요.",
dismissEnhancementError: "프롬프트 개선 오류 닫기",
sendWhileRunning: "후속 메시지 보내기 · {{shortcut}}로 방향 수정",
steeringUnavailable: "현재 턴에 지시를 추가할 수 없습니다. 초안은 유지됩니다.",
@@ -1217,6 +1219,7 @@ sklm: {
"재작성에 사용할 추론 강도입니다. 기본값은 끄기이며 가장 빠릅니다.",
promptEnhancementThinkingOff: "끄기(추론 없음)",
promptEnhancementModelFollow: "현재 모델 따르기",
+ promptEnhancementModelUnavailable: "사용할 수 없음 — 향상 시 현재 모델로 대체됩니다",
promptEnhancementUserTemplate: "사용자 템플릿",
promptEnhancementUserTemplateDesc:
"초안을 감쌉니다. 초안 변수를 반드시 포함해야 하며, 삽입 버튼으로 넣으세요.",
@@ -1224,6 +1227,7 @@ sklm: {
promptEnhancementRestore: "기본값 복원",
promptEnhancementMissingDraftVariable:
"사용자 템플릿에 초안 변수가 있어야 하며, 없으면 초안을 보낼 수 없습니다.",
+ promptEnhancementTooLong: "사용자 템플릿은 최대 8000자입니다.",
promptEnhancementSaveError: "프롬프트 향상 설정을 저장하지 못했습니다.",
},
project: {
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 4016c2323..e52b5a275 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -256,6 +256,8 @@ export const tr = {
speakSaved: "Ses {{path}} konumuna kaydedildi",
undoEnhancement: "İyileştirmeyi geri al",
enhancementFailed: "İstem iyileştirilemedi",
+ enhancementTimeout:
+ "Yeniden yazma zaman aşımına uğradı. Yeniden deneyin veya Ayarlar'dan daha hızlı bir iyileştirme modeli seçin.",
dismissEnhancementError: "İyileştirme hatasını kapat",
sendWhileRunning: "Takip mesajı gönder · {{shortcut}} ile yönlendir",
steeringUnavailable: "Bu tur artık yönlendirme kabul edemiyor. Taslağınız korundu.",
@@ -1217,6 +1219,7 @@ sklm: {
"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",
+ promptEnhancementModelUnavailable: "Kullanılamıyor — iyileştirme geçerli modele düşer",
promptEnhancementUserTemplate: "Kullanıcı şablonu",
promptEnhancementUserTemplateDesc:
"Taslağı sarar. Taslak değişkenini içermelidir; ekleme düğmesini kullanın.",
@@ -1224,6 +1227,7 @@ sklm: {
promptEnhancementRestore: "Varsayılanı geri yükle",
promptEnhancementMissingDraftVariable:
"Kullanıcı şablonu taslak değişkenini içermelidir, aksi halde taslak gönderilemez.",
+ promptEnhancementTooLong: "Kullanıcı şablonu en fazla 8000 karakter olabilir.",
promptEnhancementSaveError: "Prompt iyileştirme ayarları kaydedilemedi.",
},
project: {
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index d9f1f79fe..8a7e164fd 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -249,6 +249,7 @@ export const zhCN = {
speakSaved: "朗读音频已保存到 {{path}}",
undoEnhancement: "撤回增强",
enhancementFailed: "提示词增强失败",
+ enhancementTimeout: "改写超时。请重试,或在设置里换一个更快的增强模型。",
dismissEnhancementError: "关闭增强错误",
sendWhileRunning: "发送后续消息 · {{shortcut}} 立即转向",
steeringUnavailable: "当前轮已无法接收转向输入,草稿已保留。",
@@ -1201,6 +1202,7 @@ sklm: {
"改写时使用的思考强度。默认关闭,最快。",
promptEnhancementThinkingOff: "关闭思考",
promptEnhancementModelFollow: "跟随当前模型",
+ promptEnhancementModelUnavailable: "不可用 — 增强时会回退到当前模型",
promptEnhancementUserTemplate: "用户模板",
promptEnhancementUserTemplateDesc:
"用于包裹草稿。必须包含草稿变量,请用插入按钮写入。",
@@ -1208,6 +1210,7 @@ sklm: {
promptEnhancementRestore: "恢复默认",
promptEnhancementMissingDraftVariable:
"用户模板必须包含草稿变量,否则草稿无法发送给模型。",
+ promptEnhancementTooLong: "用户模板最多 8000 个字符。",
promptEnhancementSaveError: "无法保存提示词增强设置。",
},
project: {
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 2dd310acf..82e68a4f3 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -249,6 +249,7 @@ export const zhTW = {
speakSaved: "朗讀音訊已儲存到 {{path}}",
undoEnhancement: "撤回增強",
enhancementFailed: "提示詞增強失敗",
+ enhancementTimeout: "改寫逾時。請重試,或在設定中改用更快的增強模型。",
dismissEnhancementError: "關閉增強錯誤",
sendWhileRunning: "傳送後續訊息 · {{shortcut}} 立即轉向",
steeringUnavailable: "目前回合已無法接收轉向輸入,草稿已保留。",
@@ -1201,6 +1202,7 @@ sklm: {
"改寫時使用的思考強度。預設關閉,最快。",
promptEnhancementThinkingOff: "關閉思考",
promptEnhancementModelFollow: "跟隨目前模型",
+ promptEnhancementModelUnavailable: "無法使用 — 增強時會回退到目前模型",
promptEnhancementUserTemplate: "使用者範本",
promptEnhancementUserTemplateDesc:
"用於包裹草稿。必須包含草稿變數,請用插入按鈕寫入。",
@@ -1208,6 +1210,7 @@ sklm: {
promptEnhancementRestore: "恢復預設",
promptEnhancementMissingDraftVariable:
"使用者範本必須包含草稿變數,否則草稿無法傳送給模型。",
+ promptEnhancementTooLong: "使用者範本最多 8000 個字元。",
promptEnhancementSaveError: "無法儲存提示詞增強設定。",
},
project: {
diff --git a/packages/shared/src/prompt-enhancement.test.ts b/packages/shared/src/prompt-enhancement.test.ts
index 96bf11645..4e4712183 100644
--- a/packages/shared/src/prompt-enhancement.test.ts
+++ b/packages/shared/src/prompt-enhancement.test.ts
@@ -25,7 +25,8 @@ describe("prompt-enhancement defaults", () => {
expect(system).toContain("proper nouns");
expect(system).toContain("reproduce them exactly as written");
// Length brake and the explicit do-not list.
- expect(system).toContain("never beyond about 800 characters");
+ expect(system).toContain("twice the draft's length");
+ expect(system).not.toContain("800 characters");
expect(system).toContain("DO NOT:");
expect(system).toContain("Answer, execute, or fulfil the draft's request");
// Output contract.
@@ -38,9 +39,11 @@ describe("prompt-enhancement defaults", () => {
expect(template).toContain("帮我看看这段代码");
expect(template).toContain("fix the login bug");
expect(template).toContain("这个函数有点慢,can you make it faster");
- // The meta-note failure mode has an explicit bad/good pair.
- expect(template).toContain("Bad output");
- expect(template).toContain("Good output");
+ // The meta-note failure mode is explicit, without an `Enhanced:` prefix
+ // the model would copy into the Composer.
+ expect(template).toContain("Never emit");
+ expect(template).not.toContain("Enhanced:");
+ expect(template).toContain("<example-draft>");
});
});
diff --git a/packages/shared/src/prompt-enhancement.ts b/packages/shared/src/prompt-enhancement.ts
index 044eb9dd1..aeb83c824 100644
--- a/packages/shared/src/prompt-enhancement.ts
+++ b/packages/shared/src/prompt-enhancement.ts
@@ -47,7 +47,7 @@ REWRITE PRINCIPLES:
- Make a substantive improvement: state the task, scope, constraints, and expected output explicitly.
- Replace vague wording with verifiable requirements.
- Prefer WHAT over HOW: do not prescribe an implementation the draft does not ask for.
-- Keep the enhanced prompt concise: do not expand beyond roughly twice the draft's length, and never beyond about 800 characters.
+- Keep the enhanced prompt concise: do not expand beyond roughly twice the draft's length. A long draft may stay long; do not compress it just to be short.
- If the draft is already clear, sharpen it instead of returning it unchanged.
DO NOT:
@@ -70,7 +70,9 @@ OUTPUT:
* Default user template. The draft stays inside `<draft>` tags so draft text
* reads as content to improve, never as instructions. The examples cover
* Chinese, English, mixed-language input, and the language-meta-note failure
- * that the old single-line prompt did not guard against.
+ * that the old single-line prompt did not guard against. Example answers are
+ * bare rewritten prompts — no `Enhanced:` / `Output:` label — so the model
+ * does not copy a prefix into the Composer.
*/
export const PROMPT_ENHANCEMENT_DEFAULT_USER_TEMPLATE = `<draft>
${PROMPT_ENHANCEMENT_DRAFT_VARIABLE}
@@ -82,20 +84,20 @@ Language: match the draft's language exactly, including a natural mix when the d
Output: only the enhanced prompt. No explanation, preamble, heading, label, code fence, or wrapping quotation marks. Never end with an unfinished list, a dangling conjunction, or a trailing colon.
-Examples:
+Examples — each line after an <example-draft> is the entire answer. Copy no label.
-Draft: 帮我看看这段代码
-Enhanced: 请审查这段代码的正确性、边界情况和可读性,指出具体位置,并说明每个问题的修复方向。
+<example-draft>帮我看看这段代码</example-draft>
+请审查这段代码的正确性、边界情况和可读性,指出具体位置,并说明每个问题的修复方向。
-Draft: fix the login bug
-Enhanced: Fix the login bug: identify the failing code path, explain the root cause, and apply a minimal fix while keeping the current behavior. State how the fix can be verified.
+<example-draft>fix the login bug</example-draft>
+Fix the login bug: identify the failing code path, explain the root cause, and apply a minimal fix while keeping the current behavior. State how the fix can be verified.
-Draft: 这个函数有点慢,can you make it faster
-Enhanced: 这个函数执行较慢。请分析性能瓶颈(复杂度与热点调用),说明原因,给出优化后的实现,并保持现有行为不变。
+<example-draft>这个函数有点慢,can you make it faster</example-draft>
+这个函数执行较慢。请分析性能瓶颈(复杂度与热点调用),说明原因,给出优化后的实现,并保持现有行为不变。
-Draft: 帮我搞一下那个东西
-Bad output (never emit this): "The draft is in Chinese, so the response must be in Chinese." followed by the draft unchanged.
-Good output: 请说明要处理的具体对象、期望的输出格式、可接受的约束条件与验收标准;如果缺少必要信息,先列出需要我补充的内容再开始。`;
+<example-draft>帮我搞一下那个东西</example-draft>
+Never emit: "The draft is in Chinese, so the response must be in Chinese." followed by the draft unchanged.
+请说明要处理的具体对象、期望的输出格式、可接受的约束条件与验收标准;如果缺少必要信息,先列出需要我补充的内容再开始。`;
/** The persisted user-template override, as stored on `AppSettings`. */
export type PromptEnhancementTemplateOverrides = {