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): improve prompt prediction — split system/user, add workingDir, refine instructions

Shinkud506e5ce8bf3
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 5ece26e0b7..f81f9464c0 100644
--- a/apps/desktop/src/main/maker-host/provider-one-shot.ts
+++ b/apps/desktop/src/main/maker-host/provider-one-shot.ts
@@ -251,7 +251,12 @@ async function fetchAnthropicTitle(
fetchImpl: FetchImpl,
signal: AbortSignal,
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 });
+
const res = await fetchImpl(`${trimTrailingSlash(upstream)}/v1/messages`, {
method: 'POST',
signal,
@@ -264,7 +269,7 @@ async function fetchAnthropicTitle(
body: JSON.stringify({
model: toSdkModelString(modelId),
max_tokens: maxTokens,
- messages: [{ role: 'user', content: prompt }],
+ messages,
}),
});
if (!res.ok) throw new Error(`anthropic messages HTTP ${res.status}`);
@@ -286,10 +291,14 @@ async function fetchCodexTitle(
fetchImpl: FetchImpl,
signal: AbortSignal,
instructions: string = CODEX_DEFAULT_INSTRUCTIONS,
+ systemPrompt?: string,
): Promise<string> {
+ const effectiveInstructions = systemPrompt
+ ? `${systemPrompt}\n\n${instructions}`
+ : instructions;
const body: Record<string, unknown> = {
model: modelId,
- instructions,
+ instructions: effectiveInstructions,
input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: prompt }] }],
tools: [],
tool_choice: 'auto',
@@ -326,7 +335,12 @@ async function fetchGatewayTitle(
fetchImpl: FetchImpl,
signal: AbortSignal,
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 });
+
const res = await fetchImpl(`${trimTrailingSlash(upstream)}/chat/completions`, {
method: 'POST',
signal,
@@ -337,7 +351,7 @@ async function fetchGatewayTitle(
body: JSON.stringify({
model: modelId,
max_tokens: maxTokens,
- messages: [{ role: 'user', content: prompt }],
+ messages,
}),
});
if (!res.ok) throw new Error(`gateway chat HTTP ${res.status}`);
@@ -391,6 +405,8 @@ export interface OneShotOpts {
maxOutputChars?: number;
/** 校验通过后的 Unicode 截断长度(标题默认 40)。0 跳过截断。 */
maxVisualChars?: number;
+ /** 可选的 system 消息:有值时各 wire 在 user prompt 前追加一条 system role 消息。 */
+ systemPrompt?: string;
}
/**
@@ -406,6 +422,13 @@ export async function runProviderOneShot(
deps: ProviderOneShotDeps = {},
opts?: OneShotOpts,
): Promise<string | null> {
+ log.debug('oneShot args', {
+ sessionId: args.sessionId,
+ agentKind: args.agentKind,
+ prompt: args.prompt,
+ opts,
+ });
+
// 默认走吃系统代理的 undici fetch:上游可能是境外端点(catalog routing.upstream)。
const fetchImpl = deps.fetchImpl ?? outboundUndiciFetch;
const readSessionProviderId = deps.readSessionProviderId ?? (async () => null);
@@ -524,6 +547,11 @@ export async function runProviderOneShot(
return null;
}
if (!canDispatchNow('after-credential-refresh')) return null;
+ log.debug('oneShot request body (anthropic)', {
+ model: toSdkModelString(target.model),
+ maxTokens,
+ prompt: args.prompt,
+ });
text = await fetchAnthropicTitle(
target.upstream,
target.model,
@@ -532,6 +560,7 @@ export async function runProviderOneShot(
fetchImpl,
controller.signal,
maxTokens,
+ opts?.systemPrompt,
);
break;
}
@@ -542,6 +571,12 @@ export async function runProviderOneShot(
return null;
}
if (!canDispatchNow('after-credential-read')) return null;
+ log.debug('oneShot request body (codex)', {
+ model: target.model,
+ effort: target.effort,
+ instructions: codexInstructions,
+ prompt: args.prompt,
+ });
text = await fetchCodexTitle(
target.upstream,
target.model,
@@ -551,6 +586,7 @@ export async function runProviderOneShot(
fetchImpl,
controller.signal,
codexInstructions,
+ opts?.systemPrompt,
);
break;
}
@@ -561,6 +597,11 @@ export async function runProviderOneShot(
return null;
}
if (!canDispatchNow('after-credential-read')) return null;
+ log.debug('oneShot request body (gateway-chat)', {
+ model: target.model,
+ maxTokens,
+ prompt: args.prompt,
+ });
text = await fetchGatewayTitle(
target.upstream,
target.model,
@@ -569,10 +610,16 @@ export async function runProviderOneShot(
fetchImpl,
controller.signal,
maxTokens,
+ opts?.systemPrompt,
);
break;
}
}
+ log.debug('oneShot raw response', {
+ wire: target.wire,
+ model: target.model,
+ response: text,
+ });
// The prompt is advisory; never persist a transcript continuation, role-labelled
// response, Markdown wrapper, or multiline answer. Validate the complete response
// before applying the truncation, so a bad suffix cannot hide beyond the slice boundary.
diff --git a/apps/desktop/src/main/maker-ipc/promptPrediction.ts b/apps/desktop/src/main/maker-ipc/promptPrediction.ts
index c703ecf351..56fb6a543f 100644
--- a/apps/desktop/src/main/maker-ipc/promptPrediction.ts
+++ b/apps/desktop/src/main/maker-ipc/promptPrediction.ts
@@ -14,7 +14,6 @@
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';
@@ -68,24 +67,35 @@ function escapeReferenceData(value: string): string {
});
}
-function buildPredictionPrompt(context: string, locale: string): 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.',
- };
-
- return [
- '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.',
+function buildPredictionPrompt(
+ context: string,
+ workingDir?: string,
+): { system: string; user: string } {
+ const wdLine = workingDir ? `Current working directory: ${workingDir}` : null;
+
+ const system = [
+ 'You are a terse predictive text engine. Return only the predicted user prompt.',
+ ].join('\n');
+
+ const user = [
+ 'Predict the next message the user is likely to type.',
+ wdLine,
'',
'<recent_conversation>',
escapeReferenceData(context),
'</recent_conversation>',
- ].join('\n');
+ '',
+ 'Return exactly one concise user prompt.',
+ '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.',
+ 'No quotes, markdown, commentary, explanations, or multiple options.',
+ ]
+ .filter((line): line is string => line !== null)
+ .join('\n');
+
+ return { system, user };
}
/** 从 DB 读 sessions.provider_id。失败/空串 → null。 */
@@ -135,11 +145,18 @@ export async function generatePromptPrediction(
return null;
}
- const locale = getResolvedMainLocale();
- const prompt = buildPredictionPrompt(context, locale);
+ const { system, user } = buildPredictionPrompt(context, params.workingDir);
// 截断到上限(char 数),防止超长上下文撑爆 prompt
- const truncated = prompt.slice(0, PREDICTION_CONTEXT_MAX_CHARS + 1024); // prompt 固定部分 ~200 chars
+ const userPrompt = user.slice(0, PREDICTION_CONTEXT_MAX_CHARS + 1024); // prompt 固定部分 ~200 chars
+
+ log.debug('prompt prediction params', {
+ context,
+ system,
+ user: userPrompt,
+ agentKind: params.agentKind,
+ sessionId: params.sessionId,
+ });
// 复用 title one-shot 通路,但覆盖 token/校验参数以适配预测场景:
// - maxTokens=96: 标题仅需 32 token,预测 ≤140 chars 需要更多
@@ -150,7 +167,7 @@ export async function generatePromptPrediction(
{
sessionId: params.sessionId,
agentKind: params.agentKind,
- prompt: truncated,
+ prompt: userPrompt,
},
{
readSessionProviderId: readSessionProviderIdFromDb,
@@ -162,6 +179,7 @@ export async function generatePromptPrediction(
'Output only the predicted next user message — no quotes, markdown, or commentary.',
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 4a58d103b5..456ca428ec 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -1160,6 +1160,7 @@ export function ChatInput({
sessionId,
agentKind: runtimeAgentKind,
messages: contextMsgs,
+ workingDir: workingDir ?? undefined,
})
.then((result) => {
// 请求往返期间用户可能已经切换会话、发起新 turn 或开始打字 —— 落地前