Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): review 反馈——Anthropic system 字段、turnGen 空窗、render ref 安全

Shinkuca09c4667120
diff --git a/apps/desktop/src/main/maker-host/provider-one-shot.ts b/apps/desktop/src/main/maker-host/provider-one-shot.ts
index f81f9464c0..e82f2a0cb2 100644
--- a/apps/desktop/src/main/maker-host/provider-one-shot.ts
+++ b/apps/desktop/src/main/maker-host/provider-one-shot.ts
@@ -242,7 +242,9 @@ export function buildOneShotTarget(providerId: string): ProviderOneShotTarget |
// ── wire fetchers(各自一次 fetch;失败 / 空 → 抛错,由编排层吞成 null)─────────────
-/** Anthropic Messages:Bearer 订阅 OAuth + anthropic-beta;model 经 toSdkModelString 还原 wire 串。 */
+/** Anthropic Messages:Bearer 订阅 OAuth + anthropic-beta;model 经 toSdkModelString 还原 wire 串。
+ * systemPrompt(可选)写入 Messages API 顶层 `system` 字段,而非作为消息角色。
+ * prompt prediction 依赖此字段将系统指令与对话上下文正确分离。 */
async function fetchAnthropicTitle(
upstream: string,
modelId: string,
@@ -253,10 +255,16 @@ async function fetchAnthropicTitle(
maxTokens: number = ONE_SHOT_DEFAULT_MAX_TOKENS,
systemPrompt?: string,
): Promise<string> {
- const messages: Array<{ role: string; content: string }> = [];
- if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });
- messages.push({ role: 'user', content: prompt });
-
+ // Anthropic Messages API 不支持 role: 'system' 消息 —— 系统指令必须写入
+ // 顶层 `system` 字段,否则请求会被 API 拒绝。
+ const body: Record<string, unknown> = {
+ model: toSdkModelString(modelId),
+ max_tokens: maxTokens,
+ messages: [{ role: 'user', content: prompt }],
+ };
+ if (systemPrompt) {
+ body.system = systemPrompt;
+ }
const res = await fetchImpl(`${trimTrailingSlash(upstream)}/v1/messages`, {
method: 'POST',
signal,
@@ -266,11 +274,7 @@ async function fetchAnthropicTitle(
'anthropic-beta': 'oauth-2025-04-20',
'content-type': 'application/json',
},
- body: JSON.stringify({
- model: toSdkModelString(modelId),
- max_tokens: maxTokens,
- messages,
- }),
+ body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`anthropic messages HTTP ${res.status}`);
const json = (await res.json()) as { content?: Array<{ type?: string; text?: string }> };
@@ -405,7 +409,13 @@ export interface OneShotOpts {
maxOutputChars?: number;
/** 校验通过后的 Unicode 截断长度(标题默认 40)。0 跳过截断。 */
maxVisualChars?: number;
- /** 可选的 system 消息:有值时各 wire 在 user prompt 前追加一条 system role 消息。 */
+ /**
+ * 可选的 system 指令。
+ * - Anthropic Messages wire: 写入顶层 `system` 字段(该 API 不接受 role: 'system' 消息)。
+ * - Codex Responses wire: 拼接到 instructions 前。
+ * - Gateway chat wire: 作为 role: 'system' 消息插入 messages 数组。
+ * prompt prediction 用此字段将系统指令与对话上下文正确分离。
+ */
systemPrompt?: string;
}
diff --git a/apps/desktop/src/main/maker-ipc/promptPrediction.ts b/apps/desktop/src/main/maker-ipc/promptPrediction.ts
index 56fb6a543f..ff85fe69f6 100644
--- a/apps/desktop/src/main/maker-ipc/promptPrediction.ts
+++ b/apps/desktop/src/main/maker-ipc/promptPrediction.ts
@@ -14,6 +14,7 @@
import type { AgentKind } from '@cindy/maker-core';
+import { getResolvedMainLocale } from '../i18n.js';
import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
import { runProviderOneShot } from '../maker-host/provider-one-shot.js';
import { connectedProvidersForAgent, type ProviderView } from '@cindy/model-providers';
@@ -69,12 +70,24 @@ function escapeReferenceData(value: string): string {
function buildPredictionPrompt(
context: string,
+ locale: string,
workingDir?: string,
): { system: string; user: string } {
+ const languageHints: Record<string, string> = {
+ 'zh-CN': "Match the user's language. The user types in Simplified Chinese.",
+ en: "Match the user's language. The user types in English.",
+ ja: "Match the user's language. The user types in Japanese.",
+ ko: "Match the user's language. The user types in Korean.",
+ };
const wdLine = workingDir ? `Current working directory: ${workingDir}` : null;
+ // 系统指令写入 Anthropic Messages API 顶层 system 字段(非 Anthropic wire 忽略),
+ // 不混入 user message,避免被 Anthropic API 拒绝。
const system = [
- 'You are a terse predictive text engine. Return only the predicted user prompt.',
+ 'You are a terse predictive text engine for a coding chat input.',
+ 'Return only the predicted next user message — no quotes, markdown, commentary, or multiple options.',
+ 'Keep it under 140 characters. Make it actionable for a coding agent.',
+ languageHints[locale] ?? "Match the user's language and tone.",
].join('\n');
const user = [
@@ -86,7 +99,7 @@ function buildPredictionPrompt(
'</recent_conversation>',
'',
'Return exactly one concise user prompt.',
- 'Match the user\'s tone, brevity, phrasing, and terminology based on their recent messages.',
+ "Match the user's tone, brevity, phrasing, and terminology based on their recent messages.",
'Do not copy prior messages verbatim.',
'Make it actionable.',
'Keep it under 140 characters.',
@@ -145,15 +158,21 @@ export async function generatePromptPrediction(
return null;
}
- const { system, user } = buildPredictionPrompt(context, params.workingDir);
+ const locale = getResolvedMainLocale();
+ const { system: systemPrompt, user: userPrompt } = buildPredictionPrompt(
+ context,
+ locale,
+ params.workingDir,
+ );
// 截断到上限(char 数),防止超长上下文撑爆 prompt
- const userPrompt = user.slice(0, PREDICTION_CONTEXT_MAX_CHARS + 1024); // prompt 固定部分 ~200 chars
+ const truncated = userPrompt.slice(0, PREDICTION_CONTEXT_MAX_CHARS + 1024); // prompt 固定部分 ~200 chars
+ // 仅记录长度用于调试,不记录对话内容避免敏感数据泄漏。
log.debug('prompt prediction params', {
- context,
- system,
- user: userPrompt,
+ contextLen: context.length,
+ systemLen: systemPrompt.length,
+ userLen: truncated.length,
agentKind: params.agentKind,
sessionId: params.sessionId,
});
@@ -161,13 +180,14 @@ export async function generatePromptPrediction(
// 复用 title one-shot 通路,但覆盖 token/校验参数以适配预测场景:
// - maxTokens=96: 标题仅需 32 token,预测 ≤140 chars 需要更多
// - codexInstructions: 告诉模型这是预测而非标题
+ // - systemPrompt: Anthropic Messages API 顶层 system 字段(非 Anthropic wire 忽略)
// - maxOutputChars=0: 跳过 validateTitleOutput(该函数面向单行标题,拒绝多行/长文本)
// - maxVisualChars=140: 截断到推荐提示词上限
return runProviderOneShot(
{
sessionId: params.sessionId,
agentKind: params.agentKind,
- prompt: userPrompt,
+ prompt: truncated,
},
{
readSessionProviderId: readSessionProviderIdFromDb,
@@ -177,9 +197,9 @@ export async function generatePromptPrediction(
maxTokens: 96,
codexInstructions:
'Output only the predicted next user message — no quotes, markdown, or commentary.',
+ systemPrompt,
maxOutputChars: 0,
maxVisualChars: 140,
- systemPrompt: system,
},
);
}
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 456ca428ec..56d6f1f6d9 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -1102,23 +1102,32 @@ export function ChatInput({
// → React render」之间旧 Promise 落地的空窗;useEffect 里照旧做清除推荐 UI 的副作用。
const turnGenRef = useRef(0);
const prevShowStopRender = useRef(false);
- // 同步层:render 阶段检测 turn 开始,在 React commit 前就让旧预测的 turnGen 失效。
- const turnStarting = showStopButton && !prevShowStopRender.current;
- prevShowStopRender.current = showStopButton;
- if (turnStarting) {
- turnGenRef.current += 1;
- }
- // sessionId 切换时在 render 阶段同步更新预测相关 ref,关闭 useEffect 延迟空窗:
- // 若旧 session 的预测请求在 render→commit 之间返回,prevSessionIdRef 已指向
- // 新 session,落地校验会拒绝该结果,不会让旧会话推荐词写入新会话输入框。
const prevSessionIdRef = useRef(sessionId);
- if (prevSessionIdRef.current !== sessionId) {
- prevSessionIdRef.current = sessionId;
- prevShowStopRef.current = false;
- turnGenRef.current = 0;
- prevShowStopRender.current = false;
- showRecommendationRef.current = false;
- }
+ // useLayoutEffect 在 React commit 后、浏览器绘制前同步执行,比 useEffect 更接近
+ // render 阶段的时序,同时避免 React concurrent rendering 下 render 被丢弃但 ref
+ // 已被错误修改的风险。防御纵深:发送时已通过 turnGenRef.current += 1 立即失效
+ // 旧预测(见 handleSend),此处作为兜底处理 showStopButton 跳变场景。
+ useLayoutEffect(() => {
+ const turnStarting = showStopButton && !prevShowStopRender.current;
+ prevShowStopRender.current = showStopButton;
+ if (turnStarting) {
+ turnGenRef.current += 1;
+ }
+ });
+ // sessionId 切换时同步更新预测相关 ref。使用 useLayoutEffect 而非 render 阶段直接
+ // 修改 ref,避免 concurrent rendering 的潜在风险。sessionId 在 commit 后立即更新
+ // ref,旧 session 预测请求若在 commit→layout effect 之间返回,仍会因 sessionId
+ // 不匹配被落地校验拒绝(defense-in-depth)。
+ useLayoutEffect(() => {
+ if (prevSessionIdRef.current !== sessionId) {
+ prevSessionIdRef.current = sessionId;
+ prevShowStopRef.current = false;
+ turnGenRef.current = 0;
+ prevShowStopRender.current = false;
+ showRecommendationRef.current = false;
+ setRecommendedPrompt(null);
+ }
+ }, [sessionId]);
useEffect(() => {
// sessionId 变化时清除推荐 UI(ref 已在 render 阶段同步更新)
setRecommendedPrompt(null);
@@ -4927,6 +4936,10 @@ onUpdate: ({ editor: ed, transaction }) => {
// 选择发送,保证本 turn 与 UI/SQLite 的 effort 相同。
effortForSend = coordinator.getCommittedEffort(sessionId) ?? activeEffort;
}
+ // 发送新消息时立即递增 turnGen,让任何还未落地的旧 turn 预测结果失效。
+ // 防止「编辑器已清空 → showStopButton 尚未变 true」之间的空窗导致
+ // 旧上下文推荐短暂显示。
+ turnGenRef.current += 1;
result = await onSend(
textToSend,
activeModel,