Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop,mobile): 补回 #701 未随合并进入 main 的三条 review 修复 (#738)
Dash55e3eac2b77a
diff --git a/apps/desktop/src/main/__tests__/clearSessionHandoffOrdering.test.ts b/apps/desktop/src/main/__tests__/clearSessionHandoffOrdering.test.tsnew file mode 100644index 0000000000..2c97c7221b--- /dev/null+++ b/apps/desktop/src/main/__tests__/clearSessionHandoffOrdering.test.ts@@ -0,0 +1,56 @@+/**+ * `/clear` handler 里三步的**先后契约**:立墓碑 → cleared_at 落库 → 封 clear 边界。+ *+ * 纪元的作用是作废「在 clear 之前取过纪元、之后才写回」的交接。它一旦先于落库推进,+ * 那个 await 窗口里启动的引擎切换 / 消息删除就会同时拿到「clear 之后的纪元」和+ * 「clear 之前的 DB 历史」——校验通过,基于已清空历史算出的交接照样盖掉墓碑,下次发送+ * 把用户刚显式清空的上下文重新灌回模型(#738 review P1)。+ *+ * 墓碑必须留在最前:窗口内到达的 send 走 peek,墓碑是同步生效且不回落 DB 的那一层。+ * 而窗口内**写回**的那批(纪元还是 clear 前的值、校验会通过)由 sealClearBoundary 的+ * 重立墓碑兜住——它不只是推进纪元,顺序细节见该方法注释。+ *+ * register.ts 是超大 handler 注册文件、没有可注入的测试入口,repo 里既有的做法就是对+ * 源码断言(见 deviceLinkAutoTitleWiring.test.ts / interruptedContinuationContract.test.ts)。+ */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++const registerSource = readFileSync(+ resolve(__dirname, '..', 'maker-ipc', 'register.ts'),+ 'utf8',+).replace(/\r\n?/g, '\n');++describe('/clear:墓碑 → cleared_at 落库 → 封 clear 边界', () => {+ const handlerStart = registerSource.indexOf('MAKER_INVOKE.INPUT_CLEAR_SESSION');+ const handlerEnd = registerSource.indexOf('MAKER_INVOKE.ABORT_SESSION', handlerStart);+ const handler = registerSource.slice(handlerStart, handlerEnd);++ it('三步都在同一个 handler 内', () => {+ expect(handlerStart).toBeGreaterThan(-1);+ expect(handlerEnd).toBeGreaterThan(handlerStart);+ expect(handler).toContain('agentHandoffPending.invalidate(sid)');+ expect(handler).toContain('await clearSessionContextInDb(sid, clearBoundaryMs)');+ expect(handler).toContain('agentHandoffPending.sealClearBoundary(sid)');+ });++ it('顺序不可颠倒:纪元推进排在 cleared_at 落库之后,墓碑排在最前', () => {+ const tombstoneAt = handler.indexOf('agentHandoffPending.invalidate(sid)');+ const persistAt = handler.indexOf('await clearSessionContextInDb(sid, clearBoundaryMs)');+ const epochAt = handler.indexOf('agentHandoffPending.sealClearBoundary(sid)');+ expect(tombstoneAt).toBeLessThan(persistAt);+ expect(persistAt).toBeLessThan(epochAt);+ });++ it('落库失败不跳过纪元推进:catch 掉而不是让 handler 抛出', () => {+ // 抛出的话 sealClearBoundary 不会执行,在途那批按过期历史算出的交接+ // 就能顺利写回。失败时宁可一并丢弃。+ const persistAt = handler.indexOf('await clearSessionContextInDb(sid, clearBoundaryMs)');+ const epochAt = handler.indexOf('agentHandoffPending.sealClearBoundary(sid)');+ const between = handler.slice(persistAt, epochAt);+ expect(between).toContain('} catch (err) {');+ expect(between).not.toContain('throw');+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.tsindex 25b410331e..00728c6b7f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts@@ -188,6 +188,20 @@ describe('composeForkOriginHandoff', () => {expect(composeForkOriginHandoff('sess-p', null)).toBe(buildForkOriginHandoff('sess-p'));});+ it('legacy 中文结束标记同样被保留:老会话裁剪后不丢边界', () => {+ // 升级前落库的 agent_switch 行仍是旧中文格式;识别不了就会在裁剪时把老会话+ // 唯一的边界连同检索指引尾巴一起削掉。+ const legacyTerminator = '== 交接说明结束,以下是用户的新消息 ==';+ const capped = `${'x'.repeat(16_000 - legacyTerminator.length - 2)}\n\n${legacyTerminator}`;+ expect(capped.length).toBe(16_000);++ const text = composeForkOriginHandoff('sess-legacy', capped);++ expect(text.length).toBeLessThanOrEqual(16_000);+ expect(text).toContain('sess-legacy');+ expect(text.endsWith(`\n\n${legacyTerminator}`)).toBe(true);+ });+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}`;@@ -279,6 +293,30 @@ describe('createAgentHandoffPendingRegistry', () => {expect(decorate).toHaveBeenCalledTimes(1);});+ it('decorate 抛错期间该交接已被 consume:不退回过期值', async () => {+ // consume / set 不推进 clear 纪元(它只由 /clear 推进),所以失败路径不能只看纪元+ // ——退回已被消费的那份,accepted 后的无条件 consume 还会抹掉更新的交接。+ let reg: ReturnType<typeof createAgentHandoffPendingRegistry>;+ const decorate = vi.fn(async () => {+ reg.consume('s1');+ throw new Error('db down');+ });+ reg = createAgentHandoffPendingRegistry(async () => null, undefined, decorate);+ reg.set('s1', 'CONSUMED-HANDOFF');+ expect(await reg.peek('s1')).toBeNull();+ });++ it('decorate 抛错期间该交接已被新的 set 替换:不退回旧值', async () => {+ let reg: ReturnType<typeof createAgentHandoffPendingRegistry>;+ const decorate = vi.fn(async () => {+ reg.set('s1', 'NEWER-HANDOFF');+ throw new Error('db down');+ });+ reg = createAgentHandoffPendingRegistry(async () => null, undefined, decorate);+ reg.set('s1', 'OLD-HANDOFF');+ expect(await reg.peek('s1')).toBeNull();+ });+it('decorate 失败不写缓存,下次 peek 仍重试组合', async () => {let fail = true;const decorate = vi.fn(async (_sid: string, handoff: string) => {@@ -292,6 +330,96 @@ describe('createAgentHandoffPendingRegistry', () => {expect(await reg.peek('s1')).toBe('FORK\n\nSWITCH-HANDOFF');});+ it('过期的 set 被丢弃:期间 /clear 过,按旧历史算出的交接不得盖掉墓碑', async () => {+ const reg = createAgentHandoffPendingRegistry(async () => null);+ // agent-switch / 消息删除在读历史之前取纪元+ const gen = reg.readGeneration('s1');+ // 期间用户 /clear:立墓碑 → cleared_at 落库 → 封边界(handler 的真实顺序)+ reg.invalidate('s1');+ reg.sealClearBoundary('s1');+ // 异步活干完才写回——这份交接算的是 clear 前的历史+ reg.set('s1', 'STALE-PRE-CLEAR-HANDOFF', gen);+ expect(await reg.peek('s1')).toBeNull();+ });++ it('纪元晚于 DB 边界:invalidate 本身不推进纪元,墓碑却已同步生效', async () => {+ // /clear handler 里 invalidate 与 cleared_at 落库之间有个 await 窗口。纪元若在+ // invalidate 就推进,窗口内启动的切换会同时拿到「clear 后的纪元」和「clear 前的+ // DB 历史」——校验通过,旧交接盖掉墓碑。所以纪元必须留到落库之后。+ const query = vi.fn(async () => 'FROM-DB-PRE-CLEAR');+ const reg = createAgentHandoffPendingRegistry(query);+ reg.set('s1', 'OLD-HANDOFF');+ const genBeforeClear = reg.readGeneration('s1');++ reg.invalidate('s1');+ // 契约本体:墓碑立了,纪元还没动——窗口内启动的切换只可能取到 clear 前的值+ expect(reg.readGeneration('s1')).toBe(genBeforeClear);+ const genInWindow = reg.readGeneration('s1');+ // 与此同时,窗口内到达的 send 已经拿不到旧交接(墓碑同步生效,且不回落 DB)+ expect(await reg.peek('s1')).toBeNull();+ expect(query).not.toHaveBeenCalled();++ // cleared_at 落库完成 → 封边界(重立墓碑 + 推进纪元)+ reg.sealClearBoundary('s1');+ expect(reg.readGeneration('s1')).not.toBe(genBeforeClear);+ // 那个窗口内启动、按 clear 前历史算出的交接写回时被丢弃+ reg.set('s1', 'STALE-PRE-CLEAR-HANDOFF', genInWindow);+ expect(await reg.peek('s1')).toBeNull();+ });++ it('封边界要重立墓碑:窗口内用 clear 前纪元挤进来的交接必须被清掉', async () => {+ // 纪元推迟到落库之后,窗口里就有一段「纪元还是 clear 前的值」的时间。此刻写回的+ // 切换 / 删除校验会通过,墓碑被换成按 clear 前历史算出的交接;只推进纪元不会把+ // 已经写进去的那份清掉,下次发送照样把清空前的上下文灌回模型(#738 review)。+ const reg = createAgentHandoffPendingRegistry(async () => null);+ reg.set('s1', 'OLD-HANDOFF');+ const gen = reg.readGeneration('s1');++ reg.invalidate('s1');+ // 窗口内写回:纪元此刻确实还没推进,所以它进得来+ reg.set('s1', 'STALE-PRE-CLEAR-HANDOFF', gen);+ expect(await reg.peek('s1')).toBe('STALE-PRE-CLEAR-HANDOFF');++ // 落库完成 → 封边界,把它清掉+ reg.sealClearBoundary('s1');+ expect(await reg.peek('s1')).toBeNull();+ });++ it('纪元只由 /clear 推进:consume 不得误伤正在途中的新交接', async () => {+ // 最常见的并发,根本不需要用户 /clear:旧交接被 accepted 消费的同时,一个新的+ // 引擎切换正等着读历史/写库。若 consume 也推进纪元,新交接回来就被无辜丢弃,+ // 新引擎反而拿不到上下文。+ const reg = createAgentHandoffPendingRegistry(async () => null);+ reg.set('s1', 'OLD-HANDOFF');+ const genForNewSwitch = reg.readGeneration('s1');+ reg.consume('s1');+ reg.set('s1', 'NEW-SWITCH-HANDOFF', genForNewSwitch);+ expect(await reg.peek('s1')).toBe('NEW-SWITCH-HANDOFF');+ });++ it('纪元只由 /clear 推进:同一流程内的二次写入不被自己先前那次挡掉', async () => {+ const reg = createAgentHandoffPendingRegistry(async () => null);+ const gen = reg.readGeneration('s1');+ reg.set('s1', 'DELTA-HANDOFF', gen);+ // resume 回落:用全量交接覆盖自己刚写的增量交接,仍用最初那个纪元+ reg.set('s1', 'FULL-HANDOFF', gen);+ expect(await reg.peek('s1')).toBe('FULL-HANDOFF');+ });++ it('代次未变时 set 正常生效(无 /clear 干扰的常规路径)', async () => {+ const reg = createAgentHandoffPendingRegistry(async () => null);+ const gen = reg.readGeneration('s1');+ reg.set('s1', 'SWITCH-HANDOFF', gen);+ expect(await reg.peek('s1')).toBe('SWITCH-HANDOFF');+ });++ it('不传代次的 set 保持既有语义(无条件写入)', async () => {+ const reg = createAgentHandoffPendingRegistry(async () => null);+ reg.invalidate('s1');+ reg.set('s1', 'UNCONDITIONAL');+ expect(await reg.peek('s1')).toBe('UNCONDITIONAL');+ });+it('invalidate 留墓碑:后续 peek 直接返回 null,不回落 DB(/clear 的 cleared_at 尚未落库)', async () => {const query = vi.fn(async () => 'FROM-DB-PRE-CLEAR');const reg = createAgentHandoffPendingRegistry(query);diff --git a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.tsindex 4177059384..ea3bdc4c7d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/messageDeleteHandler.test.ts@@ -76,7 +76,8 @@ describe('performMessageDeletion', () => {expect(handoff).toContain('keep after');expect(handoff).not.toContain('delete me');expect(handoff).toContain('treat only these records as the prior conversation');- expect(deps.setPendingHandoff).toHaveBeenCalledWith('s1', handoff);+ // 第三参数是写入前取的代次(mock deps 未提供 readPendingHandoffGeneration → undefined)+ expect(deps.setPendingHandoff).toHaveBeenCalledWith('s1', handoff, undefined);expect(deps.onCommitted).toHaveBeenCalledWith({sessionId: 's1',diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.tsindex 6de43f3217..a3acae4b14 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts@@ -9,6 +9,7 @@ import {type MakerSessionAgentSwitchHandlerDeps,type PendingAgentSwitchIntent,} from '../sessionAgentSwitchHandler';+import { createAgentHandoffPendingRegistry } from '../agentHandoff';import { MAKER_INVOKE } from '../channels';import { IpcHarness } from './helpers/ipcHarness';@@ -659,6 +660,7 @@ describe('Phase 2:切回停泊引擎(resume + 增量交接)', () => {expect(deps.setPendingHandoff).toHaveBeenLastCalledWith('s1',expect.stringContaining('最早的问题'),+ undefined,);});@@ -673,4 +675,25 @@ describe('Phase 2:切回停泊引擎(resume + 增量交接)', () => {const lastPending = vi.mocked(deps.setPendingHandoff).mock.calls.at(-1)![1];expect(lastPending).toContain('最早的问题');});++ it('回落覆盖走真实 registry:第二次写入不被自己先前那次的代次挡掉', async () => {+ // mock deps 的 setPendingHandoff 不带代次语义,挡不住这个回归:同一流程内第一次+ // 写入会 bump 代次,第二次若仍拿最初的代次就会被 registry 静默丢弃,引擎只剩缺+ // 早期历史的增量交接。这里接真 registry 验证最终留下的是全量交接。+ const registry = createAgentHandoffPendingRegistry(async () => null);+ const bootstrap = vi.fn(async () => {+ throw new Error('spawn failed');+ });+ const { deps } = makeResumeDeps({+ bootstrapSwitchedSession: bootstrap,+ setPendingHandoff: (sessionId, handoff, expectedGeneration) =>+ registry.set(sessionId, handoff, expectedGeneration),+ readPendingHandoffGeneration: (sessionId) => registry.readGeneration(sessionId),+ });++ await performSessionAgentSwitch(deps, validParams);++ const pending = await registry.peek('s1');+ expect(pending).toContain('最早的问题');+ });});diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.tsindex 37bf1563d1..a458635d22 100644--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts@@ -296,10 +296,31 @@ function handoffTerminator(opts: BuildHandoffOptions): string {return opts.reason === 'message-deletion' ? REBUILD_TERMINATOR : HANDOFF_TERMINATOR;}-/** 拆出已有文本尾部的结束标记(含其前置空行),供二次裁剪时原样保留。 */+/**+ * 升级前已持久化在 agent_switch / context_rebuild 行里的中文结束标记。+ *+ * 这些行的 `content.handoff` 是**存量数据**,不会因为本次英文化而改写;老会话在升级后+ * 仍可能把它们取出来当 pending handoff 用。裁剪时若认不出这些标记,就会把它们连同+ * "以下是用户的新消息" 这个唯一边界一起截掉——所以识别列表必须包含旧格式。+ */+const LEGACY_HANDOFF_TERMINATOR = '== 交接说明结束,以下是用户的新消息 ==';+const LEGACY_REBUILD_TERMINATOR = '== 上下文重建说明结束,以下是用户的新消息 ==';++/**+ * 拆出已有文本尾部的结束标记,供二次裁剪时原样保留。+ *+ * 返回的 `tail` **从标记本身起算**,不含它前面的空行——分隔空行由+ * composeForkOriginHandoff 自己补,这样正文被从中部裁开后仍能保证标记前有空行。+ */function splitTrailingTerminator(text: string): [body: string, tail: string] {- for (const terminator of [HANDOFF_TERMINATOR, REBUILD_TERMINATOR, FORK_TERMINATOR]) {- const trimmed = text.trimEnd();+ const trimmed = text.trimEnd();+ for (const terminator of [+ HANDOFF_TERMINATOR,+ REBUILD_TERMINATOR,+ FORK_TERMINATOR,+ LEGACY_HANDOFF_TERMINATOR,+ LEGACY_REBUILD_TERMINATOR,+ ]) {if (!trimmed.endsWith(terminator)) continue;const tailStart = trimmed.length - terminator.length;return [text.slice(0, tailStart), text.slice(tailStart)];@@ -543,21 +564,67 @@ export function prependHandoffToUserMessage(* pending 下次重试。*/export interface AgentHandoffPendingRegistry {- set(sessionId: string, handoff: string): void;+ /**+ * 写入待注入交接。+ *+ * `expectedGeneration` 给"读历史 → 一堆异步活 → 才写回"的调用方(引擎切换、消息+ * 删除)用:它们在读历史之前用 `readGeneration()` 取一次,写回时带上;期间若发生+ * `/clear`,这次写就被丢弃。没有它,一个基于 clear 前历史算出来的交接会盖掉+ * `/clear` 刚立的墓碑,把已清空的上下文重新灌回去。+ *+ * 比较的是 **clear 纪元**,只由 `/clear`(invalidate / clear)推进——`set` 与+ * `consume` 都不推进它,所以同一流程内的二次写入、以及与别处 consume 的并发,+ * 都不会被误拒。+ */+ set(sessionId: string, handoff: string, expectedGeneration?: number): void;+ /** 取当前 clear 纪元(只由 `/clear` 推进),配合 `set` 的 `expectedGeneration` 使用。 */+ readGeneration(sessionId: string): number;peek(sessionId: string): Promise<string | null>;consume(sessionId: string): void;- /** session 删除 / 关闭清理,避免 Map 泄漏。 */+ /**+ * 丢弃内存里的待注入交接并推进 clear 纪元,**允许后续 peek 回落 DB 重建**。+ *+ * 给 rewind 提交用:回退之后 DB 历史本身就变了,回落重建出来的是回退后的正确+ * 结果,不需要墓碑。+ *+ * 注意纪元条目是**故意留着**的,不随本次调用删除:纪元缺省值是 0,删掉就等于把+ * 它退回 0,而绝大多数会话在首次 clear 之前取到的快照正是 0——那些正在读历史的+ * 切换 / 删除流程写回时会重新校验通过,基于回退前历史算出的交接照样盖回来,这个+ * 保护就白做了。留下的是每个被 clear 过的 session 一个 `string -> number`,与+ * `pending` 自身同量级。+ */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()` 会覆盖它。+ * 给 `/clear` 用。`cleared_at` 现在由 clear handler 内同步落库(见 register.ts 的+ * `INPUT_CLEAR_SESSION`),DB 回落本身已经能过滤掉 clear 之前的交接;但落库失败+ * 或 DB 侧过滤有缺口时,`clear()` 的回落语义会把旧交接重建出来并缓存,而后来的+ * DB 更新不会让那份缓存失效。墓碑不依赖 DB 状态,是这里更硬的保证——真有新交接时+ * `set()` 会覆盖它。+ *+ * **不推进 clear 纪元**:纪元一旦推进,就等于向在途的切换 / 删除宣告「DB 边界已+ * 就位」,而此刻 `cleared_at` 还没落库。推进动作交给 `sealClearBoundary`,由 handler+ * 在落库尝试结束之后调用。墓碑本身是同步生效的,先立不影响。*/invalidate(sessionId: string): void;+ /**+ * 封上 clear 边界:**重立墓碑 + 推进 clear 纪元**,作废所有在此之前取过纪元的在途+ * 写入。必须在 `/clear` 的 `cleared_at` 落库尝试**结束之后**调用(成功或失败都要调)。+ *+ * 两件事都不能省,因为 `invalidate` 与本调用之间那段 await 是双向漏的:+ * - 纪元若在 `invalidate` 就推进,窗口内**启动**的切换 / 删除会同时拿到「clear 之后+ * 的纪元」和「clear 之前的 DB 历史」——校验通过,基于已清空历史算出的交接盖掉墓碑;+ * - 纪元推迟到这里,窗口内**写回**的那批(纪元是 clear 前取的、此刻还没被推进)校验+ * 同样通过,一样盖掉墓碑,而单纯推进纪元并不会把已经写进去的那份清掉。+ *+ * 所以是「先重立墓碑清掉窗口内挤进来的,再推进纪元挡住后面写回的」。落库失败也要调:+ * 在途那批算的仍是过期历史,宁可一并丢弃。+ *+ * 代价是窗口内启动、读到的却是**已清空**历史的那一批也会被误伤——丢掉一份本来正确+ * 的交接,方向保守,可接受。+ */+ sealClearBoundary(sessionId: string): void;}export function createAgentHandoffPendingRegistry(@@ -579,22 +646,36 @@ export function createAgentHandoffPendingRegistry(/** 值由 queryPending 产出(已含组合结果)的 session,decorate 必须跳过它们。 */const composedByQuery = new Set<string>();/**- * 每个 session 的状态代次。peek 里两处 await 之后都要写回 Map,而 `/clear` 与- * `set` 可能正好落在那个窗口里——不带代次校验地写回,会把 clear 掉的旧交接原样- * 塞回缓存并标成已组合,下一次 send 就绕过 `cleared_at` 把旧上下文灌进用户刚- * 清空的会话。任何改变状态的入口都递增它,await 后代次不符就丢弃本次结果。+ * 每个 session 的 **clear 纪元**:只有 `/clear`(invalidate / clear)递增它。+ *+ * 它回答的问题只有一个——"我手上这份按某时刻历史算出来的东西,期间有没有被用户+ * 清空作废过"。所以 `set` / `consume` **不**递增:+ * - `consume` 递增会误伤正在途中的新交接:旧交接被 accepted 消费的同时,一个新的+ * 引擎切换可能正等着读历史/写库,它带着更早的纪元回来就被无辜丢弃,新引擎反而+ * 拿不到上下文(这是最常见的一种并发,根本不需要用户 /clear);+ * - `set` 递增会让同一流程内的第二次写入(resume 回落用全量交接覆盖增量交接)+ * 被自己先前那次挡掉。+ *+ * peek 写回时除了纪元,还要确认缓存值仍是自己读到的那一份——纪元不变但被别的+ * `set` 换过内容时,不能拿旧值盖回去。*/- const generation = new Map<string, number>();- const bump = (sessionId: string): void => {- generation.set(sessionId, (generation.get(sessionId) ?? 0) + 1);+ const clearEpoch = new Map<string, number>();+ const bumpClearEpoch = (sessionId: string): void => {+ clearEpoch.set(sessionId, (clearEpoch.get(sessionId) ?? 0) + 1);};- const genOf = (sessionId: string): number => generation.get(sessionId) ?? 0;+ const genOf = (sessionId: string): number => clearEpoch.get(sessionId) ?? 0;return {- set(sessionId, handoff) {+ set(sessionId, handoff, expectedGeneration) {+ // 调用方带了 clear 纪元就校验:它是在读历史之前取的,不符说明期间用户 /clear 过,+ // 这份交接算的是已作废的历史,丢弃而不是盖回去。纪元只由 clear 推进,所以同一+ // 流程内的二次写入、以及与别处 consume 的并发,都不会被误拒。+ if (expectedGeneration !== undefined && genOf(sessionId) !== expectedGeneration) return;pending.set(sessionId, handoff);// 外部直接塞进来的交接没经过 queryPending 的组合,重新纳入 decorate 范围。composedByQuery.delete(sessionId);- bump(sessionId);+ },+ readGeneration(sessionId) {+ return genOf(sessionId);},async peek(sessionId) {if (pending.has(sessionId)) {@@ -603,9 +684,11 @@ export function createAgentHandoffPendingRegistry(const gen = genOf(sessionId);try {const decorated = await decorateCached(sessionId, cached);- // 期间被 clear / set:本次结果基于已作废的状态,既不写回也不返回——- // 返回它等于把 clear 掉的交接注入这一次发送。+ // 期间被 /clear:本次结果基于已作废的状态,既不写回也不返回——返回它等于+ // 把 clear 掉的交接注入这一次发送。if (genOf(sessionId) !== gen) return null;+ // 纪元没变但值被别的 set 换过:别拿旧值盖回去,让下一次 peek 处理新值。+ if (pending.get(sessionId) !== cached) return null;// 组合结果回写并标记为已组合:同一条待注入交接在 consume 之前可能被 peek// 多次(首发被拒后的重试),没有这步每次都要重跑一遍 decorate 的 DB 查询,// 而且要靠 decorate 自身幂等才不会叠加。@@ -613,9 +696,11 @@ export function createAgentHandoffPendingRegistry(composedByQuery.add(sessionId);return decorated;} catch {- // 失败路径同样要看代次:decorate 抛错(如查询瞬时失败)期间若发生 /clear,- // 退回 cached 等于把已作废的交接注入这次发送——那正是代次校验要拦的事。+ // 失败路径与成功路径同一套校验:decorate 抛错期间若发生 /clear,或这份交接+ // 已被别处 consume / 被新交接替换,退回 cached 都等于把过期内容注入这次发送+ // ——尤其 consume 之后再注入,accepted 后的无条件 consume 还会抹掉更新的那份。if (genOf(sessionId) !== gen) return null;+ if (pending.get(sessionId) !== cached) return null;// 组合失败不能吞掉本来就该注入的交接——退回未组合的原值,且不写缓存,// 下次 peek 仍会重试组合。return cached;@@ -629,7 +714,8 @@ export function createAgentHandoffPendingRegistry(// 查询失败按无 pending 处理(不阻塞发送);下次 send 重查。return null;}- if (genOf(sessionId) !== gen) return null;+ // 期间 /clear 或有人写入了新交接:这份 DB 重建结果已过时,不写回也不返回。+ if (genOf(sessionId) !== gen || pending.has(sessionId)) return null;pending.set(sessionId, fromDb);composedByQuery.add(sessionId);return fromDb;@@ -637,18 +723,28 @@ export function createAgentHandoffPendingRegistry(consume(sessionId) {pending.set(sessionId, null);composedByQuery.delete(sessionId);- bump(sessionId);+ // 不推进 clear 纪元:消费的是"这一份"交接,不代表别处正在构造的新交接作废。onConsume?.(sessionId);},clear(sessionId) {pending.delete(sessionId);composedByQuery.delete(sessionId);- bump(sessionId);+ // 不要"顺手"改成 clearEpoch.delete():缺省值 0 会让 clear 前取到 0 的在途写入+ // 重新校验通过。理由见接口声明处。+ bumpClearEpoch(sessionId);},invalidate(sessionId) {pending.set(sessionId, null);composedByQuery.delete(sessionId);- bump(sessionId);+ // 纪元不在这里推进,见接口声明:要等 cleared_at 落库尝试结束。+ },+ sealClearBoundary(sessionId) {+ // 重立墓碑再推进纪元,顺序不能反过来也不能省。落库这段 await 里,一份用+ // clear 前纪元的 set 是能挤进来的(那时纪元还没推进,校验通过),它算的是+ // clear 前的历史;只推进纪元不会把它清掉。+ pending.set(sessionId, null);+ composedByQuery.delete(sessionId);+ bumpClearEpoch(sessionId);},};}diff --git a/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts b/apps/desktop/src/main/maker-ipc/messageDeleteHandler.tsindex 7458a49cc6..f56115c98d 100644--- a/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts+++ b/apps/desktop/src/main/maker-ipc/messageDeleteHandler.ts@@ -49,7 +49,10 @@ export interface MessageDeleteHandlerDeps {clientIds: string[],handoff: string,): Promise<MessageDeleteCommittedPayload>;- setPendingHandoff(sessionId: string, handoff: string): void;+ /** 见 sessionAgentSwitchHandler 同名字段:带代次写,防 /clear 竞态。 */+ setPendingHandoff(sessionId: string, handoff: string, expectedGeneration?: number): void;+ /** 读交接注册表的当前代次(在读历史之前取一次)。 */+ readPendingHandoffGeneration?(sessionId: string): number;onCommitted(payload: MessageDeleteCommittedPayload,requestedClientId: string,@@ -95,6 +98,9 @@ export async function performMessageDeletion(throwIpcError('SESSION_RUNNING', `Session ${sessionId} has background activity`);}+ // 代次在读历史之前取:下面到 setPendingHandoff 之间有异步活,期间 /clear 过的话+ // 这份按删除前历史算出的交接必须作废(见 registry.set 的 expectedGeneration)。+ const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);const source = await deps.listMessagesForContext(sessionId);const deletedClientIds = new Set(target.deletedClientIds);const remaining = source.filter((message) => !deletedClientIds.has(message.clientId));@@ -123,7 +129,7 @@ export async function performMessageDeletion(target.deletedClientIds,handoff,);- deps.setPendingHandoff(sessionId, handoff);+ deps.setPendingHandoff(sessionId, handoff, handoffGeneration);await deps.onCommitted(committed, clientId);deps.log.info('message delete committed; native context will rebuild on next send', {sessionId,diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex ebbe7cb392..53cd3ea7ae 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -4248,7 +4248,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionsreturn clientId;},applyResumeFallbackAtomically: applyAgentSwitchResumeFallbackAtomically,- setPendingHandoff: (sessionId, handoff) => agentHandoffPending.set(sessionId, handoff),+ setPendingHandoff: (sessionId, handoff, expectedGeneration) =>+ agentHandoffPending.set(sessionId, handoff, expectedGeneration),+ readPendingHandoffGeneration: (sessionId) => agentHandoffPending.readGeneration(sessionId),bootstrapSwitchedSession: async (sessionId) => {// 切换已提交,从 DB 行(新引擎值)重建 live session。resumeSessionId 直接取// 行上的 sdk_session_id:切换事务在有停泊绑定时已把它落成停泊 id(Phase 2@@ -4312,7 +4314,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionshasBackgroundActivity: getClaudeSessionBackgroundActivity,closeSession: (sessionId) => maker.closeSession(sessionId),commitDeletion: commitMessageDeletion,- setPendingHandoff: (sessionId, handoff) => agentHandoffPending.set(sessionId, handoff),+ setPendingHandoff: (sessionId, handoff, expectedGeneration) =>+ agentHandoffPending.set(sessionId, handoff, expectedGeneration),+ readPendingHandoffGeneration: (sessionId) => agentHandoffPending.readGeneration(sessionId),onCommitted: ({ sessionId, deletedClientIds, updatedAt, preview, messageCount },requestedClientId,@@ -6991,26 +6995,40 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions// DB 侧的 cleared_at 抑制拦不住已经落进 registry 内存的那一份(首发被拒后// 缓存仍在),下次 send 会把旧血缘灌进用户刚显式清空的上下文。//- // 用 invalidate(留 null 墓碑)而不是 clear(删条目):本地 /clear 的 cleared_at- // 由 renderer fire-and-forget 落库(main 只在 remoteInvoke 分支自己写),删条目会- // 让这段窗口内的 headless send 回落到尚未更新 cleared_at 的 DB 行,把旧交接重建- // 出来再缓存住。+ // 用 invalidate(留 null 墓碑)而不是 clear(删条目):删条目会让后续 send 回落到+ // DB 重建,把旧交接捞回来再缓存住。墓碑同步生效,窗口内的 send 立刻拿到 null;+ // clear 纪元则要等下面 cleared_at 落库之后才推进。agentHandoffPending.invalidate(sid);getAgentIslandService()?.notifyQueueEmptied(sid);// 清上下文后,active 目标失去其依据(objective 引用的内容已被抹掉)→ 一并清除目标。goalClearObserver?.(sid);- if (remoteInvoke) {- const clearBoundaryMs =- typeof clearBoundary === 'number'- ? clearBoundary- : new Date(clearBoundary).getTime();- await clearSessionContextInDb(sid, clearBoundaryMs).catch((err) => {- log.warn('remote clear session context persist failed', {- sessionId: sid,- err: err instanceof Error ? err.message : String(err),- });+ // cleared_at 在 handler 内**同步**落库,本地与远程同一口径。+ //+ // 过去本地路径只靠 renderer 事后 fire-and-forget 写这一列,于是 handler 返回到那次+ // 写入落库之间有个窗口:此刻启动的引擎切换 / 消息删除会读到**尚未标记 clear**的+ // DB 历史,却又拿到 clear 之后的纪元——纪元校验因此形同虚设,基于已清空历史算出的+ // 交接会盖掉刚立的墓碑。在这里同步写掉,那个窗口就不存在了;renderer 之后若再写一次+ // 也是同值幂等。+ const clearBoundaryMs =+ typeof clearBoundary === 'number'+ ? clearBoundary+ : new Date(clearBoundary).getTime();+ try {+ await clearSessionContextInDb(sid, clearBoundaryMs);+ } catch (err) {+ // 落库失败不阻断 /clear:内存墓碑已经立了,这一次以及后续 send 都拿不到旧交接。+ // 残余风险是 DB 里没有 cleared_at,进程重启后 findPendingAgentHandoff 可能把+ // clear 之前的交接重建出来——renderer 侧随后还会写一次同值(sdkSessionId + clearedAt),+ // 那是这里的第二次机会。用 error 级别,便于事后从日志确认是否走到过这条路。+ log.error('clear session context persist failed', {+ sessionId: sid,+ remoteInvoke,+ err: err instanceof Error ? err.message : String(err),});}+ // 落库尝试结束后封边界:重立墓碑(清掉这段 await 里用 clear 前纪元挤进来的那份)+ // + 推进纪元(挡住后面才写回的那批)。顺序不可颠倒,理由见 sealClearBoundary 注释。+ agentHandoffPending.sealClearBoundary(sid);return projection;});diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.tsindex ff31b716df..f61cb3b514 100644--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts@@ -153,7 +153,14 @@ export interface MakerSessionAgentSwitchHandlerDeps {clientId: string,content: AgentSwitchBoundaryContent,): Promise<void>;- setPendingHandoff(sessionId: string, handoff: string): void;+ /**+ * 写待注入交接。`expectedGeneration` 取自 readPendingHandoffGeneration:本函数从读+ * 历史到写回之间有大量异步工作,期间若发生 /clear,这份按 clear 前历史算出的交接+ * 必须被丢弃,而不是盖掉 clear 立的墓碑。+ */+ setPendingHandoff(sessionId: string, handoff: string, expectedGeneration?: number): void;+ /** 读交接注册表的当前代次(在读历史之前取一次)。 */+ readPendingHandoffGeneration?(sessionId: string): number;/** 从 DB 行(切换已提交后的新值)重建 live session;抛错 = 引擎未就绪。 */bootstrapSwitchedSession(sessionId: string): Promise<void>;/**@@ -206,6 +213,12 @@ export interface PendingAgentSwitchIntent {boundaryClientId: string | null;boundaryContent: AgentSwitchBoundaryContent;handoff: string;+ /**+ * 构造这份 handoff 时的 clear 纪元。重试路径必须用它、而不是重试开始时重读——+ * intent 里的 handoff 是按**当初**的历史生成的,若这中间用户 /clear 过(而 /clear+ * 并不取消 intent),重读会拿到 clear 之后的纪元,让这份已作废的历史绕过墓碑写回去。+ */+ handoffClearEpoch?: number;};}@@ -365,6 +378,9 @@ export async function performSessionAgentSwitch(// 竞态兜底:仍在跑就拒绝,绝不打断进行中的 turn。throwIpcError('SESSION_RUNNING', `Session ${sessionId} is running a turn`);}+ // 交接注册表代次:必须在读历史**之前**取。下面到 setPendingHandoff 之间全是异步活,+ // 期间用户可能 /clear——带上它,过期的写入会被 registry 丢弃而不是盖掉墓碑。+ const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);// 交接素材与停泊绑定先于任何状态变更取得(失败不留半切换状态)。// Phase 2:目标引擎有停泊原生会话 → resume + 增量交接(只补离开期间的进展,// 工作状态区仍按全量历史提取);无绑定 → v1 全量交接 + 全新原生会话。@@ -434,7 +450,7 @@ export async function performSessionAgentSwitch(err: err instanceof Error ? err.message : String(err),});}- deps.setPendingHandoff(sessionId, handoff);+ deps.setPendingHandoff(sessionId, handoff, handoffGeneration);let engineReady = true;let resumed = !!parked;@@ -485,6 +501,7 @@ export async function performSessionAgentSwitch(boundaryClientId,boundaryContent: fallbackBoundaryContent,handoff: fullHandoff,+ handoffClearEpoch: handoffGeneration,},});engineReady = false;@@ -507,6 +524,7 @@ export async function performSessionAgentSwitch(boundaryClientId: null,boundaryContent: fallbackBoundaryContent,handoff: fullHandoff,+ handoffClearEpoch: handoffGeneration,},});engineReady = false;@@ -515,7 +533,11 @@ export async function performSessionAgentSwitch(sessionId,});}- deps.setPendingHandoff(sessionId, fullHandoff);+ // 仍用最初那个纪元,**不要**在这里重读:纪元只由 /clear 推进,所以覆盖自己+ // 先前写的增量交接本来就不会被挡;而重读会在"期间发生过 /clear、首次写入+ // 已被正确拒绝"时拿到 clear 之后的新纪元,让这份基于清空前历史构造的全量+ // 交接反而绕过墓碑写进去。+ deps.setPendingHandoff(sessionId, fullHandoff, handoffGeneration);if (fallbackCommitted) {try {await deps.bootstrapSwitchedSession(sessionId);@@ -592,6 +614,10 @@ export function applyPendingAgentSwitchIfIdle(if (intent.resumeFallbackRecovery) {const recovery = intent.resumeFallbackRecovery;throwIfAgentSwitchAborted(opts?.signal);+ // 用**构造这份 handoff 时**记下的纪元,不要在这里重读:intent 里的 handoff 按+ // 当初的历史生成,而 /clear 并不取消 intent——重读会拿到 clear 之后的纪元,让+ // 这份已作废的历史绕过墓碑写回去。+ const recoveryHandoffGeneration = recovery.handoffClearEpoch;const boundaryClientId = recovery.boundaryClientId ??await deps.insertBoundaryMessage(sessionId, recovery.boundaryContent);// 边界补写成功、原子事务仍失败时记住 id;下次只重试事务,不重复插边界。@@ -601,7 +627,7 @@ export function applyPendingAgentSwitchIfIdle(boundaryClientId,recovery.boundaryContent,);- deps.setPendingHandoff(sessionId, recovery.handoff);+ deps.setPendingHandoff(sessionId, recovery.handoff, recoveryHandoffGeneration);if (deps.pendingSwitches?.get(sessionId) === intent) {deps.pendingSwitches.clear(sessionId);deps.onPendingSwitchChanged?.(sessionId, null);diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsxindex 85b884cbd1..4ecf55d18e 100644--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx@@ -748,6 +748,23 @@ function AutoResumeCard() {);}+/**+ * 交接正文是否为英文格式。+ *+ * `content.handoff` 是持久化数据:英文化之前落库的行仍是中文正文,升级后展开老卡片+ * 看到的就是中文。标题里"原文为英文"那句只能对新格式说,否则会自相矛盾。判据取英文+ * 结束标记的公共尾巴——三种英文标记(handoff / rebuild / fork)都含它,旧中文标记不含。+ * main 侧对应常量见 maker-ipc/agentHandoff.ts 的 *_TERMINATOR。+ */+const ENGLISH_HANDOFF_TERMINATOR_TAIL = "; the user's new message follows ==";++function isEnglishSourceHandoff(handoff: string): boolean {+ // 锚在**尾部**而不是 includes:交接正文里嵌着用户与助手的历史原文,里面完全可能+ // 出现这段尾串(比如聊过这段代码),那样旧中文交接会被误判成英文。结束标记只可能+ // 在整段的最末尾。+ return handoff.trimEnd().endsWith(ENGLISH_HANDOFF_TERMINATOR_TAIL);+}+/*** session-agent-switch 边界分隔条:复用 CompactBoundaryCard 的"分隔线 + 居中* chip"语言标记"此处引擎从 X 切换到 Y"。chip 可点展开交接内容面板(发给新引擎@@ -814,7 +831,11 @@ function AgentSwitchCard({ data }: { data?: Record<string, unknown> }) {)}><div className="mb-1.5 text-[11px] font-medium text-muted-foreground">- {t('chat.systemCard.agentSwitch.handoffTitle')}+ {t(+ isEnglishSourceHandoff(handoff)+ ? 'chat.systemCard.agentSwitch.handoffTitleEnglishSource'+ : 'chat.systemCard.agentSwitch.handoffTitle',+ )}</div><pre className="max-h-64 overflow-y-auto whitespace-pre-wrap break-words font-mono text-[12px] leading-[1.55] text-[var(--msg-tool-text)]">{handoff}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 46133d0b16..8208dfa302 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4806,6 +4806,7 @@"label": "Switched from {{from}} to {{to}}","toggleHint": "View handoff context","handoffTitle": "Handoff — the context summary sent to the new engine at switch time (not part of the chat transcript; shown only here)",+ "handoffTitleEnglishSource": "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.jsonindex 36dffd777f..0b1022f581 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4804,7 +4804,8 @@"agentSwitch": {"label": "{{from}} から {{to}} に切り替えました","toggleHint": "引き継ぎ内容を表示",- "handoffTitle": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)",+ "handoffTitle": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約(チャット履歴には含まれず、ここでのみ表示)",+ "handoffTitleEnglishSource": "引き継ぎ内容——切り替え時に新しいエンジンへ送信されたコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)","resumedBadge": "セッション再開"}},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 7940b9cc2e..143b7c4392 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4804,7 +4804,8 @@"agentSwitch": {"label": "{{from}}에서 {{to}}(으)로 전환됨","toggleHint": "인계 내용 보기",- "handoffTitle": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)",+ "handoffTitle": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약(대화 기록에 포함되지 않으며 여기에서만 표시)",+ "handoffTitleEnglishSource": "인계 내용——전환 시 새 엔진에 전송된 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)","resumedBadge": "세션 재개됨"}},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex dbcea95437..9e42decbdf 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4804,7 +4804,8 @@"agentSwitch": {"label": "已从 {{from}} 切换到 {{to}}","toggleHint": "查看交接内容",- "handoffTitle": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)",+ "handoffTitle": "交接内容——切换时发送给新引擎的上下文摘要(不计入对话记录,仅在此展示)",+ "handoffTitleEnglishSource": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)","resumedBadge": "已续接原对话"}},diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex 50013efa1c..5426aaf1a4 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -56,6 +56,7 @@"agentSwitchViewHandoff": "{{label}}, view handoff","sessionResumedPill": "Resumed original session","handoffContentDesc": "Handoff — context summary sent to the new engine when switching (not part of the chat transcript; shown only here)",+ "handoffContentDescEnglishSource": "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.jsonindex 203b1d7aaf..621f9bce9b 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -55,7 +55,8 @@"agentSwitchLabel": "{{from}} から {{to}} に切り替えました","agentSwitchViewHandoff": "{{label}}、引き継ぎ内容を表示","sessionResumedPill": "元のセッションを再開しました",- "handoffContentDesc": "引き継ぎ内容——切り替え時に新しいエンジンへ送るコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)",+ "handoffContentDesc": "引き継ぎ内容——切り替え時に新しいエンジンへ送るコンテキスト要約(チャット履歴には含まれず、ここでのみ表示)",+ "handoffContentDescEnglishSource": "引き継ぎ内容——切り替え時に新しいエンジンへ送るコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)","openDiagramDetail": "図の詳細を開く","sessionChipFallback": "セッション {{id}}","imageFallbackTitle": "画像",diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex e895c768b8..b57be74474 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -55,7 +55,8 @@"agentSwitchLabel": "{{from}}에서 {{to}}(으)로 전환됨","agentSwitchViewHandoff": "{{label}}, 인계 내용 보기","sessionResumedPill": "원래 세션을 재개함",- "handoffContentDesc": "인계 내용——전환 시 새 엔진에 전달되는 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)",+ "handoffContentDesc": "인계 내용——전환 시 새 엔진에 전달되는 컨텍스트 요약(대화 기록에 포함되지 않으며 여기에서만 표시)",+ "handoffContentDescEnglishSource": "인계 내용——전환 시 새 엔진에 전달되는 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)","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.jsonindex 0f00ee0615..290a0e03b6 100644--- a/apps/mobile/src/i18n/locales/zh-CN/message.json+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json@@ -55,7 +55,8 @@"agentSwitchLabel": "已从 {{from}} 切换到 {{to}}","agentSwitchViewHandoff": "{{label}},查看交接内容","sessionResumedPill": "已续接原对话",- "handoffContentDesc": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)",+ "handoffContentDesc": "交接内容——切换时发送给新引擎的上下文摘要(不计入对话记录,仅在此展示)",+ "handoffContentDescEnglishSource": "交接内容——切换时发送给新引擎的上下文摘要,原文为英文(不计入对话记录,仅在此展示)","openDiagramDetail": "打开图表详情","sessionChipFallback": "对话 {{id}}","imageFallbackTitle": "图片",diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 8f1fae4eec..117f2b5865 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -2931,6 +2931,17 @@ function CollabCardShell({// 提到组件外避免 MobileAgentSwitchCard 每次重渲染都重建闭包。const agentSwitchEngineLabel = (kind: unknown): string => (kind === 'codex' ? 'Codex' : 'Claude Code');+// 交接正文是否为英文格式(与 desktop SystemCard.tsx 同款判据)。content.handoff 是持久化+// 数据:英文化之前落库的行仍是中文正文,升级后展开老卡片看到的就是中文——标题里「原文为+// 英文」那句只能对新格式说。判据取英文结束标记的公共尾巴:三种英文标记都含它,旧中文标记不含。+const ENGLISH_HANDOFF_TERMINATOR_TAIL = "; the user's new message follows ==";++function isEnglishSourceHandoff(handoff: string): boolean {+ // 锚在尾部而非 includes(与 desktop SystemCard.tsx 同款):正文里嵌着历史原文,+ // 可能自身就含这段尾串,那样旧中文交接会被误判成英文。+ return handoff.trimEnd().endsWith(ENGLISH_HANDOFF_TERMINATOR_TAIL);+}+// session-agent-switch 边界卡 —— 1:1 对齐桌面 SystemCard.tsx 的 AgentSwitchCard:// 「分隔线 + 居中药丸」语言(⇄ + 已从 X 切换到 Y + · 目标模型 + 可选 · 已续接原会话),// 而非通用盒子卡片。药丸可点展开交接摘要面板(切换时发给新引擎的上下文全文,数据来自@@ -2983,7 +2994,11 @@ function MobileAgentSwitchCard({ data }: { data?: Record<string, unknown> }) {{expanded && handoff ? (<View style={styles.agentSwitchHandoffPanel}><Text style={styles.agentSwitchHandoffTitle}>- {t('message.renderer.handoffContentDesc')}+ {t(+ isEnglishSourceHandoff(handoff)+ ? 'message.renderer.handoffContentDescEnglishSource'+ : 'message.renderer.handoffContentDesc',+ )}</Text>{/* 交接全文内联展开:卡片本身在消息列表(LegendList)内,不再套内层 ScrollView——Android 上嵌套竖向滚动会被父列表截获手势导致内层滚不动(Fabric 更甚)。