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。

perf(desktop): 环境说明按变化发送,任务回执正文有界 (#6122)

Chris Zhangd3eabb2ffe70
diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
index 81c1ed16f9..c99dac63c5 100644
--- a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
@@ -330,7 +330,9 @@ describe('注入接线(源码级守卫)', () => {
// 注入链:normalized → withHandoff → withPlanReconcile → withGoalInactiveNote
// → 来源说明 → 客户端说明(元信息都在交接段之前)。
expect(source).toContain('prependNoteToWireUserMessage(withGoalInactiveNote as HandoffWireMessage, messageSourceNote)');
- expect(source).toContain('prependNoteToWireUserMessage(withSourceNote as HandoffWireMessage, mobileClientNote)');
+ // 环境说明经 wireNoteMemory 去重后再前置(内容没变就不重复),链路位置不变。
+ expect(source).toContain("prependNoteToWireUserMessage(withSourceNote as HandoffWireMessage, plannedNotes['client-environment'])");
+ expect(source).toContain('deps.planRepeatableWireNotes?.(sessionId, repeatableNotes, { force: pendingHandoff !== null })');
expect(source).toContain('readWireSourceDevice(so.sourceDevice)');
expect(source).toContain('shouldPrependMobileClientPromptNote(normalized, sess.agentKind)');
// 落库内容必须仍取 persistUserMessage.content —— 若改成 outgoing,提示语会写进
@@ -588,7 +590,9 @@ describe('排队 / 插入两条路径的接线(源码级守卫)', () => {
expect(register).toContain("isMobileControllerInvoke() || so.fromMobileClient === true");
expect(register).toContain('shouldPrependMobileClientPromptNote(normalized, sess.agentKind)');
expect(register).toContain('prependNoteToWireUserMessage(normalized as HandoffWireMessage, steerSourceNote)');
- expect(register).toContain('prependNoteToWireUserMessage(withSteerSourceNote as HandoffWireMessage, steerNote)');
+ // steer 与 send 事务共用同一份环境说明去重记忆,投递成功后才记为已发送。
+ expect(register).toContain("prependNoteToWireUserMessage(withSteerSourceNote as HandoffWireMessage, steerPlannedNotes['client-environment'])");
+ expect(register).toContain('steerNotePlan?.commit()');
expect(register).toContain('readWireSourceDevice(so.sourceDevice)');
expect(register).toContain('await sess.steer(steerPayload as never');
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botDelegationCompletionMessage.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botDelegationCompletionMessage.test.ts
new file mode 100644
index 0000000000..b4a02ee2b4
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botDelegationCompletionMessage.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildDelegationCompletionMessage,
+ COMPLETION_ARTIFACTS_WIRE_LIMIT,
+ COMPLETION_RESULT_WIRE_CHARS,
+} from '../botDelegationCompletionMessage';
+
+describe('buildDelegationCompletionMessage', () => {
+ it('keeps the receipt header, task id, status and a short result intact', () => {
+ const text = buildDelegationCompletionMessage({
+ id: 'd-1',
+ objective: '整理周报',
+ status: 'completed',
+ resultSummary: '已写好 report.md',
+ artifacts: [{ absolutePath: '/tmp/report.md' }],
+ });
+ expect(text.startsWith('[任务回执] 后台任务已完成。task_id: d-1')).toBe(true);
+ expect(text).toContain('目标事项: 整理周报');
+ expect(text).toContain('结果:\n已写好 report.md');
+ expect(text).toContain('交出的文件(1):\n- /tmp/report.md');
+ expect(text).toContain('message_session_task');
+ });
+
+ it('bounds a long result so the hidden receipt does not grow the model context unbounded', () => {
+ const long = 'x'.repeat(12_000);
+ const text = buildDelegationCompletionMessage({ id: 'd-2', objective: 'o', status: 'completed', resultSummary: long });
+ expect(text).toContain('x'.repeat(COMPLETION_RESULT_WIRE_CHARS));
+ expect(text).not.toContain('x'.repeat(COMPLETION_RESULT_WIRE_CHARS + 1));
+ expect(text).toContain('check_session_task');
+ expect(text.length).toBeLessThan(COMPLETION_RESULT_WIRE_CHARS + 600);
+ });
+
+ it('lists a bounded number of artifacts and says how many more exist', () => {
+ const artifacts = Array.from({ length: COMPLETION_ARTIFACTS_WIRE_LIMIT + 5 }, (_, i) => ({ absolutePath: `/out/${i}.txt` }));
+ const text = buildDelegationCompletionMessage({ id: 'd-3', objective: 'o', status: 'completed', artifacts });
+ expect(text).toContain(`交出的文件(${artifacts.length}):`);
+ expect(text).toContain(`/out/${COMPLETION_ARTIFACTS_WIRE_LIMIT - 1}.txt`);
+ expect(text).not.toContain(`/out/${COMPLETION_ARTIFACTS_WIRE_LIMIT}.txt`);
+ expect(text).toContain('另有 5 个');
+ });
+
+ it('maps timeouts and failures to their status lines and clips the error', () => {
+ expect(buildDelegationCompletionMessage({ id: 'd', objective: 'o', status: 'failed', lastError: 'TIMEOUT: 30m' }))
+ .toContain('后台任务已超时');
+ expect(buildDelegationCompletionMessage({ id: 'd', objective: 'o', status: 'timed-out' })).toContain('后台任务已超时');
+ expect(buildDelegationCompletionMessage({ id: 'd', objective: 'o', status: 'cancelled' })).toContain('后台任务已取消');
+ const failed = buildDelegationCompletionMessage({ id: 'd', objective: 'o', status: 'failed', lastError: 'e'.repeat(2_000) });
+ expect(failed).toContain('后台任务失败了');
+ expect(failed).toContain('失败原因: ' + 'e'.repeat(600) + '…(已截断)');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index d085060698..27c6d376c9 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -39,6 +39,7 @@ import { buildCindyMakeTaskNote } from '../../cindy-make/taskNote';
import { getResolvedMainLocale } from '../../i18n';
import { buildMobileClientPromptNote } from '../mobileClientPromptNote';
import { buildUiLanguageErrorNote } from '../uiLanguageErrorNote';
+import { createWireNoteMemory } from '../wireNoteMemory';
import {
applyPendingAgentSwitchIfIdle,
createPendingAgentSwitchRegistry,
@@ -3613,3 +3614,82 @@ it('persists coordination audit metadata and dispatches the model without a prom
role: 'user', content: '[UI_ACTION_TRIGGER]Coordination', agentMeta: { botTaskCoordinationInput: receipt },
});
});
+
+describe('repeatable environment notes are sent only when they change', () => {
+ const host = { deviceId: 'mac-1', name: 'Mac' };
+ const phone = { deviceId: 'phone-1', name: 'iPhone', platform: 'mobile' as const };
+ const pc = { deviceId: 'pc-1', name: 'Office PC', platform: 'desktop' as const };
+
+ function setup(overrides: Partial<MakerSendTransactionDeps> = {}) {
+ const memory = createWireNoteMemory();
+ const session = createSession({ agentKind: 'codex' });
+ const { deps } = createDeps({
+ getSession: vi.fn(() => session),
+ readHostDeviceIdentity: vi.fn(() => host),
+ planRepeatableWireNotes: (sessionId, notes, opts) => memory.plan(sessionId, notes, opts),
+ ...overrides,
+ });
+ return { session, deps, memory, transaction: createMakerSendTransaction(deps) };
+ }
+ const sentAt = (session: MakerSendTransactionSession, index: number) =>
+ vi.mocked(session.send).mock.calls[index]?.[0] as string;
+
+ it('drops the UI language and device notes on the second turn from the same device', async () => {
+ const { session, transaction } = setup();
+ const opts = { sourceDevice: phone, persistUserMessage: { clientId: 'm-1', content: 'hello' } };
+ await transaction.sendToAgentAccepted('session-1', 'hello', undefined, opts);
+ await transaction.sendToAgentAccepted('session-1', 'again', undefined, { ...opts, persistUserMessage: { clientId: 'm-2', content: 'again' } });
+
+ expect(sentAt(session, 0)).toContain(uiLanguageNote());
+ expect(sentAt(session, 0)).toContain('[客户端说明]');
+ expect(sentAt(session, 1)).toBe('again');
+ });
+
+ it('resends just the device note when the controller changes, and the full set after a handoff', async () => {
+ const { session, transaction } = setup({
+ peekPendingHandoff: vi.fn(async () => null),
+ });
+ await transaction.sendToAgentAccepted('session-1', 'a', undefined, { sourceDevice: phone });
+ await transaction.sendToAgentAccepted('session-1', 'b', undefined, { sourceDevice: pc });
+ expect(sentAt(session, 1)).not.toContain(uiLanguageNote());
+ expect(sentAt(session, 1)).toContain('另一台电脑「Office PC」');
+
+ vi.mocked(session.send).mockClear();
+ const { session: fresh, transaction: afterHandoff } = setup({
+ peekPendingHandoff: vi.fn(async () => 'HANDOFF'),
+ });
+ await afterHandoff.sendToAgentAccepted('session-1', 'c', undefined, { sourceDevice: pc });
+ expect(sentAt(fresh, 0)).toContain(uiLanguageNote());
+ expect(sentAt(fresh, 0)).toContain('HANDOFF');
+ });
+
+ it('keeps resending while the engine has not accepted the turn', async () => {
+ const session = createSession({
+ agentKind: 'codex',
+ send: vi.fn(async () => ({ accepted: false }) as SessionSendResult),
+ });
+ const { transaction } = setup({ getSession: vi.fn(() => session) });
+ await transaction.sendToAgentAccepted('session-1', 'a').catch(() => undefined);
+ await transaction.sendToAgentAccepted('session-1', 'b').catch(() => undefined);
+ expect(sentAt(session, 0)).toContain(uiLanguageNote());
+ expect(sentAt(session, 1)).toContain(uiLanguageNote());
+ });
+
+ it('leaves slash-command turns alone without marking the notes as seen', async () => {
+ const session = createSession({ agentKind: 'claude-code' });
+ const { transaction } = setup({ getSession: vi.fn(() => session) });
+ await transaction.sendToAgentAccepted('session-1', '/compact');
+ await transaction.sendToAgentAccepted('session-1', 'hello');
+ expect(sentAt(session, 0)).toBe('/compact');
+ expect(sentAt(session, 1)).toContain(uiLanguageNote());
+ });
+
+ it('sends every note each turn when no memory is wired (legacy behaviour)', async () => {
+ const session = createSession({ agentKind: 'codex' });
+ const { deps } = createDeps({ getSession: vi.fn(() => session) });
+ const transaction = createMakerSendTransaction(deps);
+ await transaction.sendToAgentAccepted('session-1', 'a');
+ await transaction.sendToAgentAccepted('session-1', 'b');
+ expect(sentAt(session, 1)).toBe(withUiLanguageNote('b'));
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
index 72438105d1..7b1f96672c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@ -252,6 +252,7 @@ function harness() {
onUnsuccessfulProductTurn: vi.fn(async () => {}),
log,
botCompactRuntimeRefreshCoordinator: { noteBoundary: vi.fn() },
+ wireNoteMemory: { reset: vi.fn() },
attemptBotCompactRuntimeRefresh: vi.fn(),
botDelegationServiceHolder: { settleSession: vi.fn(async () => {}) },
isFencedStaleSessionTerminal: vi.fn(() => false),
@@ -1884,6 +1885,8 @@ describe('Bot adapters in the shared event pipeline', () => {
const h = harness();
h.emit(event('compact_boundary'));
expect(h.deps.botCompactRuntimeRefreshCoordinator.noteBoundary).toHaveBeenCalledWith(h.session);
+ // 原生摘要可能丢掉了环境说明:下一轮整体重发。
+ expect(h.deps.wireNoteMemory.reset).toHaveBeenCalledWith('task');
expect(h.deps.attemptBotCompactRuntimeRefresh).not.toHaveBeenCalled();
h.deps.agentInputCoordinatorHolder.getQueueControlSnapshot.mockReturnValue({ pendingQueue: [{}] });
h.emit(event('done', { result: 'first result' }));
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/wireNoteMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/wireNoteMemory.test.ts
new file mode 100644
index 0000000000..118e62e8e0
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/wireNoteMemory.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest';
+
+import { createWireNoteMemory } from '../wireNoteMemory';
+
+const UI = '[UI language] zh-CN';
+const PHONE = '[客户端说明] 手机';
+const PC = '[客户端说明] 另一台电脑';
+
+describe('wireNoteMemory', () => {
+ it('sends every note the first time and nothing unchanged afterwards', () => {
+ const memory = createWireNoteMemory();
+ const first = memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE });
+ expect(first.notes).toEqual({ 'ui-language': UI, 'client-environment': PHONE });
+ first.commit();
+
+ const second = memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE });
+ expect(second.notes).toEqual({});
+ });
+
+ it('resends only the note whose content changed', () => {
+ const memory = createWireNoteMemory();
+ memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE }).commit();
+
+ const switched = memory.plan('s1', { 'ui-language': UI, 'client-environment': PC });
+ expect(switched.notes).toEqual({ 'client-environment': PC });
+ switched.commit();
+ expect(memory.plan('s1', { 'ui-language': UI, 'client-environment': PC }).notes).toEqual({});
+ });
+
+ it('remembers an absent note so its return is sent again', () => {
+ const memory = createWireNoteMemory();
+ memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE }).commit();
+ const local = memory.plan('s1', { 'ui-language': UI, 'client-environment': null });
+ expect(local.notes).toEqual({});
+ local.commit();
+ expect(memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE }).notes).toEqual({
+ 'client-environment': PHONE,
+ });
+ });
+
+ it('does not treat an uncommitted (rejected) send as delivered', () => {
+ const memory = createWireNoteMemory();
+ memory.plan('s1', { 'ui-language': UI });
+ expect(memory.plan('s1', { 'ui-language': UI }).notes).toEqual({ 'ui-language': UI });
+ });
+
+ it('resends everything when forced (handoff first turn) or after reset (compact / clear)', () => {
+ const memory = createWireNoteMemory();
+ memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE }).commit();
+
+ expect(memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE }, { force: true }).notes)
+ .toEqual({ 'ui-language': UI, 'client-environment': PHONE });
+
+ memory.reset('s1');
+ expect(memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE }).notes)
+ .toEqual({ 'ui-language': UI, 'client-environment': PHONE });
+ });
+
+ it('a reset during an in-flight send invalidates the earlier plan so the next turn resends everything', () => {
+ const memory = createWireNoteMemory();
+ memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE }).commit();
+ // 第二轮内容没变 → 计划里什么都不发;发送在途时原生压缩触发 reset。
+ const inFlight = memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE });
+ expect(inFlight.notes).toEqual({});
+ memory.reset('s1');
+ inFlight.commit();
+ // 旧计划不能把"已发过"写回:新上下文没看过说明,下一轮必须整体重发。
+ expect(memory.plan('s1', { 'ui-language': UI, 'client-environment': PHONE }).notes)
+ .toEqual({ 'ui-language': UI, 'client-environment': PHONE });
+ // reset 之后新建的计划照常可以 commit。
+ const fresh = memory.plan('s1', { 'ui-language': UI });
+ fresh.commit();
+ expect(memory.plan('s1', { 'ui-language': UI }).notes).toEqual({});
+ // 另一个会话的 reset 不影响本会话的计划。
+ const other = memory.plan('s1', { 'ui-language': UI, 'client-environment': PC });
+ memory.reset('s2');
+ other.commit();
+ expect(memory.plan('s1', { 'ui-language': UI, 'client-environment': PC }).notes).toEqual({});
+ });
+
+ it('keeps sessions independent', () => {
+ const memory = createWireNoteMemory();
+ memory.plan('s1', { 'ui-language': UI }).commit();
+ expect(memory.plan('s2', { 'ui-language': UI }).notes).toEqual({ 'ui-language': UI });
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationCompletionMessage.ts b/apps/desktop/src/main/maker-ipc/botDelegationCompletionMessage.ts
new file mode 100644
index 0000000000..65a32d59ad
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botDelegationCompletionMessage.ts
@@ -0,0 +1,59 @@
+/**
+ * 后台任务终态回执:发给发起伙伴模型的隐藏指令正文。
+ *
+ * 完整结果(最多 MAX_RESULT_CHARS)已经作为独立的 assistant 回执行持久化在时间线里
+ * (botDelegationService 的 persistResultReceipt),模型随时能用 `check_session_task`
+ * 或任务卡读到全文。回执正文只需要让伙伴接得上工作:长期对话里这类回执会累积几十条
+ * 并一直留在原生上下文中,正文每多一千字,之后每一轮都要重复付这笔 token。
+ */
+
+export interface DelegationCompletionMessageInput {
+ id: string;
+ objective: string;
+ status: 'completed' | 'failed' | 'cancelled' | 'timed-out';
+ resultSummary?: string | null;
+ artifacts?: ReadonlyArray<{ absolutePath: string }>;
+ lastError?: string | null;
+}
+
+/** 回执正文里结果摘要的上限(字符);超出部分留在持久回执,按需读取。 */
+export const COMPLETION_RESULT_WIRE_CHARS = 1_500;
+/** 回执正文里列出的交付文件上限;其余在任务卡里。 */
+export const COMPLETION_ARTIFACTS_WIRE_LIMIT = 10;
+const OBJECTIVE_WIRE_CHARS = 400;
+const ERROR_WIRE_CHARS = 600;
+
+function clip(text: string, cap: number, omittedHint: string): string {
+ if (text.length <= cap) return text;
+ return `${text.slice(0, cap)}…(${omittedHint})`;
+}
+
+export function buildDelegationCompletionMessage(params: DelegationCompletionMessageInput): string {
+ const statusLine =
+ params.status === 'completed'
+ ? '已完成'
+ : params.status === 'cancelled'
+ ? '已取消'
+ : params.status === 'timed-out' || params.lastError?.startsWith('TIMEOUT')
+ ? '已超时'
+ : '失败了';
+ const artifacts = params.artifacts ?? [];
+ const listed = artifacts.slice(0, COMPLETION_ARTIFACTS_WIRE_LIMIT);
+ const omittedArtifacts = artifacts.length - listed.length;
+ return [
+ `[任务回执] 后台任务${statusLine}。task_id: ${params.id}`,
+ `目标事项: ${params.objective.slice(0, OBJECTIVE_WIRE_CHARS)}`,
+ params.resultSummary
+ ? `结果:\n${clip(params.resultSummary, COMPLETION_RESULT_WIRE_CHARS, '后续内容见任务卡或 check_session_task')}`
+ : '',
+ listed.length
+ ? `交出的文件(${artifacts.length}):\n${listed.map((item) => `- ${item.absolutePath}`).join('\n')}${
+ omittedArtifacts > 0 ? `\n- …另有 ${omittedArtifacts} 个,见任务卡` : ''
+ }`
+ : '',
+ params.lastError ? `失败原因: ${clip(params.lastError, ERROR_WIRE_CHARS, '已截断')}` : '',
+ '据此接手继续当前工作;要让执行者接着做,用 `message_session_task`(带 task_id),不必重新发起。回复用户时不要复述本条回执或提及内部编号。',
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+}
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index ec1a866bcd..cf5e6a7316 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -30,6 +30,7 @@ import { UI_ACTION_TRIGGER_PREFIX } from '../../shared/interruptedTurn.js';
import { createLogger } from '../logger.js';
import { resolveBusinessSessionId } from '../sessionIds.js';
import { registerBotDelegationParentCancellation } from './botDelegationLifecycle.js';
+import { buildDelegationCompletionMessage } from './botDelegationCompletionMessage.js';
import { classifyBotDelegationDispatchFailure } from './botDelegationDispatchOutcome.js';
import { resolveBotCanonicalSession } from './botCanonicalSessionRegistry.js';
import type {
@@ -895,30 +896,18 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
clearCompletionRetryTimer(params.id);
return false;
}
- const taskSubject = '后台任务';
- const statusLine =
- params.status === 'completed'
- ? '已完成'
- : params.status === 'cancelled'
- ? '已取消'
- : params.status === 'timed-out' || params.lastError?.startsWith('TIMEOUT')
- ? '已超时'
- : '失败了';
const artifacts = params.artifacts ?? [];
// 发给模型的回执正文不带 [UI_ACTION_TRIGGER] 前缀;前缀只留在落库 / 排队可见内容上,
// 让这条主机内部消息在时间线与排队区保持隐藏(同 botDirectMessageService 的私信)。
- const completionMessage = [
- `[任务回执] ${taskSubject}${statusLine}。task_id: ${params.id}`,
- `目标事项: ${params.objective.slice(0, 400)}`,
- params.resultSummary ? `结果:\n${params.resultSummary}` : '',
- artifacts.length
- ? `交出的文件(${artifacts.length}):\n${artifacts.slice(0, 20).map((item) => `- ${item.absolutePath}`).join('\n')}`
- : '',
- params.lastError ? `失败原因: ${params.lastError}` : '',
- '当前时间线里的任务卡已更新到终态,交付文件清单也在卡片里。直接依据结果接手继续当前工作;结果不够或还想让执行者接着做,用 `message_session_task`(带 task_id)继续说,不必重新发起。回复用户时不要复述本条回执,也不要提及任何内部编号。',
- ]
- .filter(Boolean)
- .join('\n\n');
+ // 正文有界(结果摘要 / 文件清单截断):完整结果在下面持久化的回执行里,模型按需读取。
+ const completionMessage = buildDelegationCompletionMessage({
+ id: params.id,
+ objective: params.objective,
+ status: params.status,
+ resultSummary: params.resultSummary,
+ artifacts,
+ lastError: params.lastError,
+ });
try {
if (!(await completionStillPending())) {
clearCompletionRetryTimer(params.id);
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index 6909ed035d..6595964308 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -43,6 +43,7 @@ import { buildWireMessageSourceNote, readWireSourceDevice, readWireSourcePlugin
import { buildCindyMakeTaskNote } from '../cindy-make/taskNote.js';
import { getResolvedMainLocale } from '../i18n.js';
import { buildUiLanguageErrorNote, turnUiLanguageFromSendOpts } from './uiLanguageErrorNote.js';
+import type { RepeatableWireNotes, WireNotePlan } from './wireNoteMemory.js';
import {
excludeDirectoryGrantConflicts,
directoryGrantsForRuntime,
@@ -544,6 +545,16 @@ export interface MakerSendTransactionDeps {
* 命中时每轮把任务说明追加到 wire 用户消息(不落库、不显示),见 cindy-make/taskNote.ts。
*/
isCindyMakeSession?(sessionId: string): Promise<boolean>;
+ /**
+ * 逐轮环境说明去重(见 wireNoteMemory.ts):返回本轮真正要前置的段;与上一次已被
+ * 引擎接受的内容相同的段不再重复。`force` 在交接首条(原生上下文刚重建)时整体重发。
+ * 缺省(未注入)= 每轮全发,行为与旧版一致。
+ */
+ planRepeatableWireNotes?(
+ sessionId: string,
+ notes: RepeatableWireNotes,
+ opts: { force: boolean },
+ ): WireNotePlan;
log: MakerSendTransactionLog;
workdirDiagnostics?: WorkdirDiagnosticLogger;
}
@@ -1330,30 +1341,43 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
// context 盖章);没有设备信息时沿用旧的手机判据(直连走 deps 注入的 async context,
// 排队走 so.fromMobileClient)。
const sourceDevice = readWireSourceDevice(so.sourceDevice);
- const mobileClientNote = shouldPrependMobileClientPromptNote(normalized, sess.agentKind)
+ const allowsEnvironmentNotes = shouldPrependMobileClientPromptNote(normalized, sess.agentKind);
+ const mobileClientNote = allowsEnvironmentNotes
? buildClientEnvironmentNote({
device: sourceDevice,
host: sourceDevice ? deps.readHostDeviceIdentity?.() : undefined,
legacyMobile: deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true,
})
: null;
- const withMobileNote = mobileClientNote
- ? prependNoteToWireUserMessage(withSourceNote as HandoffWireMessage, mobileClientNote)
- : withSourceNote;
// 个人版制作任务说明:与手机说明同层、同占位规则(原生命令必须留在消息开头)。
const cindyMakeNote =
(await deps.isCindyMakeSession?.(sessionId).catch(() => false)) === true &&
- shouldPrependMobileClientPromptNote(normalized, sess.agentKind)
+ allowsEnvironmentNotes
? buildCindyMakeTaskNote()
: null;
- const withCindyMakeNote = cindyMakeNote
- ? prependNoteToWireUserMessage(withMobileNote as HandoffWireMessage, cindyMakeNote)
- : withMobileNote;
- const uiLanguageNote = shouldPrependMobileClientPromptNote(normalized, sess.agentKind)
+ const uiLanguageNote = allowsEnvironmentNotes
? buildUiLanguageErrorNote(turnUiLanguageFromSendOpts(so, getResolvedMainLocale()))
: null;
- const outgoing = uiLanguageNote
- ? prependNoteToWireUserMessage(withCindyMakeNote as HandoffWireMessage, uiLanguageNote)
+ // 这三段是"环境说明":同一原生上下文里内容没变就不重复发(wireNoteMemory)。交接首条
+ // (原生上下文刚重建)整体重发;只有引擎接受后才记为已发送。斜杠命令轮次本来就不带
+ // 说明,也不改写记忆——它不代表模型已经看过新的环境。
+ const repeatableNotes: RepeatableWireNotes = {
+ 'client-environment': mobileClientNote,
+ 'cindy-make': cindyMakeNote,
+ 'ui-language': uiLanguageNote,
+ };
+ const wireNotePlan = allowsEnvironmentNotes
+ ? (deps.planRepeatableWireNotes?.(sessionId, repeatableNotes, { force: pendingHandoff !== null }) ?? null)
+ : null;
+ const plannedNotes = wireNotePlan?.notes ?? repeatableNotes;
+ const withMobileNote = plannedNotes['client-environment']
+ ? prependNoteToWireUserMessage(withSourceNote as HandoffWireMessage, plannedNotes['client-environment'])
+ : withSourceNote;
+ const withCindyMakeNote = plannedNotes['cindy-make']
+ ? prependNoteToWireUserMessage(withMobileNote as HandoffWireMessage, plannedNotes['cindy-make'])
+ : withMobileNote;
+ const outgoing = plannedNotes['ui-language']
+ ? prependNoteToWireUserMessage(withCindyMakeNote as HandoffWireMessage, plannedNotes['ui-language'])
: withCindyMakeNote;
const meta = await deps.getSessionMeta(sessionId).catch(() => null);
let persistUserMessage = readPersistUserMessageOption(so);
@@ -1741,6 +1765,8 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
// 只有跨过不可逆 dispatch 边界才消费;未派发保留 pending 下次重试。
deps.consumePendingHandoff?.(sessionId);
}
+ // 环境说明同样只在引擎接受后记为已发送;被拒 / 抛错时下次照常重发。
+ if (sendResult.accepted) wireNotePlan?.commit();
if (workdirRecoveryNote && sendResult.accepted) {
deps.consumeWorkingDirectoryRecoveryNote?.(sessionId, workdirRecoveryNote);
}
diff --git a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts
index 5737c03b4e..2c987f6837 100644
--- a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts
+++ b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts
@@ -22,6 +22,8 @@ import {
* 追加在 wire 消息上,与 IM 渠道说明(hook-control/outbound.buildHookPromptNote)
* 及引擎交接前缀(agentHandoff.prependHandoffToUserMessage)同一层、同一套语义:
* **只进喂给 agent 的内容,不进落库/显示的用户消息原话。**
+ * 「逐轮」不等于每轮都重复一份:同一原生上下文里内容没变就不再前置(wireNoteMemory.ts),
+ * 换窗、原生压缩、/clear 之后整体重发一次——长对话里几十份一模一样的说明只占窗口。
*
* ── 与代码职责的分界(§2 能用代码保证的不甩给 prompt) ────────────────────
* 「产出物在手机上打不开」已经由代码解决:手机端能渲染 HTML 并把同目录资源取回来。
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 82a4ec60bd..42355f12e0 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -600,6 +600,7 @@ import {
type BotCompactRuntimeRefreshOutcome,
type BotCompactRuntimeSession,
} from './botCompactRuntimeRefresh.js';
+import { createWireNoteMemory } from './wireNoteMemory.js';
import { isBotCanonicalReplacementBusy } from './botCanonicalReplacementGuard.js';
import { configureBotCanonicalReplacementCoordinator } from './botCanonicalReplacementCoordinator.js';
import { botSessionInputBlockReason, isShadowedCompanionCanonical, SHADOWED_COMPANION_INPUT_MESSAGE } from './botSessionInputGuard.js';
@@ -3260,6 +3261,11 @@ type BotCompactRuntimeRefreshHandler = (
* and let the instance-scoped coordinator own all compact settle signals.
*/
let botCompactRuntimeRefreshHandler: BotCompactRuntimeRefreshHandler | null = null;
+/**
+ * 逐轮环境说明(界面语言 / 客户端设备 / 个人版制作说明)的去重记忆:同一原生上下文里内容
+ * 没变就不重复前置。原生压缩边界、`/clear`、换窗重建后整体重发一次(见 wireNoteMemory.ts)。
+ */
+const wireNoteMemory = createWireNoteMemory();
const botCompactRuntimeRefreshCoordinator = createBotCompactRuntimeRefreshCoordinator({
hasPendingInteraction: hasPendingAgentInteractionForSession,
refresh: (session, boundary) =>
@@ -5477,6 +5483,7 @@ const sessionEventDependencies: SessionEventDependencies = {
onUnsuccessfulProductTurn: interruptProductTurn,
deferUnsuccessfulProductTurn: (owner) => deferredProductTurnFailureGate.defer(owner),
get botCompactRuntimeRefreshCoordinator() { return botCompactRuntimeRefreshCoordinator; },
+ get wireNoteMemory() { return wireNoteMemory; },
get attemptBotCompactRuntimeRefresh() { return attemptBotCompactRuntimeRefresh; },
get botDelegationServiceHolder() { return botDelegationServiceHolder; },
get botGroupChatServiceHolder() { return botGroupChatServiceHolder; },
@@ -16242,6 +16249,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 调用方自报;与手机说明同层(只进 wire 消息)。
isCindyMakeSession: async (sessionId) =>
(await readSessionSource(sessionId)) === CINDY_MAKE_SESSION_SOURCE,
+ planRepeatableWireNotes: (sessionId, notes, opts) => wireNoteMemory.plan(sessionId, notes, opts),
applyPendingAgentSwitch: async (sessionId, options) => {
await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId);
// Queued Orca delivery and resume both use this transaction. A failed
@@ -16497,6 +16505,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// overflow 终态已先走 coordinator onTurnEvent('error'),会留下 active-turn
// recovery 和错误横幅。重放绕开 coordinator,随后的 done 会被 recovery 吃掉。
agentInputCoordinatorHolder?.clearError(sessionId);
+ // 新原生上下文没看过任何环境说明:下一轮整体重发(重放路径不经 send 事务)。
+ wireNoteMemory.reset(sessionId);
},
getRecoveryAbortSignal: (sessionId) => {
const coordinator = agentInputCoordinatorHolder!;
@@ -16718,21 +16728,27 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 设备来源只认盖章值(coordinator 透传 / 直连 IPC 边界按 async context 盖);没有设备
// 信息时沿用旧手机判据:IPC 直连 steer 时 async context 在;coordinator 投递时靠透传。
const steerDevice = readWireSourceDevice(so.sourceDevice);
- const steerNote = shouldPrependMobileClientPromptNote(normalized, sess.agentKind)
+ const steerAllowsEnvironmentNotes = shouldPrependMobileClientPromptNote(normalized, sess.agentKind);
+ const steerNote = steerAllowsEnvironmentNotes
? buildClientEnvironmentNote({
device: steerDevice,
host: steerDevice ? getHostSourceDevice() : undefined,
legacyMobile: isMobileControllerInvoke() || so.fromMobileClient === true,
})
: null;
- const withSteerNote = steerNote
- ? prependNoteToWireUserMessage(withSteerSourceNote as HandoffWireMessage, steerNote)
- : withSteerSourceNote;
- const steerLanguageNote = shouldPrependMobileClientPromptNote(normalized, sess.agentKind)
+ const steerLanguageNote = steerAllowsEnvironmentNotes
? buildUiLanguageErrorNote(turnUiLanguageFromSendOpts(so, getResolvedMainLocale()))
: null;
- const steerPayload = steerLanguageNote
- ? prependNoteToWireUserMessage(withSteerNote as HandoffWireMessage, steerLanguageNote)
+ // 环境说明与 send 事务共用同一份去重记忆:插话进的是同一个原生上下文。
+ const steerNotePlan = steerAllowsEnvironmentNotes
+ ? wireNoteMemory.plan(sessionId, { 'client-environment': steerNote, 'ui-language': steerLanguageNote }, { force: false })
+ : null;
+ const steerPlannedNotes = steerNotePlan?.notes ?? {};
+ const withSteerNote = steerPlannedNotes['client-environment']
+ ? prependNoteToWireUserMessage(withSteerSourceNote as HandoffWireMessage, steerPlannedNotes['client-environment'])
+ : withSteerSourceNote;
+ const steerPayload = steerPlannedNotes['ui-language']
+ ? prependNoteToWireUserMessage(withSteerNote as HandoffWireMessage, steerPlannedNotes['ui-language'])
: withSteerNote;
try {
const remote = isDeviceLinkInvoke();
@@ -16758,6 +16774,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
[AUTO_REVIEW_DELEGATED_CONTINUATION]: so[AUTO_REVIEW_DELEGATED_CONTINUATION],
[AUTO_REVIEW_USER_INTENT]: restoredSteerIntent,
});
+ steerNotePlan?.commit();
log.info('steer: delivered', { sessionId, agentKind: sess.agentKind });
} catch (err) {
const messageText = err instanceof Error ? err.message : String(err);
@@ -19737,6 +19754,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// DB 重建,把旧交接捞回来再缓存住。墓碑同步生效,窗口内的 send 立刻拿到 null;
// clear 纪元则要等下面 cleared_at 落库之后才推进。
agentHandoffPending.invalidate(sid);
+ // 清空后的原生上下文没看过任何环境说明:下一轮整体重发。
+ wireNoteMemory.reset(sid);
getAgentIslandService()?.notifyQueueEmptied(sid);
// 清上下文后,active 目标失去其依据(objective 引用的内容已被抹掉)→ 一并清除目标。
goalClearObserver?.(sid);
diff --git a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
index 5baf4843c9..65a6699ac8 100644
--- a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
@@ -129,6 +129,11 @@ export interface PrepareSessionEventDeps {
event: AgentEvent,
) => boolean;
readonly isGatewayProxyTokenRecoveryErrorEvent: (sessionId: string, event: AgentEvent) => boolean;
+ /**
+ * 逐轮环境说明的去重记忆(wireNoteMemory.ts)。原生自动压缩后摘要可能已丢掉旧说明,
+ * 下一轮要整体重发一次;缺省(未注入)不去重,行为同旧版。
+ */
+ readonly wireNoteMemory?: { reset(sessionId: string): void };
}
export function prepareSessionEvent(
@@ -141,6 +146,7 @@ export function prepareSessionEvent(
// potentially multi-megabyte payload to every renderer and device-link controller.
if (event.type === 'turn_diff') return;
if (event.type === 'compact_boundary') deps.botCompactRuntimeRefreshCoordinator.noteBoundary(session);
+ if (event.type === 'compact_boundary') deps.wireNoteMemory?.reset(session.id);
if (
event.turnScope === 'background' &&
Object.prototype.hasOwnProperty.call(event, 'backgroundTurnStartedAt') &&
diff --git a/apps/desktop/src/main/maker-ipc/uiLanguageErrorNote.ts b/apps/desktop/src/main/maker-ipc/uiLanguageErrorNote.ts
index b07e17a028..68f2f8ab51 100644
--- a/apps/desktop/src/main/maker-ipc/uiLanguageErrorNote.ts
+++ b/apps/desktop/src/main/maker-ipc/uiLanguageErrorNote.ts
@@ -49,7 +49,9 @@ export function turnUiLanguageFromSendOpts(
/**
* Per-turn note for the model only. It is not part of the cached system prompt:
* the viewing client can change between turns, and a locale must not enter the
- * stable prefix. The note text is fixed for each supported locale.
+ * stable prefix. The note text is fixed for each supported locale, so the send
+ * paths only repeat it when the locale changes or the native context was rebuilt,
+ * compacted or cleared (see wireNoteMemory.ts).
*/
export function buildUiLanguageErrorNote(locale: SupportedLocale): string {
const name = INTERFACE_LANGUAGE_NAME[locale];
diff --git a/apps/desktop/src/main/maker-ipc/wireNoteMemory.ts b/apps/desktop/src/main/maker-ipc/wireNoteMemory.ts
new file mode 100644
index 0000000000..46fa2c7d4a
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/wireNoteMemory.ts
@@ -0,0 +1,76 @@
+/**
+ * 逐轮环境说明的去重记忆:同一原生上下文里,内容没变的说明不再重复前置。
+ *
+ * 发给模型的 wire 消息会前置几段"系统每轮自动追加"的环境说明(界面语言、客户端设备、
+ * 个人版制作任务说明)。它们刻意不进 system prompt(控制端会中途切换,易变内容只能进
+ * per-call 段,见 mobileClientPromptNote.ts 头注释),代价是**每一轮**都重复一遍,并随
+ * 用户消息一起被原生引擎持久化:长对话压缩后仍能剩下近百份一模一样的界面语言说明,
+ * 既占窗口,又稀释压缩摘要。宿主无法事后从原生历史里剥掉它们,只能在发送时少发。
+ *
+ * 规则(按 session 记上一次**已被引擎接受**的各段原文):
+ * - 本轮某段与上次相同 → 不发;不同(含从无到有)→ 发;从有到无 → 不发但记住"无"。
+ * - 原生上下文失去连续性时必须整体重发一次:换窗 / 引擎切换的交接首条(调用方传
+ * `force`)、原生自动压缩边界之后、`/clear` 之后(调用方 `reset`)。原生摘要可能已经
+ * 把旧说明丢掉,宿主拿不到摘要内容,只能保守重发。
+ * - 进程重启后记忆为空,首轮多发一次,方向保守。
+ *
+ * 只有跨过不可逆 dispatch 边界(accepted)才 `commit`;被拒 / 抛错不记,下次照常重发。
+ * `[消息来源]` 不在此列:它陈述的是"本条"由谁发,逐条都要带。
+ */
+
+export type RepeatableWireNoteKind = 'ui-language' | 'client-environment' | 'cindy-make';
+
+export type RepeatableWireNotes = Partial<Record<RepeatableWireNoteKind, string | null>>;
+
+export interface WireNotePlan {
+ /** 本轮真正要前置的段(已去掉与上次相同的)。 */
+ readonly notes: RepeatableWireNotes;
+ /** 引擎接受后调用,把本轮各段原文(含 null)记为上一次已发送状态。 */
+ commit(): void;
+}
+
+export interface WireNoteMemory {
+ plan(sessionId: string, notes: RepeatableWireNotes, opts?: { force?: boolean }): WireNotePlan;
+ /** 原生上下文失去连续性(压缩边界 / clear / 重建):下一轮整体重发。 */
+ reset(sessionId: string): void;
+}
+
+const KINDS: readonly RepeatableWireNoteKind[] = ['ui-language', 'client-environment', 'cindy-make'];
+
+export function createWireNoteMemory(): WireNoteMemory {
+ const lastSent = new Map<string, Map<RepeatableWireNoteKind, string | null>>();
+ /**
+ * 每个会话的重置代次:plan 时记下,commit 时核对。发送在途(Pi 受理前可能先压缩)
+ * 期间发生 reset,代次已变,旧 plan 的 commit 不能把"已发过"写回去——否则下一轮
+ * 继续省略,而新原生上下文其实没看过这些说明。
+ */
+ const resetEpoch = new Map<string, number>();
+ const epochOf = (sessionId: string): number => resetEpoch.get(sessionId) ?? 0;
+ return {
+ plan(sessionId, notes, opts) {
+ const previous = lastSent.get(sessionId);
+ const epoch = epochOf(sessionId);
+ const planned: RepeatableWireNotes = {};
+ for (const kind of KINDS) {
+ const text = notes[kind] ?? null;
+ if (text === null) continue;
+ // 没有记忆(首轮 / 重启 / reset 之后)或调用方要求整体重发时全发。
+ if (opts?.force || !previous || previous.get(kind) !== text) planned[kind] = text;
+ }
+ return {
+ notes: planned,
+ commit() {
+ // plan 之后 reset 过:这份计划面对的是旧上下文,不记为已发送,下一轮整体重发。
+ if (epochOf(sessionId) !== epoch) return;
+ const next = new Map<RepeatableWireNoteKind, string | null>();
+ for (const kind of KINDS) next.set(kind, notes[kind] ?? null);
+ lastSent.set(sessionId, next);
+ },
+ };
+ },
+ reset(sessionId) {
+ lastSent.delete(sessionId);
+ resetEpoch.set(sessionId, epochOf(sessionId) + 1);
+ },
+ };
+}