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。

feat(desktop): fork 会话向模型注入来源标记,handoff 文本改英文 (#701)

Dashb11d2c3de156
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
index 3ddc30f74a..c303e96057 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
@@ -43,6 +43,8 @@ vi.mock('../../client/current', () => ({
import {
findParkedEngineSession,
findPendingAgentHandoff,
+ findForkParentSessionId,
+ findPendingForkOrigin,
getMessageDeletionTarget,
markLatestAgentHandoffConsumed,
readPriorUserRoundCost,
@@ -54,7 +56,10 @@ function createDb(): Database.Database {
sqlite.exec(`
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
- cleared_at INTEGER
+ cleared_at INTEGER,
+ parent_session_id TEXT,
+ created_at INTEGER NOT NULL DEFAULT 0,
+ total_token_usage INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE messages (
id TEXT PRIMARY KEY,
@@ -273,6 +278,137 @@ describe('local-db:messages:list cursor', () => {
});
});
+describe('findPendingForkOrigin 来源标记重建', () => {
+ const FORK_AT = 5_000;
+
+ function insertForkedSession(
+ sqlite: Database.Database,
+ parent: string | null,
+ totalTokenUsage = 0,
+ ): void {
+ sqlite
+ .prepare(
+ 'INSERT INTO sessions (id, cleared_at, parent_session_id, created_at, total_token_usage) VALUES (?, NULL, ?, ?, ?)',
+ )
+ .run('s1', parent, FORK_AT, totalTokenUsage);
+ }
+
+ function insertRowAt(
+ sqlite: Database.Database,
+ role: 'user' | 'assistant',
+ createdAt: number,
+ ): void {
+ sqlite
+ .prepare(
+ `
+ INSERT INTO messages (
+ id, client_id, session_id, role, content, tool_use_id, agent_meta,
+ agent_kind, created_at, rewind_at
+ ) VALUES (?, ?, 's1', ?, '"q"', NULL, NULL, 'cc', ?, NULL)
+ `,
+ )
+ .run(`${role}-${createdAt}`, `${role}-${createdAt}`, role, createdAt);
+ }
+
+ it('fork 后尚未跑过一轮:返回父会话 id(重启后同样可重建,不依赖内存态)', async () => {
+ const sqlite = createDb();
+ insertForkedSession(sqlite, 'parent-1');
+ await expect(findPendingForkOrigin('s1')).resolves.toBe('parent-1');
+ });
+
+ it('子会话跑过一轮(token 已累加且该轮 user 行仍存活)后不再返回', async () => {
+ const sqlite = createDb();
+ insertForkedSession(sqlite, 'parent-1', 1_234);
+ insertRowAt(sqlite, 'user', FORK_AT + 10);
+ await expect(findPendingForkOrigin('s1')).resolves.toBeNull();
+ });
+
+ it('Codex 回滚掉首个 post-fork turn 后重新 arm(token 计数不随 rewind 回退)', async () => {
+ // rewind 把该轮的 user / assistant 都标上 rewind_at,但 total_token_usage 留在原地;
+ // 只看 token 会让「回滚后重发」的 Codex 会话永远拿不回来源标记。
+ const sqlite = createDb();
+ insertForkedSession(sqlite, 'parent-1', 4_321);
+ sqlite
+ .prepare(
+ `INSERT INTO messages (
+ id, client_id, session_id, role, content, tool_use_id, agent_meta,
+ agent_kind, created_at, rewind_at
+ ) VALUES ('u-r', 'u-r', 's1', 'user', '"q"', NULL, NULL, 'codex', ?, ?)`,
+ )
+ .run(FORK_AT + 10, FORK_AT + 50);
+ sqlite
+ .prepare(
+ `INSERT INTO messages (
+ id, client_id, session_id, role, content, tool_use_id, agent_meta,
+ agent_kind, created_at, rewind_at
+ ) VALUES ('a-r', 'a-r', 's1', 'assistant', '"a"', NULL, NULL, 'codex', ?, ?)`,
+ )
+ .run(FORK_AT + 20, FORK_AT + 50);
+ await expect(findPendingForkOrigin('s1')).resolves.toBe('parent-1');
+ });
+
+ it('Codex 首轮完成(token>0 且 user 行存活)判定已消费', async () => {
+ const sqlite = createDb();
+ insertForkedSession(sqlite, 'parent-1', 4_321);
+ insertRowAt(sqlite, 'user', FORK_AT + 10);
+ await expect(findPendingForkOrigin('s1')).resolves.toBeNull();
+ });
+
+ it('Claude 会话(token 列恒为 0)靠 assistant 行判定已跑过一轮', async () => {
+ // recordSessionTurnTokens 只在 register.ts 的 codex done 分支调用,Claude 的
+ // total_token_usage 永远是 0;只认 token 会让 Claude fork 每次重启都重复注入。
+ const sqlite = createDb();
+ insertForkedSession(sqlite, 'parent-1');
+ insertRowAt(sqlite, 'assistant', FORK_AT + 10);
+ await expect(findPendingForkOrigin('s1')).resolves.toBeNull();
+ });
+
+ it('fork 后 /clear 过:不再注入(历史已被用户显式重置)', async () => {
+ const sqlite = createDb();
+ sqlite
+ .prepare(
+ 'INSERT INTO sessions (id, cleared_at, parent_session_id, created_at, total_token_usage) VALUES (?, ?, ?, ?, 0)',
+ )
+ .run('s1', FORK_AT + 100, 'parent-1', FORK_AT);
+ await expect(findPendingForkOrigin('s1')).resolves.toBeNull();
+ await expect(findForkParentSessionId('s1')).resolves.toBeNull();
+ });
+
+ it('findForkParentSessionId 不受首发消费影响:切引擎/删消息重建上下文仍带血缘', async () => {
+ // 首轮已跑完(token 已累加)→ 一次性标记该消费;但 fork 是永久属性,
+ // 重建原生上下文时仍要带上,否则新上下文不知道自己是分叉。
+ const sqlite = createDb();
+ insertForkedSession(sqlite, 'parent-1', 5_000);
+ insertRowAt(sqlite, 'user', FORK_AT + 10);
+ await expect(findPendingForkOrigin('s1')).resolves.toBeNull();
+ await expect(findForkParentSessionId('s1')).resolves.toBe('parent-1');
+ });
+
+ it('已知边界:导入会话的合成时间戳会让来源标记漏注入一次(方向安全,故意接受)', async () => {
+ // importer 为强制行序写 createdAt+sequence / timestamp+lineNo,长 transcript 的
+ // 末尾行能超出真实墙钟数秒。此时复制来的 assistant 会被算成子会话自己的回应。
+ // 记录为已接受的取舍:方向是漏一次,而不是把内部说明重复灌给模型。
+ const sqlite = createDb();
+ insertForkedSession(sqlite, 'parent-1');
+ insertRowAt(sqlite, 'assistant', FORK_AT + 9_000);
+ await expect(findPendingForkOrigin('s1')).resolves.toBeNull();
+ });
+
+ it('goal 路径先落 user 行再 peek:仍返回父会话 id(不被 pre-dispatch 持久化骗过)', async () => {
+ // GoalController.setGoal 先 persistUserMessage 再 fireTurn→peek。
+ const sqlite = createDb();
+ insertForkedSession(sqlite, 'parent-1');
+ insertRowAt(sqlite, 'user', FORK_AT + 5);
+ await expect(findPendingForkOrigin('s1')).resolves.toBe('parent-1');
+ });
+
+ it('非 fork 会话恒为 null', async () => {
+ const sqlite = createDb();
+ insertForkedSession(sqlite, null, 999);
+ await expect(findPendingForkOrigin('s1')).resolves.toBeNull();
+ });
+});
+
describe('findPendingAgentHandoff 持久消费位', () => {
function insertBoundary(
sqlite: Database.Database,
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index cca04f3688..acefd56d1e 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -7,7 +7,7 @@
*/
import { ipcMain, BrowserWindow } from 'electron';
-import { and, asc, count, eq, lt, gt, desc, isNull, or, sql, type SQL } from 'drizzle-orm';
+import { and, asc, count, eq, lt, gt, gte, desc, isNull, or, sql, type SQL } from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
import { getDbClient } from '../client/current';
@@ -1492,6 +1492,114 @@ export async function findPendingAgentHandoff(sessionId: string): Promise<string
return handoff;
}
+/**
+ * 查 fork 出的子会话是否还欠一条「来源标记」——返回父会话 id,不欠则 null。
+ *
+ * 判定"子会话是否已经自己跑过一轮",两个信号取**或**——单用任一个都有整条引擎
+ * 线失效。按代码里的判定顺序:
+ * 1. 存在未 rewind 的 assistant 行(`createdAt >= session.createdAt`):引擎无关的
+ * 主信号,带 rewind_at 过滤,所以回滚掉首个 post-fork turn 后会自动失效;
+ * 2. `total_token_usage > 0` **且**存在未 rewind 的 user 行:Codex 补充——Claude
+ * 完成路径不累加该列(recordSessionTurnTokens 的唯一调用点在 register.ts 的
+ * `event.source === 'codex'` done 分支),而 token 计数不随 rewind 回退,所以必须
+ * 搭配一条仍存活的 user 行才作数。
+ *
+ * 精度边界(都落在信号一的时间戳比较上,方向不同):
+ * - **漏注入一次**:外部导入的会话里 createdAt 是**合成**的,importer 故意写
+ * `createdAt + sequence`(claude-local-sessions.ts)与 `timestamp + lineNo`
+ * (codex-local-sessions.ts)来强制行序,长 transcript 的末尾行能超出真实墙钟
+ * 好几秒;fork 这类会话时,复制来的 assistant 可能被算成子会话自己的回应。
+ * 同毫秒边界(复制行与 fork 操作同一毫秒)同理。
+ * - **多注入一次**:一轮跑完但 usage 上报失败、或 turn 中途重启。
+ *
+ * 为什么不看 user 行:goal 路径的 setGoal 先 persistUserMessage 再 fireTurn→peek
+ * (goal-host/controller.ts),dispatch 前就落了 user 行,会把 fork 后首个动作是
+ * /goal 的会话误判成已发送。assistant 只在模型确实回应后才出现,没这个问题。
+ *
+ * 为什么不加持久消费位:写 messages 隐藏边界行会让该会话之后再也不能被 fork
+ * (resolveForkNativeSource 见到 context_rebuild 即判 UNSUPPORTED_HISTORY);
+ * 加 schema 列则是为一个元信息付一次 migration。两者的代价都高于上述边角。
+ */
+export async function findPendingForkOrigin(sessionId: string): Promise<string | null> {
+ const db = getDbClient().drizzle;
+ const [sessRow] = await db
+ .select({
+ parentSessionId: sessions.parentSessionId,
+ createdAt: sessions.createdAt,
+ clearedAt: sessions.clearedAt,
+ totalTokenUsage: sessions.totalTokenUsage,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (!sessRow?.parentSessionId) return null;
+ // fork 之后 /clear 过:渲染历史与原生上下文都被显式重置成新对话,再把来源标记
+ // 灌进去等于往用户主动清空的上下文里塞旧元信息。
+ if (sessRow.clearedAt !== null && sessRow.clearedAt >= sessRow.createdAt) return null;
+ // 信号一(引擎无关):子会话自己产生过 assistant 行。带 rewindAt 过滤,所以回滚掉
+ // 首个 post-fork turn 之后该信号会自动失效——标记重新 arm,正是期望行为。
+ const [assistantAfterFork] = await db
+ .select({ id: messages.id })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.sessionId, sessionId),
+ eq(messages.role, 'assistant'),
+ isNull(messages.rewindAt),
+ gte(messages.createdAt, sessRow.createdAt),
+ ),
+ )
+ .limit(1);
+ if (assistantAfterFork) return null;
+ // 信号二(Codex 补充):Claude 完成路径不累加 total_token_usage(唯一调用点在
+ // register.ts 的 codex done 分支),所以只有 Codex 会走到这里。**必须搭配一条仍
+ // 存活的 user 行**才作数:token 计数不随 rewind 回退,单看它会让"回滚掉首个
+ // post-fork turn 再重发"的 Codex 会话永远拿不回来源标记。
+ if ((sessRow.totalTokenUsage ?? 0) > 0) {
+ const [userAfterFork] = await db
+ .select({ id: messages.id })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.sessionId, sessionId),
+ eq(messages.role, 'user'),
+ isNull(messages.rewindAt),
+ gte(messages.createdAt, sessRow.createdAt),
+ ),
+ )
+ .limit(1);
+ if (userAfterFork) return null;
+ }
+ return sessRow.parentSessionId;
+}
+
+/**
+ * 只看 fork 血缘,不看首发消费态——给"重建原生上下文"用。
+ *
+ * 与 findPendingForkOrigin 的区别在语义:后者管的是"首发那一次性的来源标记",
+ * 跑过一轮就该消费掉;而 fork 这个**事实**是会话的永久属性。引擎切换与消息删除
+ * 会从持久消息重新拼出一份交接、创建新的原生上下文,那份交接是纯粹按 messages
+ * 重建的,不含任何 fork 信息——若这里也跟着"已消费"一起沉默,新原生上下文就再也
+ * 不知道自己是分叉出来的。
+ *
+ * /clear 之后同样抑制:那时历史已被用户显式重置,血缘不该再进新上下文。
+ */
+export async function findForkParentSessionId(sessionId: string): Promise<string | null> {
+ const db = getDbClient().drizzle;
+ const [sessRow] = await db
+ .select({
+ parentSessionId: sessions.parentSessionId,
+ createdAt: sessions.createdAt,
+ clearedAt: sessions.clearedAt,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (!sessRow?.parentSessionId) return null;
+ if (sessRow.clearedAt !== null && sessRow.clearedAt >= sessRow.createdAt) return null;
+ return sessRow.parentSessionId;
+}
+
/**
* session-agent-switch:读取交接素材——本会话未被 rewind、晚于 /clear 边界的
* 最近 limit 行(时间正序返回),只取交接需要的最小投影。
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
index 05637ca0ff..25b410331e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ buildForkOriginHandoff,
+ composeForkOriginHandoff,
buildHandoffText,
createAgentHandoffPendingRegistry,
extractPlainText,
@@ -67,8 +69,8 @@ describe('buildHandoffText', () => {
const text = buildHandoffText([msg('user', '第一个问题'), msg('assistant', '第一个回答')], opts);
expect(text).toContain('Claude Code');
expect(text).toContain('Codex');
- expect(text).toContain('不要向用户提及本段交接说明');
- expect(text.trimEnd().endsWith('== 交接说明结束,以下是用户的新消息 ==')).toBe(true);
+ expect(text).toContain('Do not mention this handoff note to the user');
+ expect(text.trimEnd().endsWith("== End of handoff note; the user's new message follows ==")).toBe(true);
});
it('最近轮次逐字保留,更早轮次进单行提要', () => {
@@ -79,13 +81,13 @@ describe('buildHandoffText', () => {
}
const text = buildHandoffText(messages, opts);
// 最近 4 轮(4..7)逐字
- expect(text).toContain('[用户]\n问题7');
- expect(text).toContain('[助手]\n回答7');
- expect(text).toContain('[用户]\n问题4');
+ expect(text).toContain('[User]\n问题7');
+ expect(text).toContain('[Assistant]\n回答7');
+ expect(text).toContain('[User]\n问题4');
// 更早轮(0..3)在提要区
- expect(text).toContain('- 用户: 问题0');
- expect(text).toContain('回应: 回答3');
- expect(text).not.toContain('[用户]\n问题0');
+ expect(text).toContain('- User: 问题0');
+ expect(text).toContain('Reply: 回答3');
+ expect(text).not.toContain('[User]\n问题0');
});
it('工具调用渲染为 name + input 摘要,tool_result/thinking 不进正文', () => {
@@ -99,7 +101,7 @@ describe('buildHandoffText', () => {
],
opts,
);
- expect(text).toContain('[工具] Read: {"file_path":"/a.ts"}');
+ expect(text).toContain('[Tool] Read: {"file_path":"/a.ts"}');
expect(text).not.toContain('内心戏');
expect(text).not.toContain('x'.repeat(200));
});
@@ -150,6 +152,76 @@ describe('buildHandoffText', () => {
});
});
+describe('buildForkOriginHandoff', () => {
+ it('带上父会话 id,并以结束标记收尾(模型不会把它读成用户的话)', () => {
+ const text = buildForkOriginHandoff('sess-parent-1');
+ expect(text).toContain('sess-parent-1');
+ expect(text).toContain('forked by the user from another conversation');
+ expect(text.trimEnd().endsWith("== End of fork note; the user's new message follows =="))
+ .toBe(true);
+ });
+
+ it('不提分叉点——forkSessionStripEncrypted 的 forkedAtMessageId 为 null,措辞须对两种 fork 都成立', () => {
+ const text = buildForkOriginHandoff('sess-parent-3');
+ expect(text).not.toContain('at one of its messages');
+ });
+
+ it('带「不要向用户提及」约束,避免把父会话 id 泄露给用户', () => {
+ expect(buildForkOriginHandoff('sess-parent-4')).toContain('Do not mention this note or that id');
+ // 组合进交接时同样带着该约束(它在事实行里,不在独立结束段)
+ expect(composeForkOriginHandoff('sess-parent-4', 'PENDING')).toContain(
+ 'Do not mention this note or that id',
+ );
+ });
+
+ it('保持极简:不重复 agent-switch 那套摘要/检索指引(fork 的上下文本来就是完整的)', () => {
+ const text = buildForkOriginHandoff('sess-parent-2');
+ expect(text).not.toContain('search_chat_history');
+ expect(text).not.toContain('get_chat_history');
+ expect(text).not.toContain('== Work state');
+ expect(text.split('\n').filter((line) => line.trim().length > 0)).toHaveLength(3);
+ });
+});
+
+describe('composeForkOriginHandoff', () => {
+ it('无 pending 交接时等价于单独的来源标记', () => {
+ expect(composeForkOriginHandoff('sess-p', null)).toBe(buildForkOriginHandoff('sess-p'));
+ });
+
+ it('已顶到上限的交接:组合后仍不超限,且结束标记前保有空行分隔', () => {
+ const terminator = "== End of handoff note; the user's new message follows ==";
+ const capped = `${'x'.repeat(16_000 - terminator.length - 2)}\n\n${terminator}`;
+ expect(capped.length).toBe(16_000);
+
+ const text = composeForkOriginHandoff('sess-p', capped);
+
+ expect(text.length).toBeLessThanOrEqual(16_000);
+ expect(text).toContain('sess-p');
+ expect(text.trimEnd().endsWith(terminator)).toBe(true);
+ // 正文被从中部裁开后,结束标记不能直接贴在半句话后面
+ expect(text.endsWith(`\n\n${terminator}`)).toBe(true);
+ });
+
+ it('在引擎切换边界上 fork:来源标记并入 re-armed 交接,不替换它', () => {
+ // fork 事务会把复制过去的 agent_switch 边界 re-arm 成 consumed:false,
+ // 子会话首发时必须仍拿得到完整跨引擎交接——顶掉它就等于让子会话失忆。
+ const switchHandoff = buildHandoffText([msg('user', '切换前的问题')], {
+ fromLabel: 'Claude Code',
+ toLabel: 'Codex',
+ });
+ const text = composeForkOriginHandoff('sess-p', switchHandoff);
+
+ expect(text).toContain('sess-p');
+ expect(text).toContain('切换前的问题');
+ expect(text).toContain('from here on you (Codex) continue it');
+ // 来源标记在前,交接自带的结束标记统一收尾——不出现两个「以下是用户的新消息」
+ expect(text.indexOf('forked by the user')).toBeLessThan(text.indexOf('Session handoff'));
+ expect(text).not.toContain("== End of fork note");
+ expect(text.trimEnd().endsWith("== End of handoff note; the user's new message follows =="))
+ .toBe(true);
+ });
+});
+
describe('prependHandoffToUserMessage', () => {
it('string 形态直接前拼', () => {
expect(prependHandoffToUserMessage('新消息', 'HANDOFF')).toBe('HANDOFF\n\n新消息');
@@ -186,6 +258,108 @@ describe('createAgentHandoffPendingRegistry', () => {
expect(consumed).toHaveBeenCalledWith('s1');
});
+ it('内存命中也过 decorate:agent-switch 直接 set 的交接仍能并上 fork 来源标记', async () => {
+ // fork 出子会话后、首发前切引擎:切换流程走 setPendingHandoff 直接写内存,
+ // 不经 DB fallback。没有这层组合,来源标记会被整条跳过。
+ const query = vi.fn(async () => null);
+ const decorate = vi.fn(async (_sid: string, handoff: string) => `FORK-ORIGIN\n\n${handoff}`);
+ const reg = createAgentHandoffPendingRegistry(query, undefined, decorate);
+ reg.set('s1', 'SWITCH-HANDOFF');
+ expect(await reg.peek('s1')).toBe('FORK-ORIGIN\n\nSWITCH-HANDOFF');
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it('decorate 结果回写缓存:重试 peek 不重跑 DB 查询,也不会叠加', async () => {
+ const decorate = vi.fn(async (_sid: string, handoff: string) => `FORK\n\n${handoff}`);
+ const reg = createAgentHandoffPendingRegistry(async () => null, undefined, decorate);
+ reg.set('s1', 'SWITCH-HANDOFF');
+ expect(await reg.peek('s1')).toBe('FORK\n\nSWITCH-HANDOFF');
+ // 首发被拒 → 未 consume → 重试再 peek
+ expect(await reg.peek('s1')).toBe('FORK\n\nSWITCH-HANDOFF');
+ expect(decorate).toHaveBeenCalledTimes(1);
+ });
+
+ it('decorate 失败不写缓存,下次 peek 仍重试组合', async () => {
+ let fail = true;
+ const decorate = vi.fn(async (_sid: string, handoff: string) => {
+ if (fail) throw new Error('db down');
+ return `FORK\n\n${handoff}`;
+ });
+ const reg = createAgentHandoffPendingRegistry(async () => null, undefined, decorate);
+ reg.set('s1', 'SWITCH-HANDOFF');
+ expect(await reg.peek('s1')).toBe('SWITCH-HANDOFF');
+ fail = false;
+ expect(await reg.peek('s1')).toBe('FORK\n\nSWITCH-HANDOFF');
+ });
+
+ it('invalidate 留墓碑:后续 peek 直接返回 null,不回落 DB(/clear 的 cleared_at 尚未落库)', async () => {
+ const query = vi.fn(async () => 'FROM-DB-PRE-CLEAR');
+ const reg = createAgentHandoffPendingRegistry(query);
+ reg.set('s1', 'H');
+ reg.invalidate('s1');
+ expect(await reg.peek('s1')).toBeNull();
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ it('invalidate 之后的 set 可以覆盖墓碑(clear 后又切引擎)', async () => {
+ const reg = createAgentHandoffPendingRegistry(async () => null);
+ reg.invalidate('s1');
+ reg.set('s1', 'NEW-SWITCH-HANDOFF');
+ expect(await reg.peek('s1')).toBe('NEW-SWITCH-HANDOFF');
+ });
+
+ it('decorate 抛错期间发生 /clear:不退回已作废的交接', async () => {
+ let reg: ReturnType<typeof createAgentHandoffPendingRegistry>;
+ const decorate = vi.fn(async () => {
+ reg.clear('s1');
+ throw new Error('db down');
+ });
+ reg = createAgentHandoffPendingRegistry(async () => null, undefined, decorate);
+ reg.set('s1', 'STALE-HANDOFF');
+ expect(await reg.peek('s1')).toBeNull();
+ });
+
+ it('consume 后不触发 decorate(消费语义不被组合钩子破坏)', async () => {
+ const decorate = vi.fn(async (_sid: string, handoff: string) => `X${handoff}`);
+ const reg = createAgentHandoffPendingRegistry(async () => null, undefined, decorate);
+ reg.set('s1', 'H');
+ await reg.peek('s1');
+ reg.consume('s1');
+ expect(await reg.peek('s1')).toBeNull();
+ expect(decorate).toHaveBeenCalledTimes(1);
+ });
+
+ it('DB fallback 缓存的值不再 decorate:首发未 accepted 的重试不会拿到两份来源标记', async () => {
+ const query = vi.fn(async () => 'COMPOSED-BY-QUERY');
+ const decorate = vi.fn(async (_sid: string, handoff: string) => `FORK\n\n${handoff}`);
+ const reg = createAgentHandoffPendingRegistry(query, undefined, decorate);
+ expect(await reg.peek('s1')).toBe('COMPOSED-BY-QUERY');
+ // 未 accepted → 未 consume → 重试再 peek,仍是同一份,不叠加
+ expect(await reg.peek('s1')).toBe('COMPOSED-BY-QUERY');
+ expect(decorate).not.toHaveBeenCalled();
+ expect(query).toHaveBeenCalledTimes(1);
+ });
+
+ it('set 覆盖 DB 缓存后重新纳入 decorate(切换交接是新塞进来的,尚未组合)', async () => {
+ const reg = createAgentHandoffPendingRegistry(
+ async () => 'COMPOSED-BY-QUERY',
+ undefined,
+ async (_sid: string, handoff: string) => `FORK\n\n${handoff}`,
+ );
+ await reg.peek('s1');
+ reg.set('s1', 'SWITCH-HANDOFF');
+ expect(await reg.peek('s1')).toBe('FORK\n\nSWITCH-HANDOFF');
+ });
+
+ it('decorate 失败退回未组合的原值,不吞掉本来该注入的交接', async () => {
+ const decorate = vi.fn(async () => {
+ throw new Error('db down');
+ });
+ const reg = createAgentHandoffPendingRegistry(async () => null, undefined, decorate);
+ reg.set('s1', 'SWITCH-HANDOFF');
+ expect(await reg.peek('s1')).toBe('SWITCH-HANDOFF');
+ });
+
it('内存 miss 时经 DB 重建并缓存(重启恢复语义)', async () => {
const query = vi.fn(async () => 'from-db');
const reg = createAgentHandoffPendingRegistry(query);
@@ -230,7 +404,7 @@ describe('buildHandoffText 工作状态区(社区 handoff packet 口径)', () =>
],
opts,
);
- expect(text).toContain('== 工作状态(自动提取)==');
+ expect(text).toContain('== Work state (auto-extracted) ==');
expect(text).toContain('- /repo/a.ts');
expect(text).toContain('- /repo/b.ts');
expect(text).toContain('- /repo/c.ts');
@@ -255,13 +429,13 @@ describe('buildHandoffText 工作状态区(社区 handoff packet 口径)', () =>
it('无工具活动时不渲染工作状态区', () => {
const text = buildHandoffText([msg('user', '你好'), msg('assistant', '你好!')], opts);
- expect(text).not.toContain('== 工作状态');
+ expect(text).not.toContain('== Work state');
});
it('framing 包含「先核对工作区、以工作区为准」纪律', () => {
const text = buildHandoffText([msg('user', 'q')], opts);
expect(text).toContain('git status');
- expect(text).toContain('以工作区现状为准');
+ expect(text).toContain('the workspace always wins');
});
});
@@ -270,18 +444,20 @@ describe('buildHandoffText 早期原文检索指引', () => {
it('提供 sessionId 时附带检索指引(两个工具名 + session_ids 定向)', () => {
const text = buildHandoffText([msg('user', '你好')], { ...opts, sessionId: 'sess-abc' });
- expect(text).toContain('== 早期原文检索(需要时用)==');
- expect(text).toContain('本会话 id:sess-abc');
+ expect(text).toContain('== Retrieving earlier verbatim history (use when needed) ==');
+ expect(text).toContain('Session id: sess-abc');
expect(text).toContain('search_chat_history');
expect(text).toContain('get_chat_history');
expect(text).toContain('"session_ids":["sess-abc"]');
// 指引在结束标记之前
- expect(text.indexOf('早期原文检索')).toBeLessThan(text.indexOf('交接说明结束'));
+ expect(text.indexOf('Retrieving earlier verbatim history')).toBeLessThan(
+ text.indexOf('End of handoff note'),
+ );
});
it('不提供 sessionId 时不渲染检索指引', () => {
const text = buildHandoffText([msg('user', '你好')], opts);
- expect(text).not.toContain('早期原文检索');
+ expect(text).not.toContain('Retrieving earlier verbatim history');
expect(text).not.toContain('get_chat_history');
});
});
@@ -291,14 +467,14 @@ describe('buildHandoffText 增量(delta)模式:切回停泊引擎', () => {
it('framing 为归位续接口径,不用全量交接的"此前由 X 驱动"措辞', () => {
const text = buildHandoffText([msg('user', '离开期间的问题'), msg('assistant', '回答')], opts);
- expect(text).toContain('你(Claude Code)此前处理过本会话');
- expect(text).toContain('切回由你继续');
- expect(text).toContain('你离开期间发生的进展记录');
- expect(text).not.toContain('现在起由你(Claude Code)继续');
+ expect(text).toContain('You (Claude Code) worked on this conversation before');
+ expect(text).toContain('now it is switching back to you');
+ expect(text).toContain('a record of what happened while you were away');
+ expect(text).not.toContain('from here on you (Claude Code) continue it');
// 纪律保留:不向用户提及 + 以工作区为准
- expect(text).toContain('不要向用户提及本段交接说明');
- expect(text).toContain('以工作区现状为准');
- expect(text.trimEnd().endsWith('== 交接说明结束,以下是用户的新消息 ==')).toBe(true);
+ expect(text).toContain('Do not mention this handoff note to the user');
+ expect(text).toContain('the workspace always wins');
+ expect(text.trimEnd().endsWith("== End of handoff note; the user's new message follows ==")).toBe(true);
});
it('工作状态区按 workStateMessages(全量历史)提取,对话区只含增量', () => {
@@ -312,25 +488,25 @@ describe('buildHandoffText 增量(delta)模式:切回停泊引擎', () => {
expect(text).toContain('- /repo/early.ts'); // 全量工作状态
expect(text).toContain('离开期间的问题');
expect(text).not.toContain('最早的问题'); // 对话区不含水位线之前的内容
- expect(text).toContain('== 你离开期间的对话记录 ==');
+ expect(text).toContain('== Conversation while you were away ==');
});
it('空增量(切走后立即切回)显式说明,不留歧义', () => {
const text = buildHandoffText([], opts);
- expect(text).toContain('== 你离开期间没有新的对话消息 ==');
+ expect(text).toContain('== No new messages while you were away ==');
});
it('delta 模式同样附带检索指引(sessionId 提供时)', () => {
const text = buildHandoffText([msg('user', 'q')], { ...opts, sessionId: 'sess-d1' });
- expect(text).toContain('== 早期原文检索(需要时用)==');
+ expect(text).toContain('== Retrieving earlier verbatim history (use when needed) ==');
expect(text).toContain('"session_ids":["sess-d1"]');
});
it('full 模式(缺省)不受 delta 文案影响', () => {
const text = buildHandoffText([msg('user', 'q')], { fromLabel: 'Codex', toLabel: 'Claude Code' });
- expect(text).toContain('现在起由你(Claude Code)继续');
- expect(text).not.toContain('切回由你继续');
- expect(text).not.toContain('你离开期间没有新的对话消息');
+ expect(text).toContain('from here on you (Claude Code) continue it');
+ expect(text).not.toContain('now it is switching back to you');
+ expect(text).not.toContain('No new messages while you were away');
});
});
@@ -348,9 +524,64 @@ describe('buildHandoffText 超限收缩保住首尾', () => {
sessionId: 'sess-tail',
});
expect(text.length).toBeLessThanOrEqual(16_000);
- expect(text).toContain('== 早期原文检索(需要时用)==');
+ expect(text).toContain('== Retrieving earlier verbatim history (use when needed) ==');
expect(text).toContain('"session_ids":["sess-tail"]');
- expect(text.trimEnd().endsWith('== 交接说明结束,以下是用户的新消息 ==')).toBe(true);
+ expect(text.trimEnd().endsWith("== End of handoff note; the user's new message follows ==")).toBe(true);
+ });
+
+ /**
+ * 工具密集 + 工作状态区 + 检索指引三者叠满时,逐字区收缩到 1 轮仍会超过硬上限,
+ * 真正走到兜底截断分支(实测该构造正好顶到 16000)。英文 framing 比原中文长,
+ * 触达上限更容易;裸 slice 会把结束标记连同检索指引的尾巴一并削掉,用户的新消息
+ * 就失去了与内部历史的唯一显式分隔。
+ */
+ function capOverflowHistory(): HandoffSourceMessage[] {
+ const out: HandoffSourceMessage[] = [];
+ for (let i = 0; i < 25; i++) {
+ out.push(msg('user', `Q${i} ${'x'.repeat(3_000)}`));
+ out.push(msg('tool_use', {
+ toolUseId: `e-${i}`,
+ toolName: 'Edit',
+ input: { file_path: `/repo/very/deep/path/segment/${i}/${'d'.repeat(120)}.ts` },
+ }));
+ out.push(msg('tool_use', {
+ toolUseId: `b-${i}`,
+ toolName: 'Bash',
+ input: { command: `pnpm run something-${i} ${'c'.repeat(300)}` },
+ }));
+ out.push(msg('assistant', `A${i} ${'y'.repeat(3_000)}`));
+ }
+ for (let j = 0; j < 45; j++) {
+ out.push(msg('tool_use', {
+ toolUseId: `x-${j}`,
+ toolName: 'Read',
+ input: { file_path: `/repo/tail/${j}/${'t'.repeat(400)}.ts` },
+ }));
+ }
+ return out;
+ }
+
+ it('逐字区收缩到底仍超限时,兜底截断也必须留住结束标记(不裸 slice 削尾)', () => {
+ const text = buildHandoffText(capOverflowHistory(), {
+ fromLabel: 'Claude Code',
+ toLabel: 'Codex',
+ sessionId: 'sess-cap',
+ });
+ expect(text.length).toBe(16_000); // 确实顶到上限 = 确实走了兜底分支
+ expect(text.trimEnd().endsWith("== End of handoff note; the user's new message follows =="))
+ .toBe(true);
+ });
+
+ it('message-deletion 兜底截断留住的是重建版结束标记', () => {
+ const text = buildHandoffText(capOverflowHistory(), {
+ fromLabel: 'Codex',
+ toLabel: 'Codex',
+ sessionId: 'sess-cap',
+ reason: 'message-deletion',
+ });
+ expect(text.length).toBe(16_000);
+ expect(text.trimEnd().endsWith("== End of rebuild note; the user's new message follows =="))
+ .toBe(true);
});
it('单轮 100 条 tool_use 折叠中部,且硬上限/检索段/结束标记全部存活', () => {
@@ -368,9 +599,9 @@ describe('buildHandoffText 超限收缩保住首尾', () => {
sessionId: 'sess-tools',
});
expect(text.length).toBeLessThanOrEqual(16_000);
- expect(text).toContain('(中间 60 条工具调用略)');
- expect(text).toContain('== 早期原文检索(需要时用)==');
+ expect(text).toContain('(60 tool calls omitted)');
+ expect(text).toContain('== Retrieving earlier verbatim history (use when needed) ==');
expect(text).toContain('"session_ids":["sess-tools"]');
- expect(text.trimEnd().endsWith('== 交接说明结束,以下是用户的新消息 ==')).toBe(true);
+ expect(text.trimEnd().endsWith("== End of handoff note; the user's new message follows ==")).toBe(true);
});
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts
index c1f6050ccd..4177059384 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts
@@ -75,7 +75,7 @@ describe('performMessageDeletion', () => {
expect(handoff).toContain('keep before');
expect(handoff).toContain('keep after');
expect(handoff).not.toContain('delete me');
- expect(handoff).toContain('只把这些记录视为此前对话');
+ expect(handoff).toContain('treat only these records as the prior conversation');
expect(deps.setPendingHandoff).toHaveBeenCalledWith('s1', handoff);
expect(deps.onCommitted).toHaveBeenCalledWith(
{
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
index f031ca6f95..6de43f3217 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
@@ -562,7 +562,7 @@ describe('Phase 2:切回停泊引擎(resume + 增量交接)', () => {
const boundary = vi.mocked(deps.insertBoundaryMessage).mock.calls[0][1];
expect(boundary.resumed).toBe(true);
// 增量 framing(归位续接),且工作状态区来自全量历史
- expect(boundary.handoff).toContain('切回由你继续');
+ expect(boundary.handoff).toContain('now it is switching back to you');
expect(boundary.handoff).toContain('- /repo/a.ts');
expect(boundary.handoff).not.toContain('最早的问题');
expect(boundary.handoff).toContain('离开期间的问题');
diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
index 4bbf6f7bc7..37bf1563d1 100644
--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts
+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
@@ -97,7 +97,7 @@ const COMMAND_TOOL_NAMES = new Set(['Bash', 'shell', 'exec_command', 'local_shel
function truncate(text: string, cap: number): string {
if (text.length <= cap) return text;
- return `${text.slice(0, cap)}…(截断)`;
+ return `${text.slice(0, cap)}…(truncated)`;
}
/** 折叠换行成单行(提要区用)。 */
@@ -212,7 +212,7 @@ function splitTurns(messages: HandoffSourceMessage[]): Turn[] {
case 'assistant': {
const text = extractPlainText(msg.content);
if (text) {
- current.detailLines.push(`[助手]\n${truncate(text, RECENT_TEXT_CAP)}`);
+ current.detailLines.push(`[Assistant]\n${truncate(text, RECENT_TEXT_CAP)}`);
current.lastAssistantText = text;
}
break;
@@ -226,20 +226,20 @@ function splitTurns(messages: HandoffSourceMessage[]): Turn[] {
} catch {
inputDigest = '';
}
- current.detailLines.push(`[工具] ${name}${inputDigest ? `: ${truncate(inputDigest, TOOL_INPUT_CAP)}` : ''}`);
+ current.detailLines.push(`[Tool] ${name}${inputDigest ? `: ${truncate(inputDigest, TOOL_INPUT_CAP)}` : ''}`);
break;
}
case 'error': {
const text = extractPlainText(msg.content);
- if (text) current.detailLines.push(`[错误] ${truncate(oneLine(text), 200)}`);
+ if (text) current.detailLines.push(`[Error] ${truncate(oneLine(text), 200)}`);
break;
}
case 'ask_user': {
- current.detailLines.push('[向用户提问并获得了回答]');
+ current.detailLines.push('[Asked the user a question and got an answer]');
break;
}
case 'plan_review': {
- current.detailLines.push('[提交了计划供用户审阅]');
+ current.detailLines.push('[Submitted a plan for the user to review]');
break;
}
default:
@@ -260,7 +260,7 @@ function collapseDetailLines(lines: string[]): string[] {
const omitted = normalized.length - kept;
return [
...normalized.slice(0, DETAIL_LINES_EDGE_CAP),
- `(中间 ${omitted} 条工具调用略)`,
+ `(${omitted} tool calls omitted)`,
...normalized.slice(-DETAIL_LINES_EDGE_CAP),
];
}
@@ -276,15 +276,51 @@ export function buildHandoffText(
const turns = splitTurns(messages);
// 超出硬上限时逐档收缩逐字区(4→3→2→1 轮)重组——绝不能从尾部硬切:
// 检索指引与结束标记在尾部,是最不能丢的段。收缩到 1 轮仍超限才走最后的
- // 尾部截断保险(实际不可达:各区预算之和 < 上限)。
+ // 尾部截断保险。
for (let recentCount = RECENT_TURNS; recentCount >= 1; recentCount--) {
const text = assembleHandoffText(turns, messages, opts, recentCount);
if (text.length <= HANDOFF_HARD_CAP || recentCount === 1) {
- return text.length > HANDOFF_HARD_CAP ? text.slice(0, HANDOFF_HARD_CAP) : text;
+ return capPreservingTerminator(text, opts);
}
}
/* istanbul ignore next -- 循环必然 return */
- return assembleHandoffText(turns, messages, opts, 1).slice(0, HANDOFF_HARD_CAP);
+ return capPreservingTerminator(assembleHandoffText(turns, messages, opts, 1), opts);
+}
+
+const REBUILD_TERMINATOR = "== End of rebuild note; the user's new message follows ==";
+const HANDOFF_TERMINATOR = "== End of handoff note; the user's new message follows ==";
+const FORK_TERMINATOR = "== End of fork note; the user's new message follows ==";
+
+/** 结束标记——交接正文与"用户的新消息"之间唯一的分隔,任何情况下都要留住。 */
+function handoffTerminator(opts: BuildHandoffOptions): string {
+ return opts.reason === 'message-deletion' ? REBUILD_TERMINATOR : HANDOFF_TERMINATOR;
+}
+
+/** 拆出已有文本尾部的结束标记(含其前置空行),供二次裁剪时原样保留。 */
+function splitTrailingTerminator(text: string): [body: string, tail: string] {
+ for (const terminator of [HANDOFF_TERMINATOR, REBUILD_TERMINATOR, FORK_TERMINATOR]) {
+ const trimmed = text.trimEnd();
+ if (!trimmed.endsWith(terminator)) continue;
+ const tailStart = trimmed.length - terminator.length;
+ return [text.slice(0, tailStart), text.slice(tailStart)];
+ }
+ return [text, ''];
+}
+
+/**
+ * 兜底截断:宁可从正文中部切,也必须保住尾部的结束标记。
+ *
+ * 裸 `slice(0, CAP)` 会把结束标记连同检索指引的尾巴一起削掉,新用户消息就失去了与
+ * 内部历史的显式分隔——工具密集的长历史(逐字区已收缩到 1 轮仍超限)真会走到这里,
+ * 英文 framing 比原中文长,触达上限更容易。
+ */
+function capPreservingTerminator(text: string, opts: BuildHandoffOptions): string {
+ if (text.length <= HANDOFF_HARD_CAP) return text;
+ const terminator = handoffTerminator(opts);
+ const separator = '\n\n';
+ const room = HANDOFF_HARD_CAP - terminator.length - separator.length;
+ if (room <= 0) return terminator.slice(0, HANDOFF_HARD_CAP);
+ return `${text.slice(0, room)}${separator}${terminator}`;
}
function assembleHandoffText(
@@ -299,36 +335,39 @@ function assembleHandoffText(
const sections: string[] = [];
if (opts.reason === 'message-deletion') {
sections.push(
- `[会话上下文重建·内部上下文]\n` +
- `本会话的本地记录已由用户编辑,当前原生会话上下文因此失效。` +
- `下面是编辑后的有效对话历史;只把这些记录视为此前对话,不要尝试恢复、引用或推断未列出的消息。` +
- `请以第一人称自然续接,不要向用户提及本段重建说明。` +
- `开始改动前先核对工作区实际状态(如 git status / git diff / 读相关文件):` +
- `记述与工作区冲突时,一律以工作区现状为准;` +
- `对更早的细节没有把握时,优先读取实际文件与代码核实,不要凭摘要臆断。`,
+ `[Session context rebuild · internal context]\n` +
+ `The user edited this conversation's local record, which invalidated the current native session context. ` +
+ `Below is the valid conversation history after that edit; treat only these records as the prior conversation, ` +
+ `and do not try to recover, cite, or infer messages that are not listed. ` +
+ `Continue naturally in the first person, and do not mention this rebuild note to the user. ` +
+ `Before making any change, check the actual workspace state (e.g. git status / git diff / reading the relevant files): ` +
+ `when the record conflicts with the workspace, the workspace always wins; ` +
+ `when you are unsure about an earlier detail, read the real files and code to confirm rather than guessing from the summary.`,
);
} else if (opts.mode === 'delta') {
// 归位续接:目标引擎 resume 了自己的停泊原生会话,已持有离场前的完整记忆。
// 只补"离开期间"的进展;同时防御 resume 静默失效——指引它以工作区与检索为准,
// 而不是断言"你一定记得"。
sections.push(
- `[会话交接·内部上下文]\n` +
- `你(${opts.toLabel})此前处理过本会话,期间曾切换给 ${opts.fromLabel} 引擎接手,现在切回由你继续。` +
- `你离场前的对话记忆应仍然有效;下面是你离开期间发生的进展记录,请合并进你的理解后以第一人称自然续接。` +
- `不要向用户提及本段交接说明,也不要提及引擎切换过程。` +
- `开始改动前先核对工作区实际状态(如 git status / git diff / 读相关文件):` +
- `记述、你的记忆与工作区三者冲突时,一律以工作区现状为准;` +
- `对离开期间的细节没有把握时,优先读取实际文件与代码核实,不要凭摘要臆断。`,
+ `[Session handoff · internal context]\n` +
+ `You (${opts.toLabel}) worked on this conversation before; it was handed over to the ${opts.fromLabel} engine for a while, and now it is switching back to you. ` +
+ `Your memory of the conversation from before you left should still be valid; below is a record of what happened while you were away. ` +
+ `Merge it into your understanding and continue naturally in the first person. ` +
+ `Do not mention this handoff note to the user, and do not mention the engine switch. ` +
+ `Before making any change, check the actual workspace state (e.g. git status / git diff / reading the relevant files): ` +
+ `when the record, your own memory, and the workspace disagree, the workspace always wins; ` +
+ `when you are unsure about something from while you were away, read the real files and code to confirm rather than guessing from the summary.`,
);
} else {
sections.push(
- `[会话交接·内部上下文]\n` +
- `本会话此前由 ${opts.fromLabel} 引擎驱动,现在起由你(${opts.toLabel})继续。` +
- `下面是这场对话的既往记录——这是你与用户之间同一场对话的延续,请以第一人称自然续接。` +
- `不要向用户提及本段交接说明,不要说"根据交接摘要/记录"之类的话。` +
- `开始改动前先核对工作区实际状态(如 git status / git diff / 读相关文件):` +
- `记述与工作区冲突时,一律以工作区现状为准;` +
- `对更早的细节没有把握时,优先读取实际文件与代码核实,不要凭摘要臆断。`,
+ `[Session handoff · internal context]\n` +
+ `This conversation was previously driven by the ${opts.fromLabel} engine; from here on you (${opts.toLabel}) continue it. ` +
+ `Below is the prior record of this conversation — it is the same conversation between you and the user, ` +
+ `so continue naturally in the first person. ` +
+ `Do not mention this handoff note to the user, and do not say things like "according to the handoff summary/record". ` +
+ `Before making any change, check the actual workspace state (e.g. git status / git diff / reading the relevant files): ` +
+ `when the record conflicts with the workspace, the workspace always wins; ` +
+ `when you are unsure about an earlier detail, read the real files and code to confirm rather than guessing from the summary.`,
);
}
@@ -339,22 +378,22 @@ function assembleHandoffText(
if (work.changedFiles.length > 0 || work.commands.length > 0) {
const lines: string[] = [];
if (work.changedFiles.length > 0) {
- lines.push('改动过的文件:');
+ lines.push('Files changed:');
for (const f of work.changedFiles) lines.push(`- ${f}`);
}
if (work.commands.length > 0) {
- lines.push('执行过的命令(最近几条):');
+ lines.push('Commands run (most recent):');
for (const cmd of work.commands) lines.push(`- ${cmd}`);
}
- sections.push(`== 工作状态(自动提取)==\n${lines.join('\n')}`);
+ sections.push(`== Work state (auto-extracted) ==\n${lines.join('\n')}`);
}
if (earlier.length > 0) {
const lines: string[] = [];
for (const t of earlier) {
- if (t.userText) lines.push(`- 用户: ${truncate(oneLine(t.userText), DIGEST_LINE_CAP)}`);
+ if (t.userText) lines.push(`- User: ${truncate(oneLine(t.userText), DIGEST_LINE_CAP)}`);
if (t.lastAssistantText) {
- lines.push(` 回应: ${truncate(oneLine(t.lastAssistantText), DIGEST_LINE_CAP)}`);
+ lines.push(` Reply: ${truncate(oneLine(t.lastAssistantText), DIGEST_LINE_CAP)}`);
}
}
// 预算内保留最新的提要行,最旧的先丢
@@ -368,12 +407,12 @@ function assembleHandoffText(
kept.unshift(lines[i]);
used += cost;
}
- digest = `(更早内容已省略)\n${kept.join('\n')}`;
+ digest = `(earlier content omitted)\n${kept.join('\n')}`;
}
sections.push(
opts.mode === 'delta'
- ? `== 你离开期间·较早进展提要 ==\n${digest}`
- : `== 较早对话提要 ==\n${digest}`,
+ ? `== Earlier progress while you were away ==\n${digest}`
+ : `== Earlier conversation digest ==\n${digest}`,
);
}
@@ -381,18 +420,18 @@ function assembleHandoffText(
const blocks: string[] = [];
for (const t of recent) {
const parts: string[] = [];
- if (t.userText) parts.push(`[用户]\n${truncate(t.userText, RECENT_TEXT_CAP)}`);
+ if (t.userText) parts.push(`[User]\n${truncate(t.userText, RECENT_TEXT_CAP)}`);
parts.push(...collapseDetailLines(t.detailLines));
if (parts.length > 0) blocks.push(parts.join('\n'));
}
sections.push(
opts.mode === 'delta'
- ? `== 你离开期间的对话记录 ==\n${blocks.join('\n---\n')}`
- : `== 最近对话记录 ==\n${blocks.join('\n---\n')}`,
+ ? `== Conversation while you were away ==\n${blocks.join('\n---\n')}`
+ : `== Recent conversation ==\n${blocks.join('\n---\n')}`,
);
} else if (opts.mode === 'delta') {
// 切走后一条消息都没发就切回:显式说明,避免引擎误以为漏了记录。
- sections.push('== 你离开期间没有新的对话消息 ==');
+ sections.push('== No new messages while you were away ==');
}
if (opts.sessionId) {
@@ -400,25 +439,79 @@ function assembleHandoffText(
// 翻到原文。工具名 / 参数是确定性事实(@cindy/mcps xdt-helper,session_ids 过滤,
// 两个工具均支持),写死在指引里比让模型自己发现可靠(规则 9)。
sections.push(
- `== 早期原文检索(需要时用)==\n` +
- `本会话 id:${opts.sessionId}\n` +
- `以上摘要之外的早期对话原文可随时检索(工具在 cindy_helper 的 history 类目):\n` +
- `- 按内容找:search_chat_history,args {"query":"<关键词>","session_ids":["${opts.sessionId}"]}\n` +
- `- 按时间/角色拉原文:get_chat_history,args {"session_ids":["${opts.sessionId}"],"roles":["user","assistant"]}(hasMore 用 nextCursor 翻页)\n` +
- `用户追问的细节不在上文时,先检索原文再回答,不要凭提要猜;检索到的旧内容与工作区现状冲突时,以工作区为准。仅在需要时使用,不必每轮都查。`,
+ `== Retrieving earlier verbatim history (use when needed) ==\n` +
+ `Session id: ${opts.sessionId}\n` +
+ `Earlier conversation text beyond the digest above can be retrieved at any time (tools live under cindy_helper's history category):\n` +
+ `- By content: search_chat_history, args {"query":"<keywords>","session_ids":["${opts.sessionId}"]}\n` +
+ `- By time/role: get_chat_history, args {"session_ids":["${opts.sessionId}"],"roles":["user","assistant"]} (page through with nextCursor when hasMore)\n` +
+ `When the user asks about a detail that is not in the context above, retrieve the original text before answering instead of guessing from the digest; ` +
+ `when retrieved history conflicts with the current workspace, the workspace wins. Use this only when needed, not on every turn.`,
);
}
- sections.push(
- opts.reason === 'message-deletion'
- ? '== 上下文重建说明结束,以下是用户的新消息 =='
- : '== 交接说明结束,以下是用户的新消息 ==',
- );
+ sections.push(handoffTerminator(opts));
// 不在组装阶段做任何截断——超限收缩由 buildHandoffText 的外层循环负责
// (收缩逐字区保住首尾),尾部硬切只是外层最后的保险。
return sections.join('\n\n');
}
+/**
+ * fork 出的子会话注入给模型的来源标记。
+ *
+ * 为什么只有一行:fork 的上下文是原会话前缀的**完整**拷贝,模型不缺记忆,只缺
+ * "我是谁、我从哪来" 这一个元信息。agent-switch 那种逐字摘要 + 检索指引在这里
+ * 是纯浪费——真需要翻原会话时,history 类工具本来就在工具列表里,不必手把手教。
+ *
+ * 措辞对两种 fork 都成立:消息级 fork 与 forkSessionStripEncrypted(后者
+ * forkedAtMessageId 为 null,不存在"某条消息"),所以只陈述"从哪个会话分叉",
+ * 不提分叉点。
+ */
+export function buildForkOriginHandoff(parentSessionId: string): string {
+ return `${forkOriginFactLine(parentSessionId)}\n\n${FORK_TERMINATOR}`;
+}
+
+function forkOriginFactLine(parentSessionId: string): string {
+ return (
+ `[Session fork · internal context]\n` +
+ `This conversation was forked by the user from another conversation (id: ${parentSessionId}). ` +
+ `Do not mention this note or that id to the user.`
+ );
+}
+
+/**
+ * 把来源标记**并进**已有的 pending 交接,而不是替换它。
+ *
+ * 必须组合的原因:在引擎切换后的首条 user 消息上 fork 时,fork 事务会刻意把复制
+ * 过去的 agent_switch 边界重置为 `consumed: false`(见 WorkerThreadTransport 的
+ * sanitizeForkedMessageContent 与 fork.ts 的 resetHandoffBoundaryClientId),让子会话
+ * 首次发送时仍拿得到完整的跨引擎交接。若来源标记直接顶掉它,子会话会在没有切换前
+ * 上下文的情况下起跑——那正是交接机制本身要防的失忆。
+ *
+ * 顺序:来源标记在前(只是"我是谁"的元信息),交接正文在后,由交接自带的结束标记
+ * 统一收尾,避免出现两个"以下是用户的新消息"。
+ */
+export function composeForkOriginHandoff(
+ parentSessionId: string,
+ pendingHandoff: string | null,
+): string {
+ if (!pendingHandoff) return buildForkOriginHandoff(parentSessionId);
+ const fact = forkOriginFactLine(parentSessionId);
+ const composed = `${fact}\n\n${pendingHandoff}`;
+ if (composed.length <= HANDOFF_HARD_CAP) return composed;
+ // 交接正文可能**已经**被 buildHandoffText 顶到上限(工具密集的长历史),再前置
+ // fork 事实就会顶破它。从正文中部裁,两头都留住:前面的 fork 事实与它自带的结束
+ // 标记——否则这条路径正好在最需要分隔的长历史上丢掉分隔。
+ const [body, tail] = splitTrailingTerminator(pendingHandoff);
+ const separator = '\n\n';
+ // 两个 separator:fact 与正文之间、正文与结束标记之间。后者不能省——正文被从中部
+ // 裁开后末尾多半停在半句上,结束标记直接贴上去就毁掉了"显式分隔"这个不变量本身。
+ const room = HANDOFF_HARD_CAP - fact.length - separator.length * 2 - tail.length;
+ // 极端情形(当前上限下不可达)也要守住优先级:交接关系到跨引擎的对话连续性,
+ // 来源标记只是元信息——挤不下时丢后者,绝不能反过来把整段交接换成一行来源说明。
+ if (room <= 0) return pendingHandoff;
+ return `${fact}${separator}${body.slice(0, room).trimEnd()}${separator}${tail}`;
+}
+
/** send 路径的 wire 消息形态(与 makerSendTransaction 的 IpcUserMessage 对齐)。 */
export type HandoffWireMessage =
| string
@@ -455,19 +548,80 @@ export interface AgentHandoffPendingRegistry {
consume(sessionId: string): void;
/** session 删除 / 关闭清理,避免 Map 泄漏。 */
clear(sessionId: string): void;
+ /**
+ * 墓碑式失效:留下 null 条目,后续 peek 直接返回 null,**不回落 DB**。
+ *
+ * 给 `/clear` 用。本地 `/clear` 的 `cleared_at` 是 renderer 侧 fire-and-forget 写入
+ * 的(main 只在 device-link 远程调用时自己落库),handler 返回到那次写入提交之间有
+ * 个窗口;若此刻用 `clear()` 删掉条目,恰好撞上 hook / scheduler 等直发路径的 send,
+ * peek 会回落到**尚未更新 cleared_at** 的 DB 行,把旧交接重建出来并缓存,而后来的
+ * DB 更新不会让那份缓存失效。留墓碑就没有这个窗口——真有新交接时 `set()` 会覆盖它。
+ */
+ invalidate(sessionId: string): void;
}
export function createAgentHandoffPendingRegistry(
queryPending: (sessionId: string) => Promise<string | null>,
onConsume?: (sessionId: string) => void,
+ /**
+ * 内存命中时的补充组合钩子。存在的理由:交接不只由 queryPending 产出——
+ * agent-switch / 消息删除会直接 `set` 进内存(register.ts 的 setPendingHandoff),
+ * 那条路径不经过 DB fallback。fork 出的子会话若在首发前切了引擎,内存里就只有
+ * 切换交接,来源标记会被整条跳过。这里对**非 null 的内存值**再过一次组合,把两
+ * 者并起来;null(已 consume)不触发,消费语义不变。
+ *
+ * 只对 `set` 进来的值生效:queryPending 的产出已经组合过,再过一遍会让首发未
+ * accepted 的重试拿到两份来源标记(下面的 composedByQuery 就是这道闸)。
+ */
+ decorateCached?: (sessionId: string, handoff: string) => Promise<string>,
): AgentHandoffPendingRegistry {
const pending = new Map<string, string | null>();
+ /** 值由 queryPending 产出(已含组合结果)的 session,decorate 必须跳过它们。 */
+ const composedByQuery = new Set<string>();
+ /**
+ * 每个 session 的状态代次。peek 里两处 await 之后都要写回 Map,而 `/clear` 与
+ * `set` 可能正好落在那个窗口里——不带代次校验地写回,会把 clear 掉的旧交接原样
+ * 塞回缓存并标成已组合,下一次 send 就绕过 `cleared_at` 把旧上下文灌进用户刚
+ * 清空的会话。任何改变状态的入口都递增它,await 后代次不符就丢弃本次结果。
+ */
+ const generation = new Map<string, number>();
+ const bump = (sessionId: string): void => {
+ generation.set(sessionId, (generation.get(sessionId) ?? 0) + 1);
+ };
+ const genOf = (sessionId: string): number => generation.get(sessionId) ?? 0;
return {
set(sessionId, handoff) {
pending.set(sessionId, handoff);
+ // 外部直接塞进来的交接没经过 queryPending 的组合,重新纳入 decorate 范围。
+ composedByQuery.delete(sessionId);
+ bump(sessionId);
},
async peek(sessionId) {
- if (pending.has(sessionId)) return pending.get(sessionId) ?? null;
+ if (pending.has(sessionId)) {
+ const cached = pending.get(sessionId) ?? null;
+ if (cached === null || !decorateCached || composedByQuery.has(sessionId)) return cached;
+ const gen = genOf(sessionId);
+ try {
+ const decorated = await decorateCached(sessionId, cached);
+ // 期间被 clear / set:本次结果基于已作废的状态,既不写回也不返回——
+ // 返回它等于把 clear 掉的交接注入这一次发送。
+ if (genOf(sessionId) !== gen) return null;
+ // 组合结果回写并标记为已组合:同一条待注入交接在 consume 之前可能被 peek
+ // 多次(首发被拒后的重试),没有这步每次都要重跑一遍 decorate 的 DB 查询,
+ // 而且要靠 decorate 自身幂等才不会叠加。
+ pending.set(sessionId, decorated);
+ composedByQuery.add(sessionId);
+ return decorated;
+ } catch {
+ // 失败路径同样要看代次:decorate 抛错(如查询瞬时失败)期间若发生 /clear,
+ // 退回 cached 等于把已作废的交接注入这次发送——那正是代次校验要拦的事。
+ if (genOf(sessionId) !== gen) return null;
+ // 组合失败不能吞掉本来就该注入的交接——退回未组合的原值,且不写缓存,
+ // 下次 peek 仍会重试组合。
+ return cached;
+ }
+ }
+ const gen = genOf(sessionId);
let fromDb: string | null = null;
try {
fromDb = await queryPending(sessionId);
@@ -475,15 +629,26 @@ export function createAgentHandoffPendingRegistry(
// 查询失败按无 pending 处理(不阻塞发送);下次 send 重查。
return null;
}
+ if (genOf(sessionId) !== gen) return null;
pending.set(sessionId, fromDb);
+ composedByQuery.add(sessionId);
return fromDb;
},
consume(sessionId) {
pending.set(sessionId, null);
+ composedByQuery.delete(sessionId);
+ bump(sessionId);
onConsume?.(sessionId);
},
clear(sessionId) {
pending.delete(sessionId);
+ composedByQuery.delete(sessionId);
+ bump(sessionId);
+ },
+ invalidate(sessionId) {
+ pending.set(sessionId, null);
+ composedByQuery.delete(sessionId);
+ bump(sessionId);
},
};
}
diff --git a/apps/desktop/src/main/maker-ipc/agentHandoffPendingSingleton.ts b/apps/desktop/src/main/maker-ipc/agentHandoffPendingSingleton.ts
index 061683883d..776b9415d2 100644
--- a/apps/desktop/src/main/maker-ipc/agentHandoffPendingSingleton.ts
+++ b/apps/desktop/src/main/maker-ipc/agentHandoffPendingSingleton.ts
@@ -18,19 +18,54 @@
*/
import {
+ findForkParentSessionId,
findPendingAgentHandoff,
+ findPendingForkOrigin,
markLatestAgentHandoffConsumed,
} from '../localDb/ipc/messages.js';
import { createLogger } from '../logger.js';
-import { createAgentHandoffPendingRegistry } from './agentHandoff.js';
+import {
+ buildForkOriginHandoff,
+ composeForkOriginHandoff,
+ createAgentHandoffPendingRegistry,
+} from './agentHandoff.js';
const log = createLogger('agent-handoff-pending');
-// 查询函数包一层 lambda 在**调用期**解析:单测普遍 vi.mock 了 messages.js 且不含
-// 本导出,模块求值期直接引用会让所有传递 import 本单例的 suite 崩在 mock 缺口上;
-// 调用期访问失败则落进 registry.peek 的 try/catch(按无 pending 处理),两全。
-export const agentHandoffPending = createAgentHandoffPendingRegistry((sessionId) =>
- findPendingAgentHandoff(sessionId),
+/**
+ * fork 来源标记同样走 DB 重建,不在 fork 时写内存:
+ * - `parent_session_id` 本就是持久列,重建是确定性的(见 findPendingForkOrigin),
+ * 重启后不丢;
+ * - 更关键的是**不能**在 fork 时抢先 set 内存态——那会让 peek 命中内存直接返回,
+ * 永远查不到 DB 里那条被 fork 事务 re-arm 成 `consumed: false` 的 agent_switch
+ * 边界,把跨引擎交接整段吞掉。两者在这里组合,谁都不丢。
+ */
+export const agentHandoffPending = createAgentHandoffPendingRegistry(async (sessionId) => {
+ // 两个查询互不依赖,并行发出——这是 send 路径上的一跳,不该串成两个 RTT。
+ // 失败时**独立降级**,两者重要性并不对等:
+ // - 交接查询失败照旧上抛,由 peek 的 catch 处理(返回 null 且**不缓存**,下次
+ // send 重查)——把它就地 catch 成 null 反而会被缓存成"确认无 pending",
+ // 等于永久丢掉一段跨引擎交接;
+ // - 来源标记只是元信息,查失败就降级为无,不该反过来拖累交接。
+ const [pending, forkParentSessionId] = await Promise.all([
+ findPendingAgentHandoff(sessionId),
+ findForkParentSessionId(sessionId).catch(() => null),
+ ]);
+ // 有待注入的交接 = 正在重建原生上下文(agent-switch / 消息删除)。此时用**永久血缘**,
+ // 与 decorateCached 同口径:重启若正好落在"重建之后、发送之前",内存态已丢,这条 DB
+ // 路径是唯一出口;若它改看首发消费态,首轮跑过的 fork 会在这里丢掉血缘,新原生上下文
+ // 再也不知道自己是分叉。
+ if (pending) {
+ return forkParentSessionId
+ ? composeForkOriginHandoff(forkParentSessionId, pending)
+ : pending;
+ }
+ // 没有交接 = 纯首发注入场景,这才该看一次性的消费态。非 fork 会话在这里短路,
+ // 只省掉这条**第二**次查询;上面 Promise.all 里的两条对所有会话都会发出。
+ if (!forkParentSessionId) return null;
+ const pendingForkOrigin = await findPendingForkOrigin(sessionId).catch(() => null);
+ return pendingForkOrigin ? buildForkOriginHandoff(pendingForkOrigin) : null;
+},
(sessionId) => {
void markLatestAgentHandoffConsumed(sessionId).catch((err) => {
// accepted 已跨不可逆边界,持久标记失败不能把这次 send 改判失败;内存态
@@ -41,4 +76,17 @@ export const agentHandoffPending = createAgentHandoffPendingRegistry((sessionId)
});
});
},
+ // agent-switch / 消息删除会直接把交接 set 进内存(register.ts 的 setPendingHandoff),
+ // 不经上面的 DB fallback。fork 出的子会话若在首发前切了引擎,内存里就只剩切换交接,
+ // 来源标记会被整条跳过——这里补一次组合。
+ //
+ // 这里用 findForkParentSessionId 而**不是** findPendingForkOrigin:这两条路径重建的是
+ // 新的原生上下文,交接正文纯按 messages 拼出、不含 fork 信息。fork 是会话的永久属性,
+ // 不该随首发那一次性标记被消费掉——否则首轮跑完再切引擎,新上下文就不知道自己是分叉。
+ async (sessionId, handoff) => {
+ const forkParentSessionId = await findForkParentSessionId(sessionId);
+ return forkParentSessionId
+ ? composeForkOriginHandoff(forkParentSessionId, handoff)
+ : handoff;
+ },
);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index f17465f0e3..bdee939b78 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -6956,6 +6956,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions
});
const projection = inputCoordinator.clearSession(sid, clearBoundary);
silentStopAutoResumeGuard.noteSessionReset(sid);
+ // 丢弃缓存的待注入交接 / fork 来源标记:它们是按 clear 之前的历史算出来的,
+ // DB 侧的 cleared_at 抑制拦不住已经落进 registry 内存的那一份(首发被拒后
+ // 缓存仍在),下次 send 会把旧血缘灌进用户刚显式清空的上下文。
+ //
+ // 用 invalidate(留 null 墓碑)而不是 clear(删条目):本地 /clear 的 cleared_at
+ // 由 renderer fire-and-forget 落库(main 只在 remoteInvoke 分支自己写),删条目会
+ // 让这段窗口内的 headless send 回落到尚未更新 cleared_at 的 DB 行,把旧交接重建
+ // 出来再缓存住。
+ agentHandoffPending.invalidate(sid);
getAgentIslandService()?.notifyQueueEmptied(sid);
// 清上下文后,active 目标失去其依据(objective 引用的内容已被抹掉)→ 一并清除目标。
goalClearObserver?.(sid);
diff --git a/apps/desktop/src/main/maker-ipc/rewind.ts b/apps/desktop/src/main/maker-ipc/rewind.ts
index b11b7409fd..c6e9f0caed 100644
--- a/apps/desktop/src/main/maker-ipc/rewind.ts
+++ b/apps/desktop/src/main/maker-ipc/rewind.ts
@@ -18,6 +18,7 @@ import { requireString, throwIpcError } from '../utils/ipcValidate.js';
import { MAKER_INVOKE } from './channels.js';
import { withSessionInputStoppedForRewind } from './register.js';
+import { agentHandoffPending } from './agentHandoffPendingSingleton.js';
const log = createLogger('maker-ipc/rewind');
const STOPPED_REWIND_RETRY_MS = 100;
@@ -92,6 +93,10 @@ export function registerMakerRewindIpc(): void {
? await withSessionInputStoppedForRewind(sid, () =>
commitAfterStopping(sid, cid, { requireLatestUser }))
: await commitRewindAtMessage(sid, cid, { requireLatestUser });
+ // 回滚后缓存的待注入交接 / fork 来源标记都是按截断前的历史算出来的,丢弃它,
+ // 让下次 send 按回滚后的现状重新判定——被回滚掉的正是当初携带来源标记的那一轮时,
+ // DB 侧判定会自动重新 arm(它按 rewind_at 过滤)。
+ agentHandoffPending.clear(sid);
// 回滚后会话历史被截断,active 目标若继续就会对着变化后的上下文跑 —— 暂停它
// (保留计数,用户 review 后可 resume)。fire-and-forget,失败不阻塞 rewind。
void getGoalController()?.pauseGoal(sid, 'paused: conversation rewound').catch(() => {});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b99ef1b47b..519fdd6c3e 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4766,7 +4766,7 @@
"agentSwitch": {
"label": "Switched from {{from}} to {{to}}",
"toggleHint": "View handoff context",
- "handoffTitle": "Handoff — the context summary sent to the new engine at switch time (never shown in your messages)",
+ "handoffTitle": "Handoff — the context summary sent to the new engine at switch time (not part of the chat transcript; shown only here)",
"resumedBadge": "session resumed"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index ae4a4a8432..4e506a237a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4765,7 +4765,7 @@
"agentSwitch": {
"label": "{{from}} から {{to}} に切り替えました",
"toggleHint": "引き継ぎ内容を表示",
- "handoffTitle": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約(メッセージには表示されません)",
+ "handoffTitle": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)",
"resumedBadge": "セッション再開"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 02a806a5e0..2253f0f545 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4765,7 +4765,7 @@
"agentSwitch": {
"label": "{{from}}에서 {{to}}(으)로 전환됨",
"toggleHint": "인계 내용 보기",
- "handoffTitle": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약(메시지에는 표시되지 않음)",
+ "handoffTitle": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)",
"resumedBadge": "세션 재개됨"
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 01961a6742..c961651333 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4765,7 +4765,7 @@
"agentSwitch": {
"label": "已从 {{from}} 切换到 {{to}}",
"toggleHint": "查看交接内容",
- "handoffTitle": "交接内容——切换时发送给新引擎的上下文摘要(不会出现在你的消息里)",
+ "handoffTitle": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)",
"resumedBadge": "已续接原对话"
}
},
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 57dcd96d74..50013efa1c 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -55,7 +55,7 @@
"agentSwitchLabel": "Switched from {{from}} to {{to}}",
"agentSwitchViewHandoff": "{{label}}, view handoff",
"sessionResumedPill": "Resumed original session",
- "handoffContentDesc": "Handoff — context summary sent to the new engine when switching (not shown in your messages)",
+ "handoffContentDesc": "Handoff — context summary sent to the new engine when switching (not part of the chat transcript; shown only here)",
"openDiagramDetail": "Open diagram detail",
"sessionChipFallback": "Session {{id}}",
"imageFallbackTitle": "Image",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 2b1a516d8d..203b1d7aaf 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -55,7 +55,7 @@
"agentSwitchLabel": "{{from}} から {{to}} に切り替えました",
"agentSwitchViewHandoff": "{{label}}、引き継ぎ内容を表示",
"sessionResumedPill": "元のセッションを再開しました",
- "handoffContentDesc": "引き継ぎ内容——切り替え時に新しいエンジンへ送るコンテキスト要約(あなたのメッセージには表示されません)",
+ "handoffContentDesc": "引き継ぎ内容——切り替え時に新しいエンジンへ送るコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)",
"openDiagramDetail": "図の詳細を開く",
"sessionChipFallback": "セッション {{id}}",
"imageFallbackTitle": "画像",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index 1c29393508..e895c768b8 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -55,7 +55,7 @@
"agentSwitchLabel": "{{from}}에서 {{to}}(으)로 전환됨",
"agentSwitchViewHandoff": "{{label}}, 인계 내용 보기",
"sessionResumedPill": "원래 세션을 재개함",
- "handoffContentDesc": "인계 내용——전환 시 새 엔진에 전달되는 컨텍스트 요약(내 메시지에는 표시되지 않음)",
+ "handoffContentDesc": "인계 내용——전환 시 새 엔진에 전달되는 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)",
"openDiagramDetail": "다이어그램 세부 정보 열기",
"sessionChipFallback": "세션 {{id}}",
"imageFallbackTitle": "이미지",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index 44ff799e25..0f00ee0615 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -55,7 +55,7 @@
"agentSwitchLabel": "已从 {{from}} 切换到 {{to}}",
"agentSwitchViewHandoff": "{{label}},查看交接内容",
"sessionResumedPill": "已续接原对话",
- "handoffContentDesc": "交接内容——切换时发送给新引擎的上下文摘要(不会出现在你的消息里)",
+ "handoffContentDesc": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)",
"openDiagramDetail": "打开图表详情",
"sessionChipFallback": "对话 {{id}}",
"imageFallbackTitle": "图片",