Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 远程发送改为乐观收口 (#1615)
Dashe0ca17d61811
diff --git a/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts b/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.tsindex 1370e8b57e..a7952a80a4 100644--- a/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkAutoTitleWiring.test.ts@@ -24,8 +24,12 @@ const sessionsSource = readFileSync().replace(/\r\n?/g, '\n');function handlerBody(channel: string, nextChannel: string): string {- const start = registerSource.indexOf(`ipcMain.handle(MAKER_INVOKE.${channel}`);- const end = registerSource.indexOf(`ipcMain.handle(MAKER_INVOKE.${nextChannel}`, start);+ const start = registerSource.search(+ new RegExp(`ipcMain\\.handle\\(\\s*MAKER_INVOKE\\.${channel}`),+ );+ const nextPattern = new RegExp(`ipcMain\\.handle\\(\\s*MAKER_INVOKE\\.${nextChannel}`);+ const nextMatch = nextPattern.exec(registerSource.slice(start + 1));+ const end = nextMatch ? start + 1 + nextMatch.index : -1;expect(start).toBeGreaterThan(-1);expect(end).toBeGreaterThan(start);return registerSource.slice(start, end);@@ -55,11 +59,132 @@ describe('device-link auto-title wiring', () => {// 改掉默认名 / 合成占位 / fork 占位就是凭空改名(review P1)。const body = handlerBody('INPUT_STEER', 'INPUT_STOP');expect(body).toMatch(/const accepted = await inputCoordinator\.steer\(/);- expect(body).toMatch(/if \(accepted\) commitAutoTitle\(\);/);+ expect(body).toMatch(/if \(accepted\)\s*\{[\s\S]*?commitAutoTitle\(\);/);const acceptAt = body.indexOf('await inputCoordinator.steer(');expect(body.indexOf('commitAutoTitle()')).toBeGreaterThan(acceptAt);});+ it('每个异步阶段都受 clear generation 与终态 session 行双重保护', () => {+ for (const [channel, nextChannel, acceptToken, generationGuardToken] of [+ [+ 'INPUT_ENQUEUE',+ 'INPUT_COMPACT',+ 'inputCoordinator.enqueue',+ 'assertCurrentInputGeneration();',+ ],+ [+ 'INPUT_STEER',+ 'INPUT_STOP',+ 'await inputCoordinator.steer(',+ 'assertCurrentInputGeneration();',+ ],+ ] as const) {+ const body = handlerBody(channel, nextChannel);+ const deviceLinkAt = body.indexOf('const deviceLinkInvoke = isDeviceLinkInvoke();');+ const sessionRowMatches = [...body.matchAll(/await getInputSessionRow\(sid\)/g)].map(+ (match) => match.index ?? -1,+ );+ const earlySessionGuardAt = sessionRowMatches[0] ?? -1;+ const generationAt = body.indexOf(+ 'const inputGeneration = inputCoordinator.getGeneration(sid);',+ );+ const stages = [+ /(?:await\s+)?inputCoordinator\.ensureQueueRestored\(sid\)/,+ /await materializeQueuedOssAttachments/,+ /await hydrateQueuedAgentReferences/,+ /await prepareDeviceLinkAutoTitle\(sid, queued\)/,+ ];+ const acceptAt = body.indexOf(acceptToken);++ expect(deviceLinkAt).toBeGreaterThan(-1);+ expect(generationAt).toBeGreaterThan(deviceLinkAt);+ expect(earlySessionGuardAt).toBeGreaterThan(deviceLinkAt);+ expect(earlySessionGuardAt).toBeGreaterThan(generationAt);+ const earlyGenerationGuardAt = body.indexOf(generationGuardToken, earlySessionGuardAt);+ expect(earlyGenerationGuardAt).toBeGreaterThan(earlySessionGuardAt);+ let cursor = earlyGenerationGuardAt;+ let finalGuardAt = -1;+ for (const stage of stages) {+ const stageMatch = stage.exec(body.slice(cursor));+ const awaitAt = stageMatch?.index === undefined ? -1 : cursor + stageMatch.index;+ const guardAt = body.indexOf(generationGuardToken, awaitAt);+ expect(awaitAt, `missing ${stage}`).toBeGreaterThan(cursor);+ expect(guardAt, `missing generation guard after ${stage}`).toBeGreaterThan(awaitAt);+ cursor = guardAt;+ finalGuardAt = guardAt;+ }+ const finalSessionGuardAt = sessionRowMatches.find((index) => index > cursor) ?? -1;+ expect(finalSessionGuardAt).toBeGreaterThan(cursor);+ finalGuardAt = body.indexOf(generationGuardToken, finalSessionGuardAt);+ expect(finalGuardAt).toBeGreaterThan(finalSessionGuardAt);+ expect(acceptAt).toBeGreaterThan(finalGuardAt);+ expect(sessionRowMatches.length).toBeGreaterThanOrEqual(2);++ if (channel === 'INPUT_ENQUEUE' || channel === 'INPUT_STEER') {+ expect(body).toContain('REMOTE_OPTIMISTIC_INPUT_SUPERSEDED');+ expect(body).not.toContain(+ 'if (!isCurrentInputGeneration()) return inputCoordinator.getProjection(sid);',+ );+ }++ if (channel === 'INPUT_STEER') {+ expect(body).toContain(+ 'allowMissingTrustedContexts: deviceLinkInvoke && steerOpts?.removeFromQueue === true',+ );+ const steerAt = body.indexOf('await inputCoordinator.steer(', finalGuardAt);+ const postSteerGuard = body.indexOf('assertCurrentInputGeneration();', steerAt);+ const commitAt = body.indexOf('commitAutoTitle();', postSteerGuard);+ expect(steerAt).toBeGreaterThan(finalGuardAt);+ expect(postSteerGuard).toBeGreaterThan(steerAt);+ expect(commitAt).toBeGreaterThan(postSteerGuard);+ expect(body.slice(postSteerGuard, commitAt)).toMatch(/if \(accepted\)\s*\{/);+ }+ }+ expect(registerSource).toContain("if (!row || row.status === 'deleted')");+ expect(registerSource).not.toContain("currentSessionRow.status === 'archived'");+ });++ it('排队编辑的异步物化不会跨 clear 边界提交旧内容', () => {+ const body = handlerBody('INPUT_UPDATE_CONTENT', 'INPUT_MOVE');+ expect(body).toContain('const remote = isDeviceLinkInvoke();');+ expect(body).toContain('if (parsed.clientId !== cid)');++ const generationAt = body.indexOf(+ 'const inputGeneration = inputCoordinator.getGeneration(sid);',+ );+ const sessionRowMatches = [...body.matchAll(/await getInputSessionRow\(sid\)/g)].map(+ (match) => match.index ?? -1,+ );+ const earlySessionGuardAt = sessionRowMatches[0] ?? -1;+ const earlyGenerationGuardAt = body.indexOf(+ 'if (!isCurrentInputGeneration())',+ earlySessionGuardAt,+ );+ const materializeAt = body.indexOf('await materializeQueuedOssAttachments');+ const materializeGuardAt = body.indexOf('assertCurrentInputGeneration();', materializeAt);+ const hydrateAt = body.indexOf('await hydrateQueuedAgentReferences', materializeAt);+ const hydrateGuardAt = body.indexOf('assertCurrentInputGeneration();', hydrateAt);+ const finalSessionGuardAt = sessionRowMatches.find((index) => index > hydrateAt) ?? -1;+ const finalGenerationGuardAt = body.indexOf(+ 'assertCurrentInputGeneration();',+ finalSessionGuardAt,+ );+ const updateAt = body.indexOf('inputCoordinator.updateContent', finalSessionGuardAt);++ expect(generationAt).toBeGreaterThan(-1);+ expect(earlySessionGuardAt).toBeGreaterThan(generationAt);+ expect(earlyGenerationGuardAt).toBeGreaterThan(earlySessionGuardAt);+ expect(materializeAt).toBeGreaterThan(earlyGenerationGuardAt);+ expect(materializeGuardAt).toBeGreaterThan(materializeAt);+ expect(hydrateAt).toBeGreaterThan(materializeGuardAt);+ expect(hydrateGuardAt).toBeGreaterThan(hydrateAt);+ expect(finalSessionGuardAt).toBeGreaterThan(hydrateGuardAt);+ expect(finalGenerationGuardAt).toBeGreaterThan(finalSessionGuardAt);+ expect(updateAt).toBeGreaterThan(finalGenerationGuardAt);+ expect(body).toContain('queued.clientId must match clientId');+ expect(body).toContain('await materialized.cleanupBeforeAcceptance?.()');+ });+it('只对远控调用生效:本机 renderer 走 maker:auto-title,不在这里重复起名', () => {const start = registerSource.indexOf('const prepareDeviceLinkAutoTitle =');expect(start).toBeGreaterThan(-1);@@ -76,14 +201,20 @@ describe('user rename notification ordering', () => {// 智能标题仍能满足 `WHERE title = 期望值` 把用户刚保存的名字盖掉(review P1)。for (const [note, write] of [// local-db:sessions:update(本机重命名框)- ["if (typeof p.title === 'string') noteUserTitleWritten(sid);",- 'await db.update(sessions).set(setObj).where(eq(sessions.id, sid));'],+ [+ "if (typeof p.title === 'string') noteUserTitleWritten(sid);",+ 'await db.update(sessions).set(setObj).where(eq(sessions.id, sid));',+ ],// patchSessionMetaInDb(device-link 远程改名)- ['if (patch.title !== undefined) noteUserTitleWritten(sessionId);',- 'await db.update(sessions).set(setObj).where(eq(sessions.id, sessionId));'],+ [+ 'if (patch.title !== undefined) noteUserTitleWritten(sessionId);',+ 'await db.update(sessions).set(setObj).where(eq(sessions.id, sessionId));',+ ],// renameSessionTitlesInDb(MCP 批量改名)- ['for (const change of changes) noteUserTitleWritten(change.sessionId);',- "getDbClient()\n .tx('sessions.renameTitles'"],+ [+ 'for (const change of changes) noteUserTitleWritten(change.sessionId);',+ "getDbClient()\n .tx('sessions.renameTitles'",+ ],] as const) {const noteAt = sessionsSource.indexOf(note);expect(noteAt).toBeGreaterThan(-1);diff --git a/apps/desktop/src/main/__tests__/deviceLinkInputSteerDedupeWiring.test.ts b/apps/desktop/src/main/__tests__/deviceLinkInputSteerDedupeWiring.test.tsnew file mode 100644index 0000000000..04b1f321b6--- /dev/null+++ b/apps/desktop/src/main/__tests__/deviceLinkInputSteerDedupeWiring.test.ts@@ -0,0 +1,59 @@+/**+ * device-link INPUT_STEER 的幂等接线契约。+ *+ * coordinator 覆盖运行期状态机;register.ts 还必须在附件物化前以及最后一个+ * await 后识别 queued-row promotion 的弱网重传,否则两个同 clientId 请求可+ * 分别生成附件 owner,重复请求会覆盖首个请求的 current owner。+ */+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');++function inputSteerHandlerBody(): string {+ const start = registerSource.search(/ipcMain\.handle\(\s*MAKER_INVOKE\.INPUT_STEER/);+ const next = registerSource+ .slice(start + 1)+ .search(/ipcMain\.handle\(\s*MAKER_INVOKE\.INPUT_STOP/);+ expect(start).toBeGreaterThan(-1);+ expect(next).toBeGreaterThan(-1);+ return registerSource.slice(start, start + 1 + next);+}++describe('device-link INPUT_STEER dedupe wiring', () => {+ it('rechecks duplicate ownership before materialisation and owner activation', () => {+ const body = inputSteerHandlerBody();+ const duplicateCheckAt = body.indexOf('const isKnownSteerDuplicate =');+ const duplicateCalls = [...body.matchAll(/isKnownSteerDuplicate\(\)/g)].map(+ (match) => match.index ?? -1,+ );+ const durableAt = body.indexOf('await remoteInputClientIdWasPersisted', duplicateCheckAt);+ const pendingAt = body.indexOf('const steeringStoredQueueItem =', durableAt);+ const materializeAt = body.indexOf('await materializeQueuedOssAttachmentsDeferred', durableAt);+ const activateAt = body.indexOf(+ 'queuedAttachmentOwnership.activateCurrentOwner',+ materializeAt,+ );++ expect(duplicateCheckAt).toBeGreaterThan(-1);+ expect(duplicateCalls).toHaveLength(3);+ expect(duplicateCalls[0]).toBeLessThan(durableAt);+ expect(duplicateCalls[1]).toBeGreaterThan(durableAt);+ expect(duplicateCalls[1]).toBeLessThan(materializeAt);+ expect(pendingAt).toBeGreaterThan(duplicateCalls[1] ?? -1);+ expect(materializeAt).toBeGreaterThan(durableAt);+ expect(duplicateCalls[2]).toBeGreaterThan(materializeAt);+ expect(duplicateCalls[2]).toBeLessThan(activateAt);+ expect(body.slice(duplicateCalls[2], activateAt)).toContain(+ 'await materialized.cleanupBeforeAcceptance?.()',+ );+ expect(body.slice(duplicateCalls[2], activateAt)).toContain(+ 'await discardSpecificQueuedAttachmentOwnership',+ );+ });+});diff --git a/apps/desktop/src/main/__tests__/ghostSetupInteractionLifecycle.test.ts b/apps/desktop/src/main/__tests__/ghostSetupInteractionLifecycle.test.tsindex 864c709bfd..eb84f0e72d 100644--- a/apps/desktop/src/main/__tests__/ghostSetupInteractionLifecycle.test.ts+++ b/apps/desktop/src/main/__tests__/ghostSetupInteractionLifecycle.test.ts@@ -67,7 +67,7 @@ describe('host-owned interaction lifecycle contract', () => {expect(ownershipHelper).toContain(bridgeName);}expect(registerSource).toMatch(- /assertResolveInteractionOrigin\(\s*decision,\s*isPendingDesktopOnlyConfirmation\(requestId\),\s*\);/,+ /assertResolveInteractionOrigin\(\s*decision,\s*isPendingDesktopOnlyConfirmation\(requestId\),?\s*\);/,);});diff --git a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.tsindex 971d7517c2..5704623c0b 100644--- a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts+++ b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts@@ -18,7 +18,10 @@ const sessionViewSource = readFileSync(function matchIndexes(haystack: string, pattern: RegExp): number[] {const indexes: number[] = [];- const re = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`);+ const re = new RegExp(+ pattern.source,+ pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`,+ );for (const match of haystack.matchAll(re)) {if (typeof match.index === 'number') indexes.push(match.index);}@@ -27,8 +30,11 @@ function matchIndexes(haystack: string, pattern: RegExp): number[] {describe('interrupted continuation enqueue contract', () => {it('does not durable-ack continue prompts at INPUT_ENQUEUE or onAccepted time', () => {- const enqueueStart = registerSource.indexOf('ipcMain.handle(MAKER_INVOKE.INPUT_ENQUEUE');- const enqueueEnd = registerSource.indexOf('ipcMain.handle(MAKER_INVOKE.INPUT_COMPACT', enqueueStart);+ const enqueueStart = registerSource.search(/ipcMain\.handle\(\s*MAKER_INVOKE\.INPUT_ENQUEUE/);+ const enqueueEndMatch = /ipcMain\.handle\(\s*MAKER_INVOKE\.INPUT_COMPACT/.exec(+ registerSource.slice(enqueueStart + 1),+ );+ const enqueueEnd = enqueueEndMatch ? enqueueStart + 1 + enqueueEndMatch.index : -1;expect(enqueueStart).toBeGreaterThan(-1);expect(enqueueEnd).toBeGreaterThan(enqueueStart);const enqueueHandler = registerSource.slice(enqueueStart, enqueueEnd);diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex cc5c146a99..3b0fafa124 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -27,11 +27,11 @@ describe('maker:event hot path ordering', () => {expect(wireSessionSource).toContain('if (existing?.session === session)');expect(wireSessionSource).toContain('for (const dispose of existing.disposers) dispose();');expect(wireSessionSource).toContain('existing.session.setInteractionListener(null);');- expect(wireSessionSource).toContain(- 'registration.disposers.push(session.onEvent((event: AgentEvent) => {',+ expect(wireSessionSource).toMatch(+ /registration\.disposers\.push\(\s*session\.onEvent\(\(event: AgentEvent\) => \{/,);- expect(wireSessionSource).toContain(- 'registration.disposers.push(session.onStatusChange((status) => {',+ expect(wireSessionSource).toMatch(+ /registration\.disposers\.push\(\s*session\.onStatusChange\(\(status\) => \{/,);// #1286:拆线(实例替换 / 会话关闭)必须给插件补 did-turn-end,否则订阅方的// 「AI 在忙」外层状态永久卡在 working,除重启没有自愈手段。同一个 disposer 里@@ -72,7 +72,7 @@ describe('maker:event hot path ordering', () => {it('defers remote auth island errors until the renderer reports retry failure', () => {const wireSessionSource = extractWireSessionSource();const deferredHandler = source.match(- /ipcMain\.handle\(MAKER_INVOKE\.PERSIST_TURN_ERROR_DEFERRED,[\s\S]*?\n {2}\}\);/,+ /ipcMain\.handle\(\s*MAKER_INVOKE\.PERSIST_TURN_ERROR_DEFERRED,[\s\S]*?\n\s*\}\);/,)?.[0];expect(source).toContain('function isRemoteAuthRetryErrorEvent(');@@ -166,6 +166,20 @@ describe('maker:event hot path ordering', () => {expect(terminalContexts.some((context) => context.includes("event.type === 'done'"))).toBe(true);expect(terminalContexts.some((context) => context.includes('isTerminalTurnErrorEvent(event)'))).toBe(true);expect([...statusContexts, ...terminalContexts].join('\n')).not.toContain("event.type === 'error'");+ // Keep a direct structural guard too: each terminal idle assignment must+ // remain inside its corresponding done/error branch.+ expect(+ wireSessionSource.lastIndexOf(+ "if (event.type === 'done') {",+ terminalIdleAssignments[0],+ ),+ ).toBeGreaterThanOrEqual(0);+ expect(+ wireSessionSource.lastIndexOf(+ 'if (isTerminalTurnErrorEvent(event)) {',+ terminalIdleAssignments[1],+ ),+ ).toBeGreaterThanOrEqual(0);});it('does not persist remote Codex account snapshots into local account usage', () => {@@ -520,20 +534,24 @@ describe('maker:event hot path ordering', () => {expect(codexDoneSource).toContain('const codexAuthInjection = isRemoteCodexSession ? null : getCodexProxyAuthInjection();');expect(wireSessionSource).toContain('!turnModelPromiseBySession.has(session.id)');expect(wireSessionSource).toContain('turnModelPromiseBySession.set(session.id, readSessionModelForUsage(session.id));');- expect(codexDoneSource).toContain('const modelPromise = turnModelPromiseBySession.get(session.id) ?? readSessionModelForUsage(session.id);');+ expect(codexDoneSource).toMatch(+ /const modelPromise\s*=\s*turnModelPromiseBySession\.get\(session\.id\)\s*\?\?\s*readSessionModelForUsage\(session\.id\);/,+ );expect(codexDoneSource).toContain('turnModelPromiseBySession.delete(session.id);');expect(codexDoneSource).not.toContain('hasCodexOAuthLogin()');expect(codexDoneSource).toContain('promptTokens + completionTokens + cachedTokens');expect(codexDoneSource).not.toContain('promptTokens + completionTokens + reasoningTokens + cachedTokens');expect(codexDoneSource).toContain('const isCustomProviderRoute =');expect(codexDoneSource).toContain('isUserProviderSession(session.id)');- expect(codexDoneSource).toContain("&& pricingModel.startsWith('codex/');");- expect(codexDoneSource).toContain('&& pricingModel.startsWith(XAI_MODEL_PREFIX);');+ expect(codexDoneSource).toMatch(/&&\s*pricingModel\.startsWith\('codex\/'\);/);+ expect(codexDoneSource).toMatch(/&&\s*pricingModel\.startsWith\(XAI_MODEL_PREFIX\);/);expect(codexDoneSource).toContain('const hasGatewayKey = Boolean(readClaudeApiKey());');expect(codexDoneSource).toContain('const hasEffectiveGatewayRoute =');expect(codexDoneSource).toContain('!isCustomProviderRoute');expect(codexDoneSource).toContain('(sessionProvider === \'xd\' && hasGatewayKey)');- expect(codexDoneSource).toContain('const isSubscriptionValue = isRemoteCodexSession ||');+ expect(codexDoneSource).toMatch(+ /const isSubscriptionValue\s*=\s*isRemoteCodexSession\s*\|\|/,+ );expect(codexDoneSource).toContain('isCodexXaiProviderRoute ||');// 用正则而非整串匹配:这段条件已按多行排版,单行字面量会因换行/缩进调整而假失败。// 要守的语义是——订阅计价只在「OpenAI 供应商 + oauth-bearer 注入 + 无生效网关路由」时成立。@@ -581,14 +599,17 @@ describe('maker:event hot path ordering', () => {const schedulerCostRecordIndex = codexDoneSource.indexOf('await recordSchedulerTurnCost({');expect(costRecordIndex).toBeGreaterThanOrEqual(0);expect(modelCostRecordIndex).toBeGreaterThanOrEqual(0);- expect(modelCostRecordIndex).toBeGreaterThan(codexDoneSource.indexOf('const pricing = isSubscriptionValue && !isCodexXaiProviderRoute'));+ expect(modelCostRecordIndex).toBeGreaterThan(codexDoneSource.indexOf('const pricing = isSubscriptionValue'));expect(schedulerCostRecordIndex).toBeGreaterThan(costRecordIndex);expect(codexDoneSource).toContain('clientId: turnAssistantPersistId');expect(codexDoneSource).toContain('money,');- expect(codexDoneSource).toContain('if (!isRemoteCodexSession &&');- expect(codexDoneSource).toContain('!isCustomProviderRoute &&');- expect(codexDoneSource).toContain("!model.startsWith(XAI_MODEL_PREFIX) &&");- expect(codexDoneSource).toContain("(codexAuthInjection === 'env-key' || model.startsWith('codex/') || (sessionProvider === 'xd' && hasGatewayKey))");+ expect(codexDoneSource).toMatch(+ /const hasEffectiveGatewayRoute\s*=\s*!isRemoteCodexSession\s*&&\s*!isCustomProviderRoute\s*&&/,+ );+ expect(codexDoneSource).toContain('const isCodexXaiProviderRoute =');+ expect(codexDoneSource).toMatch(+ /codexAuthInjection === 'env-key'\s*\|\|\s*isCodexBudgetRoute\s*\|\|\s*\(sessionProvider === 'xd' && hasGatewayKey\)/,+ );expect(codexDoneSource).not.toContain("sessionProvider !== 'xai'");expect(codexDoneSource).not.toContain('isEstimate: true');});@@ -619,8 +640,8 @@ describe('maker:event hot path ordering', () => {);// 订阅轮 (Claude Anthropic 订阅或 bridge 订阅直连) 打 #billing=subscription 标记,// 仪表盘按订阅估算价折算; 其余轮仍写归一化裸 id。- expect(claudeDoneSource).toContain(- 'model: isClaudeSubscriptionValueRow ? claudeSubscriptionUsageModelKey(m.model) : m.model,',+ expect(claudeDoneSource).toMatch(+ /model:\s*isClaudeSubscriptionValueRow\s*\?\s*claudeSubscriptionUsageModelKey\(m\.model\)\s*:\s*m\.model,/,);expect(claudeDoneSource).toContain("isClaudeSubscriptionSession && !m.money && isAnthropicModel(m.model)",diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.tsindex c4af0127ab..976150061d 100644--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts@@ -29,9 +29,19 @@ vi.mock('../logger.js', () => ({}));const { mockSend } = vi.hoisted(() => ({ mockSend: vi.fn() }));+const ownerScopeState = vi.hoisted(() => ({+ current: true,+ scope: { ownerScopeKey: 'owner-a', ownerStamp: undefined },+}));vi.mock('electron', () => ({BrowserWindow: { getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: mockSend } }] },}));+vi.mock('../device-link/broadcast-tap.js', () => ({+ captureDataOwnerBroadcastScope: vi.fn(() => ownerScopeState.scope),+ isDataOwnerBroadcastScopeCurrent: vi.fn(() => ownerScopeState.current),+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),+ tapWindowBroadcast: vi.fn(),+}));import {broadcastMessageAgentMetaUpdate,@@ -78,6 +88,7 @@ const broadcastGuard = () => expect.objectContaining({ shouldBroadcast: expect.abeforeEach(() => {vi.clearAllMocks();+ ownerScopeState.current = true;noteSessionClearBoundary(SESSION, null);clearSessionPersistState(SESSION);});@@ -182,6 +193,15 @@ describe('update_plan tool_use persistence', () => {});describe('agent_kind enqueue snapshot', () => {+ it('owner boundary after commit keeps the durable result instead of triggering retry', async () => {+ const result = await enqueueDurableWrite('post-commit-owner-switch', () => {+ ownerScopeState.current = false;+ return { committed: true };+ });++ expect(result).toEqual({ committed: true });+ });+it('writeChain 延迟期间切换引擎,消息仍使用事件入队时的 agent_kind', async () => {let release!: () => void;const gate = new Promise<void>((resolve) => { release = resolve; });@@ -875,7 +895,11 @@ describe('consumeLastAssistantPersistId(per-turn 费用挂载的目标消息追'assistant-final',{ turnCompleted: true },);- expect(broadcastMessageAgentMetaUpdate).toHaveBeenCalledWith(SESSION, 'assistant-final');+ expect(broadcastMessageAgentMetaUpdate).toHaveBeenCalledWith(+ SESSION,+ 'assistant-final',+ expect.objectContaining({ ownerStamp: undefined }),+ );});it('terminal error seal 以 durable patch 写 false', async () => {@@ -885,7 +909,11 @@ describe('consumeLastAssistantPersistId(per-turn 费用挂载的目标消息追'assistant-failed',{ turnCompleted: false },);- expect(broadcastMessageAgentMetaUpdate).toHaveBeenCalledWith(SESSION, 'assistant-failed');+ expect(broadcastMessageAgentMetaUpdate).toHaveBeenCalledWith(+ SESSION,+ 'assistant-failed',+ expect.objectContaining({ ownerStamp: undefined }),+ );});it('纯 tool turn 没有 assistant 时不写 seal', async () => {@@ -921,7 +949,11 @@ describe('onTurnErrorEvent — terminal error 持久化', () => {// live 消息流与 banner 双显示(设计取舍见 onTurnErrorEvent 头注释)。expect((optsArg as { shouldBroadcast?: () => boolean })?.shouldBroadcast?.()).toBe(false);// 脏信号必须发:让已加载历史的后台会话下次打开时从 DB 重拉,error 卡正常浮现。- expect(mockSend).toHaveBeenCalledWith('local-db:session:error-persisted', { sessionId: SESSION });+ expect(mockSend).toHaveBeenCalledWith(+ 'local-db:session:error-persisted',+ { sessionId: SESSION },+ undefined,+ );});it('message 为空 → 不落库也不发脏信号', async () => {diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.tsindex 55f6294843..4fcce35684 100644--- a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts@@ -23,6 +23,7 @@ import {prependNoteToWireUserMessage,} from '../maker-ipc/agentHandoff';import {+ attachMainOwnedInputBoundary,buildMobileClientPromptNote,stampMobileClientOrigin,stripMainOnlySendOpts,@@ -195,7 +196,9 @@ describe('注入接线(源码级守卫)', () => {);it('说明只进 wire payload,落库走 persistUserMessage.content', () => {- expect(source).toContain('const mobileClientNote = deps.isMobileClientInvoke?.() === true');+ expect(source).toMatch(+ /const mobileClientNote =\s*deps\.isMobileClientInvoke\?\.\(\) === true/,+ );expect(source).toContain('prependNoteToWireUserMessage(withHandoff as HandoffWireMessage, mobileClientNote)');// 落库内容必须仍取 persistUserMessage.content —— 若改成 outgoing,提示语会写进// 用户消息、污染界面显示的原话。@@ -262,6 +265,46 @@ describe('stripMainOnlySendOpts(直连路径消毒)', () => {.toEqual({ messageUuid: 'u' });});+ it('剥掉客户端伪造的 generation,但保留待 IPC 校验的 clear token', () => {+ expect(+ stripMainOnlySendOpts({+ expectedClearBoundaryMs: 123,+ expectedInputGeneration: 77,+ messageUuid: 'u',+ }),+ ).toEqual({ expectedClearBoundaryMs: 123, messageUuid: 'u' });+ });++ it('host stamp 覆盖 wire token 并附带 generation', () => {+ expect(+ attachMainOwnedInputBoundary(+ { expectedClearBoundaryMs: 123, expectedInputGeneration: 77, messageUuid: 'u' },+ { expectedClearBoundaryMs: 456, expectedInputGeneration: 9 },+ ),+ ).toEqual({ expectedClearBoundaryMs: 456, expectedInputGeneration: 9, messageUuid: 'u' });+ });++ it('非对象 sendOpts 也映射 main-owned abort signal 到事务读取的 signal', () => {+ const controller = new AbortController();+ expect(+ attachMainOwnedInputBoundary(undefined, {+ expectedClearBoundaryMs: 456,+ expectedInputGeneration: 9,+ inputAbortSignal: controller.signal,+ }),+ ).toEqual({+ expectedClearBoundaryMs: 456,+ expectedInputGeneration: 9,+ signal: controller.signal,+ });+ });++ it('剥掉 wire 注入的 signal,只允许 main 写入 AbortSignal', () => {+ expect(stripMainOnlySendOpts({ messageUuid: 'u', signal: 'forged' })).toEqual({+ messageUuid: 'u',+ });+ });+it('其它字段原样保留', () => {const opts = { messageUuid: 'u', userName: 'n', origin: { kind: 'scheduler' } };expect(stripMainOnlySendOpts(opts)).toEqual(opts);@@ -314,15 +357,17 @@ describe('排队 / 插入两条路径的接线(源码级守卫)', () => {});it('直连 maker:send 的 wire sendOpts 必须消毒', () => {- expect(sendHandler).toContain('stripMainOnlySendOpts(sendOpts)');+ expect(sendHandler).toContain(+ 'attachMainOwnedInputBoundary(sendOpts, mainOwnedBoundaryStamp)',+ );});it('直连 maker:steer 的 wire sendOpts 同样必须消毒', () => {// 这个 channel 在 device-link allowlist 里开放,sendOpts 是调用方可控输入 ——// 不剥的话传 `{ fromMobileClient: true }` 就能让非手机轮次收到伪造的手机说明// (review P1/P2 各报一次)。契约与 maker:send 一致:该字段只由 main 盖章。- expect(register).toMatch(- /MAKER_INVOKE\.STEER[\s\S]*?steerToAgentAccepted\(sessionId, message, stripMainOnlySendOpts\(sendOpts\)\)/,+ expect(register).toContain(+ 'attachMainOwnedInputBoundary(stripMainOnlySendOpts(sendOpts), boundaryStamp)',);// coordinator 的内部调用**不得**被消毒 —— 那条路的 sendOpts 是 main 构造的透传值。expect(register).toContain('steerToAgent: (sessionId, message, sendOpts) =>');diff --git a/apps/desktop/src/main/__tests__/renameSessionTitlesInDb.test.ts b/apps/desktop/src/main/__tests__/renameSessionTitlesInDb.test.tsindex db11e96f5d..e6f0f5c4e3 100644--- a/apps/desktop/src/main/__tests__/renameSessionTitlesInDb.test.ts+++ b/apps/desktop/src/main/__tests__/renameSessionTitlesInDb.test.ts@@ -76,7 +76,12 @@ vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ drizzle: h.fvi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../git-context/prRefsStore', () => ({ recomputePrRefsForSession: vi.fn() }));vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn() }));-vi.mock('../device-link/broadcast-tap', () => ({ tapWindowBroadcast: h.tapWindowBroadcast }));+vi.mock('../device-link/broadcast-tap', () => ({+ captureDataOwnerBroadcastScope: vi.fn(() => null),+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),+ isDataOwnerBroadcastScopeCurrent: vi.fn(() => true),+ tapWindowBroadcast: h.tapWindowBroadcast,+}));vi.mock('../agent-island/service.js', () => ({getAgentIslandService: () => h.agentIslandService,}));diff --git a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.tsindex 2392e1d97c..a04a2f8edb 100644--- a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts+++ b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts@@ -61,7 +61,10 @@ vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ drizzle: h.fvi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../git-context/prRefsStore', () => ({ recomputePrRefsForSession: vi.fn() }));vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn() }));-vi.mock('../device-link/broadcast-tap', () => ({ tapWindowBroadcast: vi.fn() }));+vi.mock('../device-link/broadcast-tap', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),+ tapWindowBroadcast: vi.fn(),+}));vi.mock('../agent-island/service.js', () => ({getAgentIslandService: () => ({ handleSessionMetadataPatch: vi.fn() }),}));diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.tsindex 91f28f7e33..6f4394d13e 100644--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts@@ -41,7 +41,12 @@ vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ tx: h.tx })vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../git-context/prRefsStore', () => ({ recomputePrRefsForSession: vi.fn() }));vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn() }));-vi.mock('../device-link/broadcast-tap', () => ({ tapWindowBroadcast: h.tapWindowBroadcast }));+vi.mock('../device-link/broadcast-tap', () => ({+ captureDataOwnerBroadcastScope: vi.fn(() => null),+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),+ isDataOwnerBroadcastScopeCurrent: vi.fn(() => true),+ tapWindowBroadcast: h.tapWindowBroadcast,+}));vi.mock('../agent-island/service.js', () => ({getAgentIslandService: () => h.agentIslandService,}));@@ -215,7 +220,7 @@ describe('setSessionsStatusInDb', () => {'utf8',);const batchBody = source.match(- /export async function setSessionsStatusInDb[\s\S]*?return applied\.map/,+ /export async function setSessionsStatusInDb[\s\S]*return applied\.map/,)?.[0];expect(batchBody).toContain('scheduleWorktreeRecycleForStatusChange(item.sessionId, item.status)');});diff --git a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.tsindex eb432c796c..564d77bd24 100644--- a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts+++ b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts@@ -77,7 +77,12 @@ vi.mock('../logger', () => ({vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../git-context/prRefsStore', () => ({ recomputePrRefsForSession: vi.fn(() => Promise.resolve()) }));vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn() }));-vi.mock('../device-link/broadcast-tap', () => ({ tapWindowBroadcast: h.tapWindowBroadcast }));+vi.mock('../device-link/broadcast-tap', () => ({+ captureDataOwnerBroadcastScope: vi.fn(() => null),+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),+ isDataOwnerBroadcastScopeCurrent: vi.fn(() => true),+ tapWindowBroadcast: h.tapWindowBroadcast,+}));vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ drizzle: h.fakeDb }) }));vi.mock('../agent-island/service.js', () => ({getAgentIslandService: () => h.agentIslandService,@@ -164,14 +169,15 @@ describe('touchUserSendInDb 广播 sessions:patched(device-link 项目归属收describe('clearSessionContextInDb 广播 sessions:patched(device-link /clear 收敛)', () => {it('写 clearedAt + sdkSessionId=null,并用 ISO clearedAt 广播给本机窗口和控制端镜像', async () => {const atMs = 1_700_000_123_000;+ // Drizzle's MAX/COALESCE expressions are not JavaScript numbers. Mock the+ // SELECT read-back with the effective values that SQLite would return.+ h.selectResults.push([{ clearedAt: atMs, updatedAt: atMs }]);await clearSessionContextInDb('sess-clear', atMs);expect(h.updateSetCalls).toHaveLength(1);- expect(h.updateSetCalls[0]).toEqual({- sdkSessionId: null,- clearedAt: atMs,- updatedAt: atMs,- });+ expect(h.updateSetCalls[0].sdkSessionId).toBeNull();+ expect(typeof h.updateSetCalls[0].clearedAt).not.toBe('number');+ expect(typeof h.updateSetCalls[0].updatedAt).not.toBe('number');const iso = new Date(atMs).toISOString();expect(h.webContentsSend).toHaveBeenCalledWith('local-db:sessions:patched', {diff --git a/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts b/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.tsindex 19447ddc40..4edb4edabf 100644--- a/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts+++ b/apps/desktop/src/main/__tests__/turnCostBroadcaster.test.ts@@ -21,6 +21,15 @@ vi.mock('electron', () => ({vi.mock('../logger.js', () => ({createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),}));+const ownerScopeState = vi.hoisted(() => ({+ current: true,+ scope: { ownerScopeKey: 'owner-a', ownerStamp: undefined },+}));+vi.mock('../device-link/broadcast-tap.js', () => ({+ captureDataOwnerBroadcastScope: vi.fn(() => ownerScopeState.scope),+ isDataOwnerBroadcastScopeCurrent: vi.fn(() => ownerScopeState.current),+ tapWindowBroadcast: vi.fn(),+}));vi.mock('../localDb/ipc/messages.js', () => ({patchMessageAgentMetaWithResult: vi.fn(async (_sessionId: string, _clientId: string, patch: Record<string, unknown>) => ({previous: {},@@ -128,9 +137,22 @@ const DETAILS = buildTurnUsageDetails({beforeEach(() => {vi.clearAllMocks();+ ownerScopeState.current = true;});describe('recordTurnCostOnMessage', () => {+ it('owner boundary after patch keeps success and suppresses stale broadcast', async () => {+ const { deps, broadcasts } = makeDeps(true);+ deps.enqueue = vi.fn(async (_label, fn) => {+ const result = await fn();+ ownerScopeState.current = false;+ return result;+ });++ await expect(recordTurnCostOnMessage(ARGS, deps)).resolves.toBe(true);+ expect(broadcasts).toHaveLength(0);+ });+it('patch 成功 → 写入原始分段与本用户轮累计,并广播同值', async () => {const { deps, broadcasts, patchCalls } = makeDeps(true);await expect(recordTurnCostOnMessage(ARGS, deps)).resolves.toBe(true);@@ -504,6 +526,28 @@ describe('recordSchedulerTurnCost', () => {expect(recordDirect).not.toHaveBeenCalled();});+ it('owner boundary after message ledger commit does not fall back to direct charging', async () => {+ const { deps } = makeDeps(true);+ deps.enqueue = vi.fn(async (_label, fn) => {+ const result = await fn();+ ownerScopeState.current = false;+ return result;+ });+ const recordOnMessage: typeof recordTurnCostOnMessage = (args) =>+ recordTurnCostOnMessage(args, deps);+ const recordDirect = vi.fn(async () => 'schedule-1');++ await expect(recordSchedulerTurnCost(+ {+ ...ARGS,+ turnOrigin: schedulerOrigin,+ },+ { recordOnMessage, recordDirect },+ )).resolves.toBeNull();++ expect(recordDirect).not.toHaveBeenCalled();+ });+it('纯 tool turn 没有 assistant message 时按 runId 直接归因并刷新自动化', async () => {const recordOnMessage = vi.fn(async () => true);const recordDirect = vi.fn(async () => 'schedule-1');diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex 221ffcc6c3..9dd27411ca 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -125,6 +125,7 @@ vi.mock('../layoutPreferenceStore.js', () => ({}));vi.mock('../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: mocks.tapWindowBroadcast,}));diff --git a/apps/desktop/src/main/appSessionState.ts b/apps/desktop/src/main/appSessionState.tsindex 0b8170e7a3..f2f0e6574a 100644--- a/apps/desktop/src/main/appSessionState.ts+++ b/apps/desktop/src/main/appSessionState.ts@@ -12,6 +12,7 @@ import crypto from 'node:crypto';import { createLogger } from './logger.js';import { createOverrideSettingsFile } from './maker-host/override-settings-file.js';import { LOCAL_PROFILE_DATA_OWNER_ID } from './profile/profileRegistryModel.js';+import type { DataOwnerPushStamp } from '../shared/dataOwnerPush.js';export type AppSessionMode = 'signed-out' | 'local' | 'cloud';@@ -99,6 +100,15 @@ export function getActiveAppSession(): ActiveAppSession {return { ...ensureLoaded() };}+/** Snapshot the owner boundary for a live main → renderer/device-link frame. */+export function getActiveDataOwnerPushStamp(): DataOwnerPushStamp {+ const session = ensureLoaded();+ return {+ dataOwnerId: session.dataOwnerId,+ ownerGeneration: session.generation,+ };+}+/*** Opaque key identifying "which account is active right now".*diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex e3d3eabece..5c779193d0 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -92,6 +92,7 @@ import {beginAppSessionBoundary,commitActiveAppSession,getActiveAppSession,+ getActiveDataOwnerPushStamp,type AppSessionMode,} from './appSessionState.js';import {@@ -183,6 +184,8 @@ export interface AuthState {mode: AppSessionMode;/** Owner for local databases and owner-scoped private state. */dataOwnerId: string | null;+ /** Main-owned owner boundary generation used to fence late renderer pushes. */+ ownerGeneration: number;/** Local and cloud sessions may enter the main application. */canEnterApp: boolean;isAuthenticated: boolean;@@ -1223,10 +1226,12 @@ async function runAuthRefreshWithReplacementRetry(* 窗口,本函数沿用同样语义;overlay 等无 listener 的窗口会忽略该事件,无副作用。*/function broadcastToRenderers(channel: string, payload: unknown): void {+ const ownerStamp = getActiveDataOwnerPushStamp();for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;try {- win.webContents.send(channel, payload);+ if (ownerStamp === undefined) win.webContents.send(channel, payload);+ else win.webContents.send(channel, payload, ownerStamp);} catch (err) {log.warn(`broadcast '${channel}' to window failed (non-fatal)`, err);}@@ -1267,6 +1272,7 @@ function snapshotAuthState(): AuthState {: null,mode: appSession.mode,dataOwnerId: appSession.dataOwnerId,+ ownerGeneration: appSession.generation,canEnterApp: appSession.mode !== 'signed-out',isAuthenticated: isCloudAuthenticated,isCanary: currentUser !== null && canaryFlagStore.read(),@@ -1278,10 +1284,12 @@ function snapshotAuthState(): AuthState {/** Logged-out projection used by stale/timeout paths that must not expose newer auth state. */function snapshotLoggedOutAuthState(): AuthState {+ const appSession = getActiveAppSession();return {user: null,mode: 'signed-out',dataOwnerId: null,+ ownerGeneration: appSession.generation,canEnterApp: false,isAuthenticated: false,isCanary: false,diff --git a/apps/desktop/src/main/cindy-brain/assistantReplyHook.ts b/apps/desktop/src/main/cindy-brain/assistantReplyHook.tsindex f23c73d49e..244be7b458 100644--- a/apps/desktop/src/main/cindy-brain/assistantReplyHook.ts+++ b/apps/desktop/src/main/cindy-brain/assistantReplyHook.ts@@ -49,6 +49,8 @@ export interface AssistantReplyHookDeps {}): void;/** "意识处理中"轻指示开/关(回复已显示、后台意识还在跑的那段)。 */setPending(sessionId: string, clientId: string, pending: boolean): void;+ /** Optional owner-boundary fence for the async continuation. */+ isCurrent?(): boolean;log?: {warn(msg: string, meta?: Record<string, unknown>): void;};@@ -65,16 +67,21 @@ export async function runAssistantReplyHook(text: string,): Promise<void> {try {+ if (deps.isCurrent && !deps.isCurrent()) return;// 快路径:无 hook 意识直接返回(register.ts 调用点也已同步守卫,双保险)。if (!deps.hasHook()) return;if (!text || text.length === 0) return;if (!(await deps.isEligible(sessionId))) return;+ if (deps.isCurrent && !deps.isCurrent()) return;deps.setPending(sessionId, clientId, true);try {const result = await deps.screen(sessionId, text);+ if (deps.isCurrent && !deps.isCurrent()) return;if (result.action === 'rewrite') {+ if (deps.isCurrent && !deps.isCurrent()) return;await deps.persistRewrite(sessionId, clientId, result.text);+ if (deps.isCurrent && !deps.isCurrent()) return;deps.broadcastRewritten({sessionId,clientId,@@ -83,6 +90,7 @@ export async function runAssistantReplyHook(text: result.text,});} else if (result.action === 'render') {+ if (deps.isCurrent && !deps.isCurrent()) return;await deps.applyRenderCard(sessionId, clientId, {ghostId: result.ghostId,ghostName: result.ghostName,@@ -92,7 +100,11 @@ export async function runAssistantReplyHook(}// allow / 未知:不动那条消息。} finally {- deps.setPending(sessionId, clientId, false);+ // Do not emit an old owner's completion frame into the new owner's UI.+ const ownerStillCurrent = deps.isCurrent?.() ?? true;+ if (ownerStillCurrent) {+ deps.setPending(sessionId, clientId, false);+ }}} catch (err) {deps.log?.warn('assistant reply hook failed (fail-open)', {diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 2b4a274287..41c9cc0bdd 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -37,6 +37,7 @@ import type { PluginMarketPackageReview } from '../../shared/pluginMarket.js';import { getAppCapabilities } from '../appCapabilities.js';import {activeOwnerScopeKey,+ getActiveDataOwnerPushStamp,getActiveAppSession,isAppSessionBoundaryPending,ownerScopedUserDataPath,@@ -292,6 +293,10 @@ import {createLegacyGhostRecoveryIpcHandlers,} from './legacyGhostRecoveryIpc.js';import type { LegacyGhostRecoveryStatus } from '../../shared/legacyGhostRecovery.js';+import {+ isDataOwnerPushStamp,+ type DataOwnerPushStamp,+} from '../../shared/dataOwnerPush.js';/*** 意识仓库的进程级单例 + IPC 注册。@@ -309,6 +314,76 @@ import type { LegacyGhostRecoveryStatus } from '../../shared/legacyGhostRecoveryconst log = createLogger('brain');+/** Attach the main-owned data-owner boundary to ghost UI pushes. */+function getGhostOwnerPushStamp(): DataOwnerPushStamp | undefined {+ try {+ return getActiveDataOwnerPushStamp();+ } catch {+ // Tests and very early bootstrap may not have an app-session store yet.+ return undefined;+ }+}++function isSameGhostOwnerStamp(+ a: DataOwnerPushStamp,+ b: DataOwnerPushStamp,+): boolean {+ return a.dataOwnerId === b.dataOwnerId && a.ownerGeneration === b.ownerGeneration;+}++function isGhostOwnerStampCurrent(ownerStamp: DataOwnerPushStamp | undefined): boolean {+ if (ownerStamp === undefined) return true;+ const current = getGhostOwnerPushStamp();+ return current !== undefined && isSameGhostOwnerStamp(ownerStamp, current);+}++function sendGhostWindowPush(+ window: BrowserWindow,+ channel: string,+ payload: unknown,+ ownerStamp?: DataOwnerPushStamp,+): void {+ sendGhostContentsPush(window.webContents, channel, payload, ownerStamp);+}++function sendGhostContentsPush(+ contents: WebContents,+ channel: string,+ payload: unknown,+ ownerStamp?: DataOwnerPushStamp,+): void {+ if (ownerStamp !== undefined && !isGhostOwnerStampCurrent(ownerStamp)) return;+ const stamp = ownerStamp ?? getGhostOwnerPushStamp();+ // The initial pre-auth bootstrap has no meaningful boundary yet. Keep the+ // old Electron call shape there; every committed owner carries a stamp.+ if (stamp === undefined || (stamp.dataOwnerId === null && stamp.ownerGeneration === 0)) {+ contents.send(channel, payload);+ } else {+ contents.send(channel, payload, stamp);+ }+}++function broadcastGhostWindowPush(+ channel: string,+ payload: unknown,+ ownerStamp?: DataOwnerPushStamp,+): void {+ for (const window of BrowserWindow.getAllWindows()) {+ if (!window.isDestroyed()) sendGhostWindowPush(window, channel, payload, ownerStamp);+ }+}++function sendGhostTrustedWindowPush(+ channel: string,+ payload: unknown,+ ownerStamp?: DataOwnerPushStamp,+): void {+ for (const window of BrowserWindow.getAllWindows()) {+ if (window.isDestroyed() || !isTrustedAppRendererWindow(window)) continue;+ sendGhostWindowPush(window, channel, payload, ownerStamp);+ }+}+/*** 电子脑管子与 settingsHtml `/app-context` 共用,避免 region / locale 两条口径漂移。* dev 区域(第三系统身份,2026-07-20)对意识映射为 'cn':意识契约@@ -1073,10 +1148,7 @@ export function getGhostSessionActivityTracker(): GhostSessionActivityTracker {if (!sessionActivityTrackerSingleton) {sessionActivityTrackerSingleton = new GhostSessionActivityTracker({broadcast: (sessionId, busy) => {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_SESSION_ACTIVITY_CHANNEL, { sessionId, busy });- });+ broadcastGhostWindowPush(GHOST_SESSION_ACTIVITY_CHANNEL, { sessionId, busy });},log,});@@ -1100,10 +1172,7 @@ export function getGhostCardService(): GhostCardService {sanitize: sanitizeGhostCardHtml,persist: (row) => upsertGhostCard(row),broadcast: (payload) => {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_CARD_UPDATED_CHANNEL, payload);- });+ broadcastGhostWindowPush(GHOST_CARD_UPDATED_CHANNEL, payload);},// 重开态(card-action 后台干活)的供片驱动会话呼吸:working/未声明续期,// done 熄灭(TTL 兜底在跟踪器内)。@@ -1189,14 +1258,11 @@ export function getGhostSubscriptionGateway(): GhostSubscriptionGateway {}},now: () => Date.now(),- onHookFused: (ghost) => {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_HOOK_FUSED_CHANNEL, {- ghostId: ghost.manifest.id,- name: ghost.manifest.name,- });- });+ onHookFused: (ghost, ownerStamp) => {+ broadcastGhostWindowPush(GHOST_HOOK_FUSED_CHANNEL, {+ ghostId: ghost.manifest.id,+ name: ghost.manifest.name,+ }, isDataOwnerPushStamp(ownerStamp) ? ownerStamp : undefined);},log,});@@ -1474,13 +1540,18 @@ export async function screenGhostUserMessage(sessionId: string,text: string,): Promise<GhostScreenResult> {+ const ownerStamp = getGhostOwnerPushStamp();try {const hasHookGhost = availableGhosts().some((g) => g.enabled && g.manifest.subscribe?.hooks?.includes('will-user-message'));if (!hasHookGhost) return { action: 'allow' };// retry(DB 未就绪)也放行:拦截是尽力而为的旁路,fail-open 不挡发送。if ((await isGhostEligibleSession(sessionId)).outcome !== 'eligible') return { action: 'allow' };- return await getGhostSubscriptionGateway().screenUserMessage({ sessionId, text });+ const result = await getGhostSubscriptionGateway().screenUserMessage(+ { sessionId, text },+ ownerStamp,+ );+ return isGhostOwnerStampCurrent(ownerStamp) ? result : { action: 'allow' };} catch (err) {log.warn('ghost screen failed (fail-open)', {error: err instanceof Error ? err.message : String(err),@@ -1501,10 +1572,7 @@ export function broadcastGhostMessageBlocked(payload: {reason: string;text: string;}): void {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_MESSAGE_BLOCKED_CHANNEL, payload);- });+ broadcastGhostWindowPush(GHOST_MESSAGE_BLOCKED_CHANNEL, payload);}/** 改写通知广播(register.ts 的 onUserMessageRewritten 依赖真身)。@@ -1519,10 +1587,7 @@ export function broadcastGhostMessageRewritten(payload: {text: string;originalText: string;}): void {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_MESSAGE_REWRITTEN_CHANNEL, payload);- });+ broadcastGhostWindowPush(GHOST_MESSAGE_REWRITTEN_CHANNEL, payload);}/** 是否有启用的意识声明了 will-assistant-message(出口钩子快路径同步守卫)。 */@@ -1538,19 +1603,22 @@ function broadcastGhostAssistantRewritten(payload: {ghostId: string;ghostName: string;text: string;-}): void {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_ASSISTANT_REWRITTEN_CHANNEL, payload);- });+}, ownerStamp?: DataOwnerPushStamp): void {+ broadcastGhostWindowPush(GHOST_ASSISTANT_REWRITTEN_CHANNEL, payload, ownerStamp);}/** 广播:出口钩子后台处理中/完成的轻指示。 */-function broadcastGhostAssistantPending(sessionId: string, clientId: string, pending: boolean): void {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_ASSISTANT_PENDING_CHANNEL, { sessionId, clientId, pending });- });+function broadcastGhostAssistantPending(+ sessionId: string,+ clientId: string,+ pending: boolean,+ ownerStamp?: DataOwnerPushStamp,+): void {+ broadcastGhostWindowPush(+ GHOST_ASSISTANT_PENDING_CHANNEL,+ { sessionId, clientId, pending },+ ownerStamp,+ );}/**@@ -1562,7 +1630,9 @@ async function applyGhostAssistantRenderCard(sessionId: string,clientId: string,card: { ghostId: string; ghostName: string; html: string; height?: number },+ ownerStamp?: DataOwnerPushStamp,): Promise<void> {+ if (ownerStamp !== undefined && !isGhostOwnerStampCurrent(ownerStamp)) return;const sanitized = sanitizeGhostCardHtml(card.html);if (!sanitized.ok) {log.warn('ghost assistant render card rejected by sanitizer', { sessionId, reason: sanitized.reason });@@ -1589,9 +1659,10 @@ async function applyGhostAssistantRenderCard(error: err instanceof Error ? err.message : String(err),});});- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_CARD_UPDATED_CHANNEL, {+ if (ownerStamp !== undefined && !isGhostOwnerStampCurrent(ownerStamp)) return;+ broadcastGhostWindowPush(+ GHOST_CARD_UPDATED_CHANNEL,+ {callId: clientId,ghostId: card.ghostId,toolUseId: null,@@ -1603,8 +1674,9 @@ async function applyGhostAssistantRenderCard(// clientId 直取),**不进 liveCards 锚定池**——否则 toolUseId:null 的条目会// 被同意识进行中 ghost_call 的启发式锚定抢走(review P1,2026-07-13)。turnCard: true,- });- });+ },+ ownerStamp,+ );}/**@@ -1614,17 +1686,31 @@ async function applyGhostAssistantRenderCard(* clientId = 本轮 assistant 消息持久化 id(consumeLastAssistantPersistId 取得)。*/export function runGhostAssistantReplyHook(sessionId: string, clientId: string, text: string): void {+ const ownerStamp = getGhostOwnerPushStamp();+ const isCurrent = () => isGhostOwnerStampCurrent(ownerStamp);void runAssistantReplyHook({+ isCurrent,hasHook: hasEnabledGhostAssistantHook,- isEligible: async (sid) => (await isGhostEligibleSession(sid)).outcome === 'eligible',- screen: (sid, t) => getGhostSubscriptionGateway().screenAssistantMessage({ sessionId: sid, text: t }),+ isEligible: async (sid) => isCurrent() && (await isGhostEligibleSession(sid)).outcome === 'eligible',+ screen: async (sid, t) => {+ if (!isCurrent()) return { action: 'allow' as const };+ const result = await getGhostSubscriptionGateway().screenAssistantMessage(+ { sessionId: sid, text: t },+ ownerStamp,+ );+ return isCurrent() ? result : { action: 'allow' as const };+ },persistRewrite: async (sid, cid, t) => {+ if (!isCurrent()) return;await updateMessageContent(sid, cid, t);},- applyRenderCard: (sid, cid, cardArg) => applyGhostAssistantRenderCard(sid, cid, cardArg),- broadcastRewritten: broadcastGhostAssistantRewritten,- setPending: broadcastGhostAssistantPending,+ applyRenderCard: (sid, cid, cardArg) =>+ applyGhostAssistantRenderCard(sid, cid, cardArg, ownerStamp),+ broadcastRewritten: (payload) =>+ broadcastGhostAssistantRewritten(payload, ownerStamp),+ setPending: (sid, cid, pending) =>+ broadcastGhostAssistantPending(sid, cid, pending, ownerStamp),log,},sessionId,@@ -1811,10 +1897,7 @@ export function broadcastGhostHostNotice(textKey: notice.textKey,...(textArgs ? { textArgs } : {}),};- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_NOTIFY_CHANNEL, payload);- });+ broadcastGhostWindowPush(GHOST_NOTIFY_CHANNEL, payload);log.info('ghost host notice shown', { ghostId, textKey: notice.textKey });}@@ -1827,10 +1910,7 @@ export function getGhostNotifySlot(): GhostNotifySlot {notifySlotSingleton = new GhostNotifySlot({getGhost: findAvailableGhost,broadcast: (payload) => {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send(GHOST_NOTIFY_CHANNEL, payload);- });+ broadcastGhostWindowPush(GHOST_NOTIFY_CHANNEL, payload);},log,});@@ -1859,11 +1939,7 @@ export const GHOST_UNREAD_SNAPSHOT_CHANNEL = 'ghosts:unread-snapshot';* 判据复用 `isTrustedAppRendererWindow`,与 `ghosts:unread` 同步读那道闸同源。*/function sendToTrustedAppWindows(channel: string, payload: unknown): void {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- if (!isTrustedAppRendererWindow(window)) return;- window.webContents.send(channel, payload);- });+ sendGhostTrustedWindowPush(channel, payload);}function broadcastGhostBadge(payload: { ghostId: string; unread: boolean; summary?: string; at?: number }): void {@@ -2042,7 +2118,7 @@ export function getGhostConfirmSlot(): GhostConfirmSlot {sendToWindow: (payload) => {const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0];if (!win || win.isDestroyed()) return false;- win.webContents.send(GHOST_CONFIRM_CHANNEL, payload);+ sendGhostWindowPush(win, GHOST_CONFIRM_CHANNEL, payload);return true;},log,@@ -2200,7 +2276,7 @@ export function getGhostPreviewSlot(): GhostPreviewSlot {broadcast: (payload) => {const windows = BrowserWindow.getAllWindows().filter((window) => !window.isDestroyed());windows.forEach((window) => {- window.webContents.send(GHOST_PREVIEW_OPEN_CHANNEL, payload);+ sendGhostWindowPush(window, GHOST_PREVIEW_OPEN_CHANNEL, payload);});return windows.length > 0;},@@ -4945,7 +5021,11 @@ export function handleGhostPreviewNavigation(return;}if (hostContents.isDestroyed()) return;- hostContents.send(GHOST_PREVIEW_MEDIA_CHANNEL, { ghostId, src: outcome.src, kind: outcome.kind });+ sendGhostContentsPush(hostContents, GHOST_PREVIEW_MEDIA_CHANNEL, {+ ghostId,+ src: outcome.src,+ kind: outcome.kind,+ });}).catch((err) => {log.warn('ghost preview failed', {@@ -5027,10 +5107,7 @@ export function resolveGhostWebviewAttach(partition: unknown, src: unknown): Ins/** 播种进行中提示广播(renderer 显示/收起非阻塞胶囊;与退出 overlay 同款视觉)。 */function broadcastGhostProvisioning(active: boolean): void {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send('ghosts:provisioning', { active });- });+ broadcastGhostWindowPush('ghosts:provisioning', { active });}/**@@ -5058,10 +5135,7 @@ function broadcastGhostsChanged(const visible = ghosts.filter((ghost) => isGhostAvailableForActiveSession(ghost.manifest.id)).map(projectGhostForRenderer);- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send('ghosts:changed', { ghosts: visible });- });+ broadcastGhostWindowPush('ghosts:changed', { ghosts: visible });// 与 renderer 同一份可见清单喂给观察者(独立窗口 controller reconcile 等);// 观察者异常不拖垮广播本体。if (ghostsChangedObserver) {@@ -5149,17 +5223,11 @@ export function refreshGhostLocalization(): void {/** Plugin 顶部快捷行的 host-owned MRU 快照,多窗口同步。 */function broadcastGhostRecentUsageChanged(ids: string[]): void {- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send('ghosts:recent-usage-changed', { ids });- });+ broadcastGhostWindowPush('ghosts:recent-usage-changed', { ids });}/** 运行时状态广播(→ 意识面板的错误接管态:crashed / fused 原地显示)。 */function broadcastGhostRuntimeStates(): void {const states = runtimeSingleton?.listStates() ?? {};- BrowserWindow.getAllWindows().forEach((window) => {- if (window.isDestroyed()) return;- window.webContents.send('ghosts:runtime-changed', { states });- });+ broadcastGhostWindowPush('ghosts:runtime-changed', { states });}diff --git a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts b/apps/desktop/src/main/cindy-brain/subscriptionGateway.tsindex 1e3b4f46c1..c42f59b01c 100644--- a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts+++ b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts@@ -85,7 +85,7 @@ export interface GhostSubscriptionGatewayDeps {sendToGhost(ghostId: string, payload: GhostPipeEventPush): void;now(): number;/** 钩子熔断回调(通知 renderer + 日志;每意识只触发一次)。 */- onHookFused?(ghost: InstalledGhost): void;+ onHookFused?(ghost: InstalledGhost, ownerStamp?: unknown): void;/** hookId 生成(测试注入固定序列;缺省 randomUUID)。 */newHookId?(): string;log?: {@@ -228,7 +228,10 @@ export class GhostSubscriptionGateway {* (currentText 累积)。block 即短路返回;任何异常都不外抛——本方法在发送* 热路径上,只能收敛为 allow / 累积 rewrite。*/- async screenUserMessage(input: { sessionId: string; text: string }): Promise<GhostScreenResult> {+ async screenUserMessage(+ input: { sessionId: string; text: string },+ ownerStamp?: unknown,+ ): Promise<GhostScreenResult> {let currentText = input.text;let rewritten = false;let lastRewriteGhost: InstalledGhost | null = null;@@ -242,7 +245,7 @@ export class GhostSubscriptionGateway {const verdict = await this.askOne(ghost, e, 'will-user-message', {sessionId: input.sessionId,text: currentText,- });+ }, ownerStamp);if (verdict?.action === 'block') {const reason = (verdict.reason ?? '').slice(0, BLOCK_REASON_MAX_CHARS);this.deps.log?.info('ghost hook blocked user message', { ghostId, sessionId: input.sessionId });@@ -281,10 +284,10 @@ export class GhostSubscriptionGateway {* (无 rewrite 即等于 AI 原文)。本方法在 turn 结束的独立续跑里跑,异常绝不* 外抛,只收敛为 allow / rewrite / render。*/- async screenAssistantMessage(input: {- sessionId: string;- text: string;- }): Promise<GhostAssistantScreenResult> {+ async screenAssistantMessage(+ input: { sessionId: string; text: string },+ ownerStamp?: unknown,+ ): Promise<GhostAssistantScreenResult> {let currentText = input.text;let lastRewriteGhost: InstalledGhost | null = null;let renderGhost: InstalledGhost | null = null;@@ -300,7 +303,7 @@ export class GhostSubscriptionGateway {const verdict = await this.askOne(ghost, e, 'will-assistant-message', {sessionId: input.sessionId,text: currentText,- });+ }, ownerStamp);if (verdict?.action === 'rewrite' && typeof verdict.text === 'string') {const next = verdict.text.slice(0, GHOST_HOOK_REWRITE_MAX_CHARS).trim();// 空改写(意识把正文清空)视为无意义,忽略此次 rewrite 保原文。@@ -351,6 +354,7 @@ export class GhostSubscriptionGateway {e: SubEntry,hookName: 'will-user-message' | 'will-assistant-message',input: { sessionId: string; text: string },+ ownerStamp?: unknown,): Promise<HookVerdict | null> {const ghostId = ghost.manifest.id;const hookId = this.deps.newHookId?.() ?? randomUUID();@@ -389,14 +393,19 @@ export class GhostSubscriptionGateway {const verdict = await verdictPromise;clearTimeout(timer);if (verdict === null) {- this.noteHookFailure(ghost, e, deliverFailure ?? 'timeout');+ this.noteHookFailure(ghost, e, deliverFailure ?? 'timeout', ownerStamp);return null;}e.hookFails = 0;return verdict;}- private noteHookFailure(ghost: InstalledGhost, e: SubEntry, why: string): void {+ private noteHookFailure(+ ghost: InstalledGhost,+ e: SubEntry,+ why: string,+ ownerStamp?: unknown,+ ): void {e.hookFails += 1;this.deps.log?.warn('ghost hook failed (fail-open)', {ghostId: ghost.manifest.id,@@ -408,7 +417,7 @@ export class GhostSubscriptionGateway {this.deps.log?.warn('ghost hook fused: degraded to observe-only', {ghostId: ghost.manifest.id,});- this.deps.onHookFused?.(ghost);+ this.deps.onHookFused?.(ghost, ownerStamp);}}diff --git a/apps/desktop/src/main/cindy-media/chatAttachments.ts b/apps/desktop/src/main/cindy-media/chatAttachments.tsindex d0fbb052a7..0dae644df1 100644--- a/apps/desktop/src/main/cindy-media/chatAttachments.ts+++ b/apps/desktop/src/main/cindy-media/chatAttachments.ts@@ -108,6 +108,15 @@ export function collectCindyMediaUrls(value: unknown): string[] {return [...new Set(serialized.match(CINDY_BLOB_URL_RE) ?? [])];}+/** Return validated blob hashes referenced by a message payload. */+export function collectCindyMediaHashes(value: unknown): string[] {+ return [...new Set(+ collectCindyMediaUrls(value)+ .map((url) => blobStore.parseBlobUrl(url)?.hash)+ .filter((hash): hash is string => typeof hash === 'string'),+ )];+}+/*** 发送时提交:给消息里的每个 blob 挂 session-attachment 引用(幂等——同* 会话同指纹已有引用则跳过,重发/插话不刷重复行)。形状不合法的 URL 跳过。diff --git a/apps/desktop/src/main/cindy-media/ledger.ts b/apps/desktop/src/main/cindy-media/ledger.tsindex 4ad0073559..b64393138e 100644--- a/apps/desktop/src/main/cindy-media/ledger.ts+++ b/apps/desktop/src/main/cindy-media/ledger.ts@@ -305,6 +305,37 @@ export async function removeRefs(return result.changes;}+/**+ * Remove one session-attachment ref only when no live message in that session+ * still contains the blob hash. The predicate is part of the DELETE so a+ * concurrent message commit cannot turn a read-then-delete check into data+ * loss; at worst a later commit recreates the coarse session ref.+ */+export async function removeSessionAttachmentRefIfUnreferencedByLiveMessage(+ params: { sessionId: string; hash: string },+ db: LedgerDb = defaultDb(),+): Promise<number> {+ if (!/^[0-9a-f]{64}$/.test(params.hash)) return 0;+ const result = await db+ .delete(mediaRefs)+ .where(+ and(+ eq(mediaRefs.refKind, 'session-attachment'),+ eq(mediaRefs.refId, params.sessionId),+ eq(mediaRefs.hash, params.hash),+ sql`NOT EXISTS (+ SELECT 1+ FROM messages+ WHERE messages.session_id = ${params.sessionId}+ AND messages.rewind_at IS NULL+ AND messages.content LIKE ${`%${params.hash}%`}+ )`,+ ),+ )+ .run();+ return result.changes;+}+/*** 意识面板供图归属校验:该指纹「出生自本意识」「挂在本意识画廊」「用户* 显式引渡给本意识(ghost-grant)」「Host 代办交接给本意识diff --git a/apps/desktop/src/main/device-link/broadcast-tap.ts b/apps/desktop/src/main/device-link/broadcast-tap.tsindex 70956a24c9..d2bd063ed0 100644--- a/apps/desktop/src/main/device-link/broadcast-tap.ts+++ b/apps/desktop/src/main/device-link/broadcast-tap.ts@@ -9,20 +9,101 @@*/import { PUSH_FORWARD_ALLOWLIST } from '@cindy/device-link';+import {+ activeOwnerScopeKey,+ getActiveDataOwnerPushStamp,+ isAppSessionBoundaryPending,+} from '../appSessionState.js';+import type { DataOwnerPushStamp } from '../../shared/dataOwnerPush.js';-/** 转发回调:(channel, payload) → 投递给所有 active 控制端 */-export type BroadcastTapListener = (channel: string, payload: unknown) => void;+/** Snapshot carried by async main-side work across an owner boundary. */+export interface DataOwnerBroadcastScope {+ readonly ownerScopeKey?: string;+ readonly ownerStamp?: DataOwnerPushStamp;+}++/** 转发回调:(channel, payload, ownerStamp) → 投递给所有 active 控制端 */+export type BroadcastTapListener = (+ channel: string,+ payload: unknown,+ ownerStamp?: DataOwnerPushStamp,+) => void;let listener: BroadcastTapListener | null = null;+/** Read the main owner stamp without making small Electron-free tests boot app storage. */+export function getSafeDataOwnerPushStamp(): DataOwnerPushStamp | undefined {+ try {+ const stamp = getActiveDataOwnerPushStamp();+ // Keep the pre-auth/test bootstrap path wire-compatible. Once the main+ // process has crossed its first owner boundary, even signed-out frames+ // carry the generation so a late old-owner frame cannot be relabeled.+ if (stamp.dataOwnerId === null && stamp.ownerGeneration === 0) return undefined;+ return stamp;+ } catch {+ return undefined;+ }+}++/** Capture both the renderer/device-link stamp and the stronger main owner key. */+export function captureDataOwnerBroadcastScope(): DataOwnerBroadcastScope {+ let ownerScopeKey: string | undefined;+ try {+ ownerScopeKey = activeOwnerScopeKey();+ } catch {+ // Electron-free unit tests and pre-bootstrap callers have no app storage yet.+ }+ return {+ ...(ownerScopeKey !== undefined ? { ownerScopeKey } : {}),+ ownerStamp: getSafeDataOwnerPushStamp(),+ };+}++/** Fail closed when async work settles after an owner switch or teardown began. */+export function isDataOwnerBroadcastScopeCurrent(scope: DataOwnerBroadcastScope): boolean {+ if (scope.ownerScopeKey !== undefined) {+ try {+ return !isAppSessionBoundaryPending() && activeOwnerScopeKey() === scope.ownerScopeKey;+ } catch {+ return false;+ }+ }+ // Legacy/bootstrap callers have no scope key. Preserve their old behavior while+ // still rejecting a late stamped frame if the owner boundary became observable.+ const current = getSafeDataOwnerPushStamp();+ return (+ current?.dataOwnerId === scope.ownerStamp?.dataOwnerId &&+ current?.ownerGeneration === scope.ownerStamp?.ownerGeneration+ );+}+/*** 旁路一份 renderer 广播给 device-link。无 listener(无控制链路)时立即返回,* 不做任何字符串比较以外的工作——保证对本地广播热路径零额外开销。*/-export function tapWindowBroadcast(channel: string, payload: unknown): void {+export function tapWindowBroadcast(+ channel: string,+ payload: unknown,+ ownerStamp?: DataOwnerPushStamp,+): void {if (listener === null) return;if (!PUSH_FORWARD_ALLOWLIST.has(channel)) return;- listener(channel, payload);+ // `undefined` is a valid captured value during bootstrap/tests. Preserve+ // the distinction between an omitted third argument (legacy call sites,+ // read the current stamp) and an explicitly captured `undefined` (do not+ // relabel an async event with a newer owner). Callers carrying an owner+ // scope should always pass the third argument, even when it is undefined.+ const hasCapturedStamp = arguments.length >= 3;+ let stamp = ownerStamp;+ if (!hasCapturedStamp) {+ // Keep the pure device-link dispatch tests (which intentionally mock only a+ // small Electron surface) independent from app-session storage. Production+ // always has a loaded app session here; the fallback is only a compatibility+ // stamp for legacy/test callers and is rejected by a stamped peer boundary.+ stamp = getSafeDataOwnerPushStamp();+ }+ if (stamp === undefined) listener(channel, payload);+ else listener(channel, payload, stamp);}/** dispatch.ts 在首个控制链路建立时注册;最后一个链路关闭时传 null 注销。 */diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex fd9882010d..3270a7de1d 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -44,6 +44,7 @@ import {type InvokeResultPayload,type LinkClosePayload,type LinkOpenPayload,+ type PushOwnerStamp,type Topic,} from '@cindy/device-link';import {@@ -68,7 +69,10 @@ import { transcribeRemoteVoiceInput } from './voiceTranscribe';import { readTelegramRemoteStatus, setTelegramRemoteOnline } from './telegramRemoteControl';import { adviseAndRecordVoiceInputDictionaryLearning } from '../voice-input/index.js';import { readDictionaryProjectionForMobile } from '../voice-input/dictionarySyncDriver.js';-import { setBroadcastTapListener } from './broadcast-tap';+import {+ setBroadcastTapListener,+} from './broadcast-tap';+import * as broadcastTap from './broadcast-tap';import { createOfflinePushQueue } from './offlinePushQueue';import * as subscriptions from './subscriptions';import { LEGACY_TOPIC, type ActiveController } from './subscriptions';@@ -572,8 +576,8 @@ const SESSION_ACTIVITY_DRAIN_RETRY_MS = 250;const SESSION_ACTIVITY_WINDOW_SOFT_CAP = 32;interface SessionActivityStage {- /** sessionId → 最新 payload;Map 插入序即更新序,超限时淘汰最旧键。 */- queue: Map<string, unknown>;+ /** sessionId → 最新 payload + source owner;Map 插入序即更新序。 */+ queue: Map<string, { payload: unknown; ownerStamp?: PushOwnerStamp }>;retryTimer: ReturnType<typeof setTimeout> | null;}const sessionActivityStages = new Map<string, SessionActivityStage>();@@ -584,7 +588,11 @@ function sessionActivityKey(payload: unknown): string | null {return typeof sessionId === 'string' && sessionId ? sessionId : null;}-function stageSessionActivityPush(dst: string, payload: unknown): void {+function stageSessionActivityPush(+ dst: string,+ payload: unknown,+ ownerStamp?: PushOwnerStamp,+): void {const key = sessionActivityKey(payload);// 无 sessionId 的活动帧无法键控(契约上不存在);丢弃而不是绕行,避免未知// 形状绕过整流重新制造窗口竞争。@@ -595,7 +603,7 @@ function stageSessionActivityPush(dst: string, payload: unknown): void {sessionActivityStages.set(dst, stage);}stage.queue.delete(key);- stage.queue.set(key, payload);+ stage.queue.set(key, { payload, ...(ownerStamp ? { ownerStamp } : {}) });while (stage.queue.size > SESSION_ACTIVITY_STAGE_MAX_KEYS) {const oldest = stage.queue.keys().next().value as string | undefined;if (oldest === undefined) break;@@ -624,11 +632,17 @@ function drainSessionActivityStage(dst: string, stage: SessionActivityStage): voscheduleSessionActivityRetry(dst, stage);return;}- const next = stage.queue.entries().next().value as [string, unknown] | undefined;+ const next = stage.queue.entries().next().value as+ | [string, { payload: unknown; ownerStamp?: PushOwnerStamp }]+ | undefined;if (!next) return;- const [key, payload] = next;+ const [key, item] = next;try {- activeClient.sendPush(dst, SESSION_ACTIVITY_CHANNEL, payload);+ if (item.ownerStamp === undefined) {+ activeClient.sendPush(dst, SESSION_ACTIVITY_CHANNEL, item.payload);+ } else {+ activeClient.sendPush(dst, SESSION_ACTIVITY_CHANNEL, item.payload, item.ownerStamp);+ }stage.queue.delete(key);} catch (err) {if (err instanceof DeviceLinkError && err.code === 'BACKPRESSURE') {@@ -675,14 +689,14 @@ export function pushSessionActivityToController(): void {if (!activeClient) return;if (!subscriptions.getControllersForTopic('sessions').includes(controllerDeviceId)) return;- stageSessionActivityPush(controllerDeviceId, payload);+ stageSessionActivityPush(controllerDeviceId, payload, broadcastTap.getSafeDataOwnerPushStamp?.());}/*** 按 topic 把一条本机广播转发给订阅了它的控制端。listener 注册后每条 tap 都过这里* (live 读 registry,topic 变化即时生效)。topic 算不出(无 session 标识)→ 丢弃。*/-function forwardPush(channel: string, payload: unknown): void {+function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerStamp): void {if (!activeClient) return;const topic = topicForPush(channel, payload);if (!topic) return;@@ -714,19 +728,20 @@ function forwardPush(channel: string, payload: unknown): void {channel,payload: remotePayload,topic,+ ...(ownerStamp ? { ownerStamp } : {}),});}}for (const dst of liveTargets) {// 会话活动是高频状态镜像:走 latest-wins 暂存整流,不直接冲可靠传输窗口。if (channel === SESSION_ACTIVITY_CHANNEL) {- stageSessionActivityPush(dst, remotePayload);+ stageSessionActivityPush(dst, remotePayload, ownerStamp);continue;}// 转发是尽力而为的旁路:单个控制端的帧超限(PAYLOAD_TOO_LARGE,如大 tool 输出)/ 连接异常// 绝不能冒泡——它会经 tapWindowBroadcast 回到 broadcastToAllWindows,让被控端**本机** renderer// 漏收该事件(本地 UI 是第一优先);per-dst 接住也避免一个控制端坏帧拖垮其它控制端的转发。- sendPushBestEffort(dst, channel, remotePayload);+ sendPushBestEffort(dst, channel, remotePayload, ownerStamp);}}@@ -736,14 +751,24 @@ function forwardPush(channel: string, payload: unknown): void {* 引擎产生,不是 renderer 广播)。路由与 tap 路径同一 forwardPush,scoped 到* 订阅者;无 active client / 无订阅者时 no-op。*/-export function pushToTopicSubscribers(channel: string, payload: unknown): void {- forwardPush(channel, payload);+export function pushToTopicSubscribers(+ channel: string,+ payload: unknown,+ ownerStamp?: PushOwnerStamp,+): void {+ forwardPush(channel, payload, ownerStamp);}-function sendPushBestEffort(dst: string, channel: string, payload: unknown): void {+function sendPushBestEffort(+ dst: string,+ channel: string,+ payload: unknown,+ ownerStamp?: PushOwnerStamp,+): void {if (!activeClient) return;try {- activeClient.sendPush(dst, channel, payload);+ if (ownerStamp === undefined) activeClient.sendPush(dst, channel, payload);+ else activeClient.sendPush(dst, channel, payload, ownerStamp);return;} catch (err) {if (!isPayloadTooLargeError(err)) {@@ -758,7 +783,8 @@ function sendPushBestEffort(dst: string, channel: string, payload: unknown): voi}try {- activeClient.sendPush(dst, channel, compactPayload);+ if (ownerStamp === undefined) activeClient.sendPush(dst, channel, compactPayload);+ else activeClient.sendPush(dst, channel, compactPayload, ownerStamp);log.warn(`forwardPush to ${shortId(dst)} sent compact payload after oversized ${channel} frame`);} catch (retryErr) {log.warn(@@ -1093,7 +1119,7 @@ function handleLinkOpen(flushRemoteInvokeResultOutbox(src);if (!knownModernController) {for (const queued of offlinePushQueue.drain(src, [LEGACY_TOPIC])) {- sendPushBestEffort(src, queued.channel, queued.payload);+ sendPushBestEffort(src, queued.channel, queued.payload, queued.ownerStamp);}}log.info(`control link opened by ${shortId(src)} (${name})`);@@ -1975,7 +2001,7 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeRes}if (isSub && topics.length > 0) {for (const queued of offlinePushQueue.drain(src, topics)) {- sendPushBestEffort(src, queued.channel, queued.payload);+ sendPushBestEffort(src, queued.channel, queued.payload, queued.ownerStamp);}}return { ok: true, result: { ok: true } };diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 84724e1c70..19c8a86a08 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -34,6 +34,7 @@ import {INVOKE_TIMEOUT_OVERRIDES_MS,} from '@cindy/device-link';import * as authManager from '../authManager';+import { getActiveDataOwnerPushStamp } from '../appSessionState.js';import { createLogger } from '../logger';import { onQuit } from '../lifecycle';import { tryGetDbClient } from '../localDb/client/current';@@ -623,6 +624,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): vdeviceId: env.src,channel: p.channel,payload: p.payload,+ ...(p.ownerStamp ? { ownerStamp: p.ownerStamp } : {}),});});@@ -1572,10 +1574,12 @@ export function sendMobileSessionNotify(payload: {}export function broadcast(channel: string, payload: unknown): void {+ const ownerStamp = getActiveDataOwnerPushStamp();for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;try {- win.webContents.send(channel, payload);+ if (ownerStamp === undefined) win.webContents.send(channel, payload);+ else win.webContents.send(channel, payload, ownerStamp);} catch (err) {log.warn(`broadcast '${channel}' failed (non-fatal)`, err);}diff --git a/apps/desktop/src/main/device-link/offlinePushQueue.ts b/apps/desktop/src/main/device-link/offlinePushQueue.tsindex 058d81dd0c..aa1f749a67 100644--- a/apps/desktop/src/main/device-link/offlinePushQueue.ts+++ b/apps/desktop/src/main/device-link/offlinePushQueue.ts@@ -3,6 +3,8 @@ export interface OfflinePushQueueItem {payload: unknown;/** The topic that controls whether this item may be replayed. */topic: string;+ /** Source app-session boundary for late-frame ingress fencing. */+ ownerStamp?: { dataOwnerId: string | null; ownerGeneration: number };}interface QueuedPush extends OfflinePushQueueItem {@@ -99,17 +101,32 @@ export function createOfflinePushQueue(options: OfflinePushQueueOptions = {}): Oconst queue = prune(deviceId);if (!topics || topics.includes(LEGACY_TOPIC)) {byDevice.delete(deviceId);- return queue.map(({ channel, payload, topic }) => ({ channel, payload, topic }));+ return queue.map(({ channel, payload, topic, ownerStamp }) => ({+ channel,+ payload,+ topic,+ ...(ownerStamp ? { ownerStamp } : {}),+ }));}const allowed = new Set(topics);const selected = queue.filter((item) => allowed.has(item.topic));const remaining = queue.filter((item) => !allowed.has(item.topic));if (remaining.length > 0) byDevice.set(deviceId, remaining);else byDevice.delete(deviceId);- return selected.map(({ channel, payload, topic }) => ({ channel, payload, topic }));+ return selected.map(({ channel, payload, topic, ownerStamp }) => ({+ channel,+ payload,+ topic,+ ...(ownerStamp ? { ownerStamp } : {}),+ }));},snapshot(deviceId): OfflinePushQueueItem[] {- return prune(deviceId).map(({ channel, payload, topic }) => ({ channel, payload, topic }));+ return prune(deviceId).map(({ channel, payload, topic, ownerStamp }) => ({+ channel,+ payload,+ topic,+ ...(ownerStamp ? { ownerStamp } : {}),+ }));},clear(deviceId): void {if (deviceId) byDevice.delete(deviceId);diff --git a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.tsindex 8aee5659b9..379f8cdd30 100644--- a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts+++ b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts@@ -15,14 +15,26 @@ import path from 'node:path';import { gzipSync, gunzipSync } from 'node:zlib';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ WorkdirWatchManager,+ type RemoteFileTreeEvent,+} from '@cindy/remote-file-service';+import { FILE_BROWSER_EVENT_CHANNEL } from '@cindy/device-link';import type { RemoteWorkingDirCheckResult } from '../../device-link/remote-workdir-guard.js';const pushSpy = vi.fn();+const ownerStampState = vi.hoisted(() => ({+ current: { dataOwnerId: 'owner-a', ownerGeneration: 7 },+}));const guardMock = vi.fn<(dir: string) => Promise<RemoteWorkingDirCheckResult>>(async () => ({allowed: true,source: 'filesystem',}));const sshRequestMock = vi.fn();+const sshListenerState = vi.hoisted(() => ({+ hostEventHandlers: [] as Array<(event: unknown) => void>,+ hostConnectedHandlers: [] as Array<() => void>,+}));const dbRowsMock = vi.fn((): Array<{ remoteHostId: string | null }> => []);const dbWhereMock = vi.fn(async (_condition: unknown) => dbRowsMock());@@ -53,8 +65,12 @@ vi.mock('../../device-link/remote-workdir-guard.js', async (importOriginal) => {checkRemoteWorkingDir: (dir: string) => guardMock(dir),};});+vi.mock('../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: () => ownerStampState.current,+}));vi.mock('../../device-link/dispatch.js', () => ({- pushToTopicSubscribers: (channel: string, payload: unknown) => pushSpy(channel, payload),+ pushToTopicSubscribers: (channel: string, payload: unknown, ownerStamp?: unknown) =>+ pushSpy(channel, payload, ownerStamp),}));vi.mock('../../device-link/subscriptions.js', () => ({setTopicsSubscribedListener: vi.fn(),@@ -83,8 +99,20 @@ vi.mock('../../maker-host/runtime-configs.js', () => ({vi.mock('../remote-deps.js', () => ({getRemoteFileBrowser: () => ({request: sshRequestMock,- onHostEvent: vi.fn(() => () => {}),- onHostConnected: vi.fn(() => () => {}),+ onHostEvent: vi.fn((_hostId: string, cb: (event: unknown) => void) => {+ sshListenerState.hostEventHandlers.push(cb);+ return () => {+ const index = sshListenerState.hostEventHandlers.indexOf(cb);+ if (index >= 0) sshListenerState.hostEventHandlers.splice(index, 1);+ };+ }),+ onHostConnected: vi.fn((_hostId: string, cb: () => void) => {+ sshListenerState.hostConnectedHandlers.push(cb);+ return () => {+ const index = sshListenerState.hostConnectedHandlers.indexOf(cb);+ if (index >= 0) sshListenerState.hostConnectedHandlers.splice(index, 1);+ };+ }),}),}));@@ -97,6 +125,9 @@ describe('file-browser device-op', () => {beforeEach(async () => {vi.clearAllMocks();+ ownerStampState.current = { dataOwnerId: 'owner-a', ownerGeneration: 7 };+ sshListenerState.hostEventHandlers.length = 0;+ sshListenerState.hostConnectedHandlers.length = 0;guardMock.mockResolvedValue({ allowed: true, source: 'filesystem' });dbRowsMock.mockReturnValue([]);workdir = await mkdtemp(path.join(os.tmpdir(), 'device-op-'));@@ -341,6 +372,7 @@ describe('file-browser device-op', () => {it('watch: subscribe starts local watch and pushes fileTree events to topic subscribers', async () => {await onFsWatchSubscribed(workdir);await new Promise((r) => setTimeout(r, 100));+ ownerStampState.current = { dataOwnerId: 'owner-b', ownerGeneration: 8 };await fsWriteFile(path.join(workdir, 'src', 'watched.ts'), 'w\n', 'utf8');await vi.waitFor(() => {@@ -353,10 +385,11 @@ describe('file-browser device-op', () => {},{ timeout: 3000, interval: 50 },);- const [, payload] = pushSpy.mock.calls.find(+ const [, payload, ownerStamp] = pushSpy.mock.calls.find(([, p]) => (p as { relPath?: string }).relPath === 'src/watched.ts',)!;expect((payload as { workdir: string }).workdir).toBe(workdir);+ expect(ownerStamp).toEqual({ dataOwnerId: 'owner-a', ownerGeneration: 7 });onFsWatchReleased(workdir);});@@ -495,6 +528,275 @@ describe('file-browser device-op', () => {onFsWatchReleased(sshWorkdir);});+ it('watch: owner change during local start discards stale owner and rebuilds', async () => {+ let resolveFirstStart!: () => void;+ const firstStart = new Promise<void>((resolve) => {+ resolveFirstStart = resolve;+ });+ const managers: WorkdirWatchManager[] = [];+ const startSpy = vi+ .spyOn(WorkdirWatchManager.prototype, 'start')+ .mockImplementation(function (this: WorkdirWatchManager) {+ managers.push(this);+ return managers.length === 1 ? firstStart : Promise.resolve();+ });+ const stopSpy = vi+ .spyOn(WorkdirWatchManager.prototype, 'stop')+ .mockImplementation(() => undefined);++ try {+ const starting = onFsWatchSubscribed(workdir);+ await vi.waitFor(() => {+ expect(startSpy).toHaveBeenCalledTimes(1);+ });++ ownerStampState.current = { dataOwnerId: 'owner-b', ownerGeneration: 8 };+ resolveFirstStart();+ await starting;++ await vi.waitFor(() => {+ expect(startSpy).toHaveBeenCalledTimes(2);+ });+ expect(managers[1]).not.toBe(managers[0]);+ expect(stopSpy.mock.instances).toContain(managers[0]);++ const event: RemoteFileTreeEvent = {+ workdir,+ type: 'change',+ relPath: 'src/owner-b.ts',+ };+ (managers[1] as unknown as { emit: (value: RemoteFileTreeEvent) => void }).emit(event);+ expect(pushSpy).toHaveBeenCalledWith(+ FILE_BROWSER_EVENT_CHANNEL,+ event,+ { dataOwnerId: 'owner-b', ownerGeneration: 8 },+ );+ } finally {+ onFsWatchReleased(workdir);+ startSpy.mockRestore();+ stopSpy.mockRestore();+ }+ });++ it('watch: owner change during SSH start discards stale owner and rebuilds', async () => {+ const sshWorkdir = '/remote/home/user/owner-race-watch';+ guardMock.mockResolvedValue({ allowed: false, reason: 'not-found' });+ dbRowsMock.mockReturnValue([{ remoteHostId: 'host-1' }]);+ let resolveFirstStart!: () => void;+ const firstStart = new Promise<void>((resolve) => {+ resolveFirstStart = resolve;+ });+ let watchStartCount = 0;+ sshRequestMock.mockImplementation((_hostId: string, op: string) => {+ if (op === 'watchStart' && watchStartCount++ === 0) return firstStart;+ return Promise.resolve({ ok: true });+ });++ const starting = onFsWatchSubscribed(sshWorkdir);+ await vi.waitFor(() => {+ expect(watchStartCount).toBe(1);+ });++ // The first owner commits a new boundary while its watchStart is still in+ // flight. The old start must be stopped and the current subscription+ // rebuilt with the new owner stamp instead of reusing the stale callback.+ ownerStampState.current = { dataOwnerId: 'owner-b', ownerGeneration: 8 };+ resolveFirstStart();+ await starting;++ await vi.waitFor(() => {+ expect(watchStartCount).toBe(2);+ });+ expect(sshRequestMock).toHaveBeenCalledWith('host-1', 'watchStop', {+ workdir: sshWorkdir,+ });+ onFsWatchReleased(sshWorkdir);+ });++ it('watch: a released SSH registration ignores a late reconnect callback', async () => {+ const sshWorkdir = '/remote/home/user/released-reconnect-watch';+ guardMock.mockResolvedValue({ allowed: false, reason: 'not-found' });+ dbRowsMock.mockReturnValue([{ remoteHostId: 'host-1' }]);+ let watchStartCount = 0;+ sshRequestMock.mockImplementation((_hostId: string, op: string) => {+ if (op === 'watchStart') watchStartCount += 1;+ return Promise.resolve({ ok: true });+ });++ await onFsWatchSubscribed(sshWorkdir);+ const staleReconnect = sshListenerState.hostConnectedHandlers[0]!;+ onFsWatchReleased(sshWorkdir);+ staleReconnect();+ await Promise.resolve();++ expect(watchStartCount).toBe(1);+ });++ it('watch: release during SSH reconnect stops a late successful watcher', async () => {+ const sshWorkdir = '/remote/home/user/reconnect-release-watch';+ guardMock.mockResolvedValue({ allowed: false, reason: 'not-found' });+ dbRowsMock.mockReturnValue([{ remoteHostId: 'host-1' }]);+ let resolveReconnect!: () => void;+ const reconnectPending = new Promise<void>((resolve) => {+ resolveReconnect = resolve;+ });+ let watchStartCount = 0;+ sshRequestMock.mockImplementation((_hostId: string, op: string) => {+ if (op === 'watchStart') {+ watchStartCount += 1;+ if (watchStartCount === 2) return reconnectPending;+ }+ return Promise.resolve({ ok: true });+ });++ await onFsWatchSubscribed(sshWorkdir);+ sshListenerState.hostConnectedHandlers[0]!();+ await vi.waitFor(() => {+ expect(watchStartCount).toBe(2);+ });+ onFsWatchReleased(sshWorkdir);+ const stopCountBeforeSettle = sshRequestMock.mock.calls.filter(+ ([, op]) => op === 'watchStop',+ ).length;+ resolveReconnect();++ await vi.waitFor(() => {+ expect(sshRequestMock.mock.calls.filter(([, op]) => op === 'watchStop').length).toBe(+ stopCountBeforeSettle + 1,+ );+ });+ expect(sshListenerState.hostConnectedHandlers).toHaveLength(0);+ expect(sshListenerState.hostEventHandlers).toHaveLength(0);+ });++ it('watch: a late old reconnect does not stop the replacement registration', async () => {+ const sshWorkdir = '/remote/home/user/reconnect-replaced-watch';+ guardMock.mockResolvedValue({ allowed: false, reason: 'not-found' });+ dbRowsMock.mockReturnValue([{ remoteHostId: 'host-1' }]);+ let resolveOldReconnect!: () => void;+ const oldReconnectPending = new Promise<void>((resolve) => {+ resolveOldReconnect = resolve;+ });+ let watchStartCount = 0;+ sshRequestMock.mockImplementation((_hostId: string, op: string) => {+ if (op === 'watchStart') {+ watchStartCount += 1;+ if (watchStartCount === 2) return oldReconnectPending;+ }+ return Promise.resolve({ ok: true });+ });++ await onFsWatchSubscribed(sshWorkdir);+ sshListenerState.hostConnectedHandlers[0]!();+ await vi.waitFor(() => {+ expect(watchStartCount).toBe(2);+ });+ onFsWatchReleased(sshWorkdir);+ ownerStampState.current = { dataOwnerId: 'owner-b', ownerGeneration: 8 };+ await onFsWatchSubscribed(sshWorkdir);+ expect(watchStartCount).toBe(3);+ const stopCountWithReplacement = sshRequestMock.mock.calls.filter(+ ([, op]) => op === 'watchStop',+ ).length;++ resolveOldReconnect();+ await Promise.resolve();+ expect(sshRequestMock.mock.calls.filter(([, op]) => op === 'watchStop')).toHaveLength(+ stopCountWithReplacement,+ );+ const event = {+ event: 'fileTree',+ data: { workdir: sshWorkdir, type: 'change', relPath: 'src/replacement-owner.ts' },+ };+ sshListenerState.hostEventHandlers.at(-1)?.(event);+ expect(pushSpy).toHaveBeenCalledWith(FILE_BROWSER_EVENT_CHANNEL, event.data, {+ dataOwnerId: 'owner-b',+ ownerGeneration: 8,+ });+ onFsWatchReleased(sshWorkdir);+ });++ it('watch: owner change after a failed initial SSH start rebuilds current listeners', async () => {+ const sshWorkdir = '/remote/home/user/owner-reject-watch';+ guardMock.mockResolvedValue({ allowed: false, reason: 'not-found' });+ dbRowsMock.mockReturnValue([{ remoteHostId: 'host-1' }]);+ let rejectFirstStart!: (error: Error) => void;+ const firstStart = new Promise<never>((_resolve, reject) => {+ rejectFirstStart = reject;+ });+ let watchStartCount = 0;+ sshRequestMock.mockImplementation((_hostId: string, op: string) => {+ if (op === 'watchStart' && watchStartCount++ === 0) return firstStart;+ return Promise.resolve({ ok: true });+ });++ const starting = onFsWatchSubscribed(sshWorkdir);+ await vi.waitFor(() => {+ expect(watchStartCount).toBe(1);+ });+ ownerStampState.current = { dataOwnerId: 'owner-b', ownerGeneration: 8 };+ rejectFirstStart(new Error('connection reset'));+ await starting;++ await vi.waitFor(() => {+ expect(watchStartCount).toBe(2);+ });+ const event = {+ event: 'fileTree',+ data: { workdir: sshWorkdir, type: 'change', relPath: 'src/current-owner.ts' },+ };+ sshListenerState.hostEventHandlers.at(-1)?.(event);+ expect(pushSpy).toHaveBeenCalledWith(FILE_BROWSER_EVENT_CHANNEL, event.data, {+ dataOwnerId: 'owner-b',+ ownerGeneration: 8,+ });+ onFsWatchReleased(sshWorkdir);+ });++ it('watch: owner change during SSH reconnect retires the stale registration', async () => {+ const sshWorkdir = '/remote/home/user/owner-reconnect-watch';+ guardMock.mockResolvedValue({ allowed: false, reason: 'not-found' });+ dbRowsMock.mockReturnValue([{ remoteHostId: 'host-1' }]);+ let resolveReconnect!: () => void;+ const reconnectPending = new Promise<void>((resolve) => {+ resolveReconnect = resolve;+ });+ let watchStartCount = 0;+ sshRequestMock.mockImplementation((_hostId: string, op: string) => {+ if (op === 'watchStart') {+ watchStartCount += 1;+ if (watchStartCount === 2) return reconnectPending;+ }+ return Promise.resolve({ ok: true });+ });++ await onFsWatchSubscribed(sshWorkdir);+ const staleReconnect = sshListenerState.hostConnectedHandlers[0]!;+ staleReconnect();+ await vi.waitFor(() => {+ expect(watchStartCount).toBe(2);+ });+ ownerStampState.current = { dataOwnerId: 'owner-b', ownerGeneration: 8 };+ resolveReconnect();++ await vi.waitFor(() => {+ expect(watchStartCount).toBe(3);+ });+ expect(sshRequestMock).toHaveBeenCalledWith('host-1', 'watchStop', {+ workdir: sshWorkdir,+ });+ const event = {+ event: 'fileTree',+ data: { workdir: sshWorkdir, type: 'change', relPath: 'src/reconnected-owner.ts' },+ };+ sshListenerState.hostEventHandlers.at(-1)?.(event);+ expect(pushSpy).toHaveBeenCalledWith(FILE_BROWSER_EVENT_CHANNEL, event.data, {+ dataOwnerId: 'owner-b',+ ownerGeneration: 8,+ });+ onFsWatchReleased(sshWorkdir);+ });+it('watch: a second release cancels an already scheduled SSH reconcile', async () => {const sshWorkdir = '/remote/home/user/cancel-retry-watch';guardMock.mockResolvedValue({ allowed: false, reason: 'not-found' });diff --git a/apps/desktop/src/main/file-browser/device-op.ts b/apps/desktop/src/main/file-browser/device-op.tsindex d3a052b6f5..f48a84e8a6 100644--- a/apps/desktop/src/main/file-browser/device-op.ts+++ b/apps/desktop/src/main/file-browser/device-op.ts@@ -56,6 +56,7 @@ import {FILE_BROWSER_EVENT_CHANNEL,FILE_BROWSER_REMOTE_OP_CHANNEL,parseFsWatchTopic,+ type PushOwnerStamp,} from '@cindy/device-link';import { WorkdirWatchManager } from '@cindy/remote-file-service';@@ -71,6 +72,7 @@ import {import { throwIpcError } from '../utils/ipcValidate.js';import { uploadLocalFile } from '../device-link/mediaTransfer.js';import { pushToTopicSubscribers } from '../device-link/dispatch.js';+import { getSafeDataOwnerPushStamp } from '../device-link/broadcast-tap.js';import * as subscriptions from '../device-link/subscriptions.js';import { getRipgrepBinaryPath } from '../maker-host/runtime-configs.js';import { getRemoteFileBrowser } from './remote-deps.js';@@ -645,9 +647,18 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {* fileTree 事件从 daemon 流入 onHostEvent → 同一推送出口。* 幂等:重复 onSubscribed 忽略;onReleased 清理对应资源。*/-const localWatch = new WorkdirWatchManager((event) => {- pushToTopicSubscribers(FILE_BROWSER_EVENT_CHANNEL, event);-});+/**+ * Keep the source owner on the watcher instance rather than reading the active+ * owner when an fs event eventually arrives. A watcher can outlive a logout or+ * account switch, and the delayed event must remain attributable to the owner+ * that created the watcher.+ */+interface LocalWatchHandle {+ manager: WorkdirWatchManager;+ ownerStamp?: PushOwnerStamp;+}++const localWatchHandles = new Map<string, LocalWatchHandle>();const localWatchWorkdirs = new Set<string>();const sshWatchOffs = new Map<string, () => void>();/** 最新订阅意图;release / 立即重订阅时由正在启动的同一任务收敛到最新状态。 */@@ -655,6 +666,20 @@ const fsWatchDesired = new Set<string>();/** 启动窗口占位:dedup 判定与首个 await 之间的 TOCTOU 防护(见下)。 */const fsWatchStarting = new Map<string, symbol>();+function isSameOwnerStamp(+ left: PushOwnerStamp | undefined,+ right: PushOwnerStamp | undefined,+): boolean {+ return (+ left?.dataOwnerId === right?.dataOwnerId &&+ left?.ownerGeneration === right?.ownerGeneration+ );+}++function isOwnerStampCurrent(ownerStamp: PushOwnerStamp | undefined): boolean {+ return isSameOwnerStamp(ownerStamp, getSafeDataOwnerPushStamp());+}+async function onFsWatchSubscribed(workdir: string): Promise<void> {fsWatchDesired.add(workdir);await startFsWatchIfDesired(workdir);@@ -713,17 +738,41 @@ async function onFsWatchSubscribedInner(workdir: string, token: symbol): Promiselog.warn('fs-watch subscribe rejected by guard', { workdir, reason: guardResult.reason });return;}+ // Freeze the owner immediately before creating the watcher. The event source,+ // not the eventual delivery time, defines the data boundary.+ const ownerStamp = getSafeDataOwnerPushStamp();if (exec.kind === 'local') {+ let localWatch = localWatchHandles.get(workdir);+ if (!localWatch) {+ const manager = new WorkdirWatchManager((event) => {+ if (!fsWatchDesired.has(workdir)) return;+ pushToTopicSubscribers(FILE_BROWSER_EVENT_CHANNEL, event, ownerStamp);+ });+ localWatch = { manager, ownerStamp };+ localWatchHandles.set(workdir, localWatch);+ }+ const activeLocalWatch = localWatch;try {- await localWatch.start(workdir, { hideMetaFiles: true });- if (!isFsWatchStartCurrent(workdir, token)) {- localWatch.stop(workdir);+ await activeLocalWatch.manager.start(workdir, { hideMetaFiles: true });+ if (+ !isFsWatchStartCurrent(workdir, token) ||+ localWatchHandles.get(workdir) !== activeLocalWatch ||+ !isOwnerStampCurrent(activeLocalWatch.ownerStamp)+ ) {+ activeLocalWatch.manager.stop(workdir);+ if (localWatchHandles.get(workdir) === activeLocalWatch) {+ localWatchHandles.delete(workdir);+ }+ if (fsWatchDesired.has(workdir)) scheduleFsWatchReconcile(workdir);return;}localWatchWorkdirs.add(workdir);log.info('device fs-watch started (local)', { workdir });} catch (err) {localWatchWorkdirs.delete(workdir);+ if (localWatchHandles.get(workdir) === activeLocalWatch) {+ localWatchHandles.delete(workdir);+ }log.warn('device fs-watch start failed', { workdir, error: String(err) });}return;@@ -735,12 +784,11 @@ async function onFsWatchSubscribedInner(workdir: string, token: symbol): Promiseif (evt.event !== 'fileTree') return;const data = evt.data as { workdir: string };if (data.workdir !== workdir) return;- pushToTopicSubscribers(FILE_BROWSER_EVENT_CHANNEL, evt.data);- });- const offReconnect = mgr.onHostConnected(hostId, () => {- void mgr.request(hostId, 'watchStart', { workdir, hideMetaFiles: true }).catch(() => undefined);+ if (!fsWatchDesired.has(workdir)) return;+ pushToTopicSubscribers(FILE_BROWSER_EVENT_CHANNEL, evt.data, ownerStamp);});let listenersDisposed = false;+ let offReconnect = (): void => undefined;const disposeListeners = (): void => {if (listenersDisposed) return;listenersDisposed = true;@@ -751,34 +799,60 @@ async function onFsWatchSubscribedInner(workdir: string, token: symbol): PromisedisposeListeners();void mgr.request(hostId, 'watchStop', { workdir }).catch(() => undefined);};- sshWatchOffs.set(workdir, stopWatch);- try {- await mgr.request(hostId, 'watchStart', { workdir, hideMetaFiles: true });- const isRegistered = sshWatchOffs.get(workdir) === stopWatch;- if (!isFsWatchStartCurrent(workdir, token) || !isRegistered) {- if (isRegistered) sshWatchOffs.delete(workdir);- // release 可能已在 watchStart 完成前发过 stop;完成后再发一次,保证- // daemon 不会留下刚启动成功的 watcher。+ const isRegistered = (): boolean => sshWatchOffs.get(workdir) === stopWatch;+ const disposeStaleWatch = (): void => {+ const registeredStop = sshWatchOffs.get(workdir);+ if (registeredStop === stopWatch) {+ sshWatchOffs.delete(workdir);+ // A watchStart may already be in flight. stopWatch is intentionally safe+ // to call again after it settles so a late successful daemon watch is removed.+ stopWatch();+ } else if (registeredStop) {+ // A newer registration owns this workdir. Only detach the stale closure:+ // watchStop is keyed by workdir and could stop the replacement watcher too.+ disposeListeners();+ } else {+ // release removed this registration while its request was in flight.stopWatch();- // release 后若已立即重新订阅,旧启动先完成清理,再从全新监听器和- // watchStart 开始;setTimeout 确保外层 finally 已移除旧 token。- if (fsWatchDesired.has(workdir)) {- scheduleFsWatchReconcile(workdir);- }- return;}+ if (fsWatchDesired.has(workdir)) scheduleFsWatchReconcile(workdir);+ };+ const startSshWatch = async (requireStartupToken: boolean): Promise<boolean> => {+ const isCurrent = (): boolean =>+ fsWatchDesired.has(workdir) &&+ isRegistered() &&+ isOwnerStampCurrent(ownerStamp) &&+ (!requireStartupToken || isFsWatchStartCurrent(workdir, token));+ if (!isCurrent()) {+ disposeStaleWatch();+ return false;+ }+ try {+ await mgr.request(hostId, 'watchStart', { workdir, hideMetaFiles: true });+ } catch (err) {+ if (!isCurrent()) disposeStaleWatch();+ throw err;+ }+ if (!isCurrent()) {+ disposeStaleWatch();+ return false;+ }+ return true;+ };+ sshWatchOffs.set(workdir, stopWatch);+ offReconnect = mgr.onHostConnected(hostId, () => {+ void startSshWatch(false).catch((err) => {+ log.warn('device fs-watch ssh reconnect failed', {+ workdir,+ hostId,+ error: String(err),+ });+ });+ });+ try {+ if (!(await startSshWatch(true))) return;log.info('device fs-watch started (ssh nested)', { workdir, hostId });} catch (err) {- const isRegistered = sshWatchOffs.get(workdir) === stopWatch;- const isCurrent = isFsWatchStartCurrent(workdir, token);- if (!isCurrent || !isRegistered) {- if (isRegistered) sshWatchOffs.delete(workdir);- disposeListeners();- // release 后立即重订阅时,旧 watchStart 的失败不能吞掉新的订阅意图。- if (fsWatchDesired.has(workdir)) {- scheduleFsWatchReconcile(workdir);- }- }// 当前订阅的初次启动失败时保留 stop/reconnect 监听;host 下次连接会// 通过 offReconnect 对应回调重试 watchStart。log.warn('device fs-watch ssh start failed', { workdir, hostId, error: String(err) });@@ -789,8 +863,17 @@ function onFsWatchReleased(workdir: string): void {// guard / DB lookup / watchStart 任一 await 结束后都读取最新订阅意图;// 保留启动 token 可串行吸收紧随 release 到来的重订阅,避免同路径双启动。fsWatchDesired.delete(workdir);+ const localWatch = localWatchHandles.get(workdir);+ // If the manager has already entered the active set, stop it even while the+ // outer start token is being finalized. Only an in-flight start is left alone+ // so an immediate resubscribe can converge on that same startup.+ if (localWatchWorkdirs.has(workdir) || !fsWatchStarting.has(workdir)) {+ if (localWatch) {+ localWatchHandles.delete(workdir);+ localWatch.manager.stop(workdir);+ }+ }if (localWatchWorkdirs.delete(workdir)) {- localWatch.stop(workdir);log.info('device fs-watch stopped (local)', { workdir });}const offSsh = sshWatchOffs.get(workdir);diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.tsindex 1571109f7e..52ab4e4fee 100644--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts@@ -100,6 +100,7 @@ vi.mock('@cindy/maker-core', async (importOriginal) => {};});vi.mock('../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: h.tapWindowBroadcast,}));vi.mock('../../maker-ipc/register.js', () => ({diff --git a/apps/desktop/src/main/im/shared/__tests__/sessionRepoBroadcast.test.ts b/apps/desktop/src/main/im/shared/__tests__/sessionRepoBroadcast.test.tsindex edee760368..21de76b0b0 100644--- a/apps/desktop/src/main/im/shared/__tests__/sessionRepoBroadcast.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/sessionRepoBroadcast.test.ts@@ -24,6 +24,7 @@ vi.mock('electron', () => ({},}));vi.mock('../../../device-link/broadcast-tap', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: mocks.tapWindowBroadcast,}));vi.mock('../../../logger', () => ({diff --git a/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts b/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.tsindex 8c6bdf4c63..8fbeb4ff01 100644--- a/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/sessionRepoRevive.test.ts@@ -40,6 +40,7 @@ vi.mock('electron', () => ({},}));vi.mock('../../../device-link/broadcast-tap', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: mocks.tapWindowBroadcast,}));vi.mock('../../../logger', () => ({diff --git a/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts b/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.tsnew file mode 100644index 0000000000..20809aa944--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ getDbClient: vi.fn(),+}));++vi.mock('../client/current', () => ({+ getDbClient: mocks.getDbClient,+}));++import {+ AgentInputQueueSnapshotTooLargeError,+ awaitAgentInputQueueSnapshotPersistence,+ saveAgentInputQueueSnapshot,+} from '../agentInputQueueSnapshots.js';+import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';++function deferred<T>() {+ let resolve!: (value: T | PromiseLike<T>) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, resolve, reject };+}++function queued(text = 'queued', clientId = `client-${text}`): AgentInputQueuedMessage {+ return {+ clientId,+ text,+ persistedContent: text,+ model: 'test-model',+ effort: 'medium',+ permissionMode: 'default',+ workingDir: '/tmp/cindy-test',+ chatMessage: { clientId, role: 'user' as const, content: text },+ createOpts: {+ agentKind: 'pi' as const,+ model: 'test-model',+ effort: 'medium',+ permissionMode: 'default',+ workingDir: '/tmp/cindy-test',+ },+ };+}++function installDb(+ opts: {+ write?: () => void | Promise<void>;+ } = {},+) {+ const onConflictDoUpdate = vi.fn(() => opts.write?.());+ const values = vi.fn(() => ({ onConflictDoUpdate }));+ const insert = vi.fn(() => ({ values }));+ const where = vi.fn(() => Promise.resolve());+ const del = vi.fn(() => ({ where }));+ const db = { insert, delete: del };+ mocks.getDbClient.mockReturnValue({ drizzle: db });+ return { db, insert, onConflictDoUpdate };+}++describe('agent input queue snapshot durability boundary', () => {+ it('waits for the current session write and resolves after the DB operation', async () => {+ const gate = deferred<void>();+ const { onConflictDoUpdate } = installDb({ write: () => gate.promise });++ const savePromise = saveAgentInputQueueSnapshot('snapshot-flush', [queued()]);+ const flushPromise = awaitAgentInputQueueSnapshotPersistence('snapshot-flush');++ let settled = false;+ void flushPromise.then(() => {+ settled = true;+ });+ await Promise.resolve();+ expect(settled).toBe(false);+ expect(onConflictDoUpdate).toHaveBeenCalledTimes(1);++ gate.resolve();+ await expect(savePromise).resolves.toBeUndefined();+ await expect(flushPromise).resolves.toBeUndefined();+ });++ it('exposes a failed write to the durable waiter while allowing a later retry', async () => {+ const failure = new Error('db unavailable');+ let attempt = 0;+ const retryGate = deferred<void>();+ const { onConflictDoUpdate } = installDb({+ write: () => {+ attempt += 1;+ if (attempt === 1) return Promise.reject(failure);+ return retryGate.promise;+ },+ });++ const failedSave = saveAgentInputQueueSnapshot('snapshot-retry', [queued('first')]);+ const failedFlush = awaitAgentInputQueueSnapshotPersistence('snapshot-retry');+ await expect(failedFlush).rejects.toBe(failure);+ await expect(failedSave).rejects.toBe(failure);+ await expect(awaitAgentInputQueueSnapshotPersistence('snapshot-retry')).rejects.toBe(failure);++ const retrySave = saveAgentInputQueueSnapshot('snapshot-retry', [queued('second')]);+ const retryFlush = awaitAgentInputQueueSnapshotPersistence('snapshot-retry');+ await Promise.resolve();+ await Promise.resolve();+ expect(onConflictDoUpdate).toHaveBeenCalledTimes(2);+ retryGate.resolve();+ await expect(retrySave).resolves.toBeUndefined();+ await expect(retryFlush).resolves.toBeUndefined();+ });++ it('fails explicitly when sanitization still leaves the snapshot over the size cap', async () => {+ const { insert } = installDb();+ const hugeText = 'x'.repeat(16 * 1024 * 1024 + 1);+ const item = queued(hugeText, 'client-oversize');+ const savePromise = saveAgentInputQueueSnapshot('snapshot-oversize', [item]);+ const flushPromise = awaitAgentInputQueueSnapshotPersistence('snapshot-oversize');++ await expect(flushPromise).rejects.toBeInstanceOf(AgentInputQueueSnapshotTooLargeError);+ await expect(savePromise).rejects.toMatchObject({+ code: 'AGENT_INPUT_QUEUE_SNAPSHOT_TOO_LARGE',+ sessionId: 'snapshot-oversize',+ });+ expect(insert).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.tsindex bae71ef284..4ef425e7ca 100644--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts@@ -17,6 +17,7 @@ vi.mock('electron', () => ({},}));vi.mock('../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: h.tapWindowBroadcast,}));vi.mock('../agentIslandSessionPatch.js', () => ({diff --git a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.tsindex 5ac8688d33..cd63cc78e5 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionActiveTurn.test.ts@@ -291,6 +291,29 @@ describe('sessionActiveTurn', () => {expect(notified[0]).toEqual(['s-notify', row!.last_turn_ended_at!]);});+ it('freezes the notify context before an async barrier settles', async () => {+ const { markSessionTurnEndedAfterBarrier, setOnSessionTurnEndedPersisted } =+ await import('../sessionActiveTurn.js');+ const client = createTestDbClient();+ await seedSession(client, 's-notify-owner');+ let currentOwner = 'owner-a';+ const notifiedOwners: unknown[] = [];+ setOnSessionTurnEndedPersisted(+ (_sid, _endedAt, context) => notifiedOwners.push(context),+ () => currentOwner,+ );++ let releaseBarrier!: () => void;+ const barrier = new Promise<void>((resolve) => {+ releaseBarrier = resolve;+ });+ markSessionTurnEndedAfterBarrier('s-notify-owner', barrier);+ currentOwner = 'owner-b';+ releaseBarrier();++ await vi.waitFor(() => expect(notifiedOwners).toEqual(['owner-a']));+ });+it('notify carries the read-back MAX-guarded value, never a stale rewind', async () => {const { markSessionTurnEnded, setOnSessionTurnEndedPersisted } =await import('../sessionActiveTurn.js');diff --git a/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts b/apps/desktop/src/main/localDb/agentInputQueueSnapshots.tsindex 224911e7d4..50bc3ab015 100644--- a/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts+++ b/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts@@ -7,8 +7,8 @@* sessionActiveTurn 的 chainWrite),避免"后发先至"让旧快照覆盖新快照。** 体量守卫:payload 超过 MAX_PAYLOAD_BYTES 时先剥离 files[].base64(剪贴板- * 图片的内联兜底,路径型附件不受影响)重试;仍超限则放弃本次写入并保留旧- * 快照(宁可恢复到稍旧的队列,不写入截断的坏数据)。+ * 图片的内联兜底,路径型附件不受影响)重试;仍超限则显式失败并保留旧快照+ * (宁可让上层保留可重试的输入,不把未持久化误报成成功)。*/import { eq } from 'drizzle-orm';@@ -28,17 +28,72 @@ const MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;/** per-session 写链:只做覆盖写/删除排队保序,无读改写。 */const _writeChains = new Map<string, Promise<void>>();+/** 当前 session 最近一次写操作的真实结果(保留 reject 供 durable boundary 等待者观察)。 */+const _latestWriteResults = new Map<string, Promise<void>>();++/**+ * A queue snapshot that cannot fit in the durable row is not a successful+ * persistence operation. Callers use this distinction to retain remote OSS+ * objects and retry instead of treating the in-memory queue as crash-safe.+ */+export class AgentInputQueueSnapshotTooLargeError extends Error {+ readonly code = 'AGENT_INPUT_QUEUE_SNAPSHOT_TOO_LARGE';++ constructor(+ readonly sessionId: string,+ readonly itemCount: number,+ readonly payloadBytes: number,+ ) {+ super(+ `agent input queue snapshot exceeds ${MAX_PAYLOAD_BYTES} bytes after sanitization ` ++ `(session=${sessionId}, items=${itemCount}, bytes=${payloadBytes})`,+ );+ this.name = 'AgentInputQueueSnapshotTooLargeError';+ }+}function chainWrite(sessionId: string, op: () => Promise<void>): Promise<void> {const prev = _writeChains.get(sessionId) ?? Promise.resolve();const opResult = prev.then(op);+ // The operation promise is returned to the caller and may be intentionally+ // observed later through awaitAgentInputQueueSnapshotPersistence(). Attach a+ // no-op rejection observer now so a fire-and-forget caller cannot create an+ // unhandled-rejection warning while the durable waiter still sees the error.+ void opResult.catch(() => undefined);const chainNext = opResult.catch(() => undefined).finally(() => {if (_writeChains.get(sessionId) === chainNext) _writeChains.delete(sessionId);});+ // Keep a settled failure visible to the next durable-boundary waiter until+ // a later successful write replaces it. Treating a rejected write as+ // "nothing pending" would let attachment ownership advance past a snapshot+ // that never became crash-recoverable.+ void opResult.then(+ () => {+ if (_latestWriteResults.get(sessionId) === opResult) {+ _latestWriteResults.delete(sessionId);+ }+ },+ () => undefined,+ );_writeChains.set(sessionId, chainNext);+ _latestWriteResults.set(sessionId, opResult);return opResult;}+/**+ * Wait for the snapshot write(s) already queued for a session at call time.+ *+ * `saveAgentInputQueueSnapshot` remains non-blocking for the coordinator, but+ * remote attachment cleanup needs a durable boundary before deleting the+ * controller's OSS object. The input handler calls this immediately after+ * accepting an item, so the returned promise covers that acceptance snapshot;+ * later writes are chained after it and are not silently skipped. A session+ * with no pending write is already at the latest known durable boundary.+ */+export function awaitAgentInputQueueSnapshotPersistence(sessionId: string): Promise<void> {+ return _latestWriteResults.get(sessionId) ?? Promise.resolve();+}+function stripInlineBase64(items: AgentInputQueuedMessage[]): AgentInputQueuedMessage[] {return items.map((item) => {let changed = false;@@ -86,7 +141,7 @@ export function saveAgentInputQueueSnapshot(items: items.length,bytes: payload.length,});- return;+ throw new AgentInputQueueSnapshotTooLargeError(sessionId, items.length, payload.length);}log.warn('queue snapshot stripped inline base64 attachments to fit size cap', {sessionId,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesClearRace.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesClearRace.test.tsnew file mode 100644index 0000000000..f78b0ee874--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesClearRace.test.ts@@ -0,0 +1,191 @@+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messages, sessions } from '../../schema';++const h = vi.hoisted(() => ({+ db: null as ReturnType<typeof drizzle> | null,+ sqlite: null as Database.Database | null,+ client: null as any,+ broadcast: vi.fn(),+ raceOnInsert: false,+}));++vi.mock('electron', () => ({+ ipcMain: { handle: vi.fn() },+ BrowserWindow: { getAllWindows: () => [] },+}));+vi.mock('../../../logger', () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../../logger.js', () => ({+ createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../../maker-host/codex-local-sessions', () => ({+ importExternalCodexMessagesForSession: vi.fn(async () => undefined),+}));+vi.mock('../../../maker-host/claude-local-sessions', () => ({+ importExternalClaudeCodeMessagesForSession: vi.fn(async () => undefined),+}));+vi.mock('../../../embedders/chat-history-embedder', () => ({+ onMessageCreated: vi.fn(async () => undefined),+}));+vi.mock('../../../git-context/prRefsStore', () => ({+ recomputePrRefsForSession: vi.fn(async () => undefined),+ recordPrRefsForMessage: vi.fn(async () => undefined),+}));+vi.mock('../../../cindy-media/chatAttachments', () => ({+ commitMessageMediaRefs: vi.fn(async () => undefined),+ collectCindyMediaHashes: vi.fn(() => []),+}));+vi.mock('../../../cindy-media/ledger', () => ({+ removeRefs: vi.fn(async () => undefined),+ removeSessionAttachmentRefIfUnreferencedByLiveMessage: vi.fn(async () => undefined),+}));+vi.mock('../../../file-browser/remote-file-cache', () => ({+ cleanupStagedChatAttachments: vi.fn(async () => undefined),+ extractChatAttachmentPathsFromPersistedContent: (content: unknown) =>+ content === 'attachment' ? ['C:\\chat-attachment-cache\\race.bin'] : [],+}));+vi.mock('../../../device-link/invoke-context', () => ({+ isDeviceLinkInvoke: vi.fn(() => false),+}));+vi.mock('../../../device-link/broadcast-tap', () => ({+ captureDataOwnerBroadcastScope: vi.fn(() => null),+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),+ tapWindowBroadcast: h.broadcast,+}));+vi.mock('../../client/current', () => ({+ getDbClient: () => h.client,+}));++import { createMessage, rewindPersistedUserMessageAfterClear } from '../messages';++function createDb(): Database.Database {+ const sqlite = new Database(':memory:');+ sqlite.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ cleared_at INTEGER,+ status TEXT NOT NULL DEFAULT 'active'+ );+ CREATE TABLE messages (+ id TEXT PRIMARY KEY,+ client_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ role TEXT NOT NULL,+ content TEXT NOT NULL,+ tool_use_id TEXT,+ agent_meta TEXT,+ agent_kind TEXT,+ created_at INTEGER NOT NULL,+ rewind_at INTEGER+ );+ CREATE UNIQUE INDEX uniq_messages_session_client ON messages(session_id, client_id);+ `);+ sqlite.prepare('INSERT INTO sessions (id, cleared_at, status) VALUES (?, NULL, ?)').run('s1', 'active');+ const db = drizzle(sqlite, { schema: { messages, sessions } });+ h.sqlite = sqlite;+ h.db = db;+ h.client = {+ drizzle: db,+ exec: vi.fn(async (sql: string, params: unknown[] = []) => {+ // Model /clear winning between the preflight SELECT and the guarded+ // INSERT. The single SQL statement must then insert zero rows.+ if (h.raceOnInsert && sql.startsWith('INSERT INTO messages')) {+ sqlite.prepare('UPDATE sessions SET cleared_at = ? WHERE id = ?').run(200, 's1');+ }+ return sqlite.prepare(sql).run(...params);+ }),+ };+ return sqlite;+}++describe('message persistence clear boundary', () => {+ let sqlite: Database.Database;++ beforeEach(() => {+ vi.clearAllMocks();+ h.raceOnInsert = false;+ sqlite = createDb();+ });++ it('uses an atomic clear-token guard for optimistic inserts', async () => {+ await expect(+ createMessage(+ 's1',+ { clientId: 'client-ok', role: 'user', content: 'hello' },+ { expectedClearBoundaryMs: null },+ ),+ ).resolves.toMatchObject({ clientId: 'client-ok', content: 'hello' });++ h.raceOnInsert = true;+ await expect(+ createMessage(+ 's1',+ { clientId: 'client-raced', role: 'user', content: 'stale' },+ { expectedClearBoundaryMs: null },+ ),+ ).rejects.toMatchObject({ code: 'REMOTE_OPTIMISTIC_INPUT_CLEARED' });++ expect(+ sqlite+ .prepare('SELECT 1 FROM messages WHERE session_id = ? AND client_id = ?')+ .get('s1', 'client-raced'),+ ).toBeUndefined();+ });++ it('rewinds a row that lost the clear race and is idempotent', async () => {+ const { cleanupStagedChatAttachments } = await import('../../../file-browser/remote-file-cache');+ sqlite+ .prepare(+ `INSERT INTO messages+ (id, client_id, session_id, role, content, created_at, rewind_at)+ VALUES (?, ?, ?, 'user', ?, ?, NULL)`,+ )+ .run('row-1', 'client-1', 's1', 'attachment', 100);++ await rewindPersistedUserMessageAfterClear('s1', 'client-1');++ const row = sqlite+ .prepare('SELECT rewind_at AS rewindAt FROM messages WHERE session_id = ? AND client_id = ?')+ .get('s1', 'client-1') as { rewindAt: number | null };+ expect(row.rewindAt).toEqual(expect.any(Number));+ expect(h.broadcast).toHaveBeenCalledWith('local-db:messages:deleted', {+ sessionId: 's1',+ clientId: 'client-1',+ clientIds: ['client-1'],+ });+ expect(cleanupStagedChatAttachments).toHaveBeenCalledWith([+ 'C:\\chat-attachment-cache\\race.bin',+ ]);++ h.broadcast.mockClear();+ await rewindPersistedUserMessageAfterClear('s1', 'client-1');+ expect(h.broadcast).not.toHaveBeenCalled();+ });++ it('reconciles session attachment refs for a rewound user row', async () => {+ const { collectCindyMediaHashes } = await import('../../../cindy-media/chatAttachments');+ const { removeSessionAttachmentRefIfUnreferencedByLiveMessage } = await import(+ '../../../cindy-media/ledger',+ );+ const hash = 'a'.repeat(64);+ vi.mocked(collectCindyMediaHashes).mockReturnValue([hash]);+ sqlite+ .prepare(+ `INSERT INTO messages+ (id, client_id, session_id, role, content, created_at, rewind_at)+ VALUES (?, ?, ?, 'user', ?, ?, NULL)`,+ )+ .run('row-media', 'client-media', 's1', `cindy-media://blobs/${hash}.png`, 100);++ await rewindPersistedUserMessageAfterClear('s1', 'client-media');++ expect(removeSessionAttachmentRefIfUnreferencedByLiveMessage).toHaveBeenCalledWith({+ sessionId: 's1',+ hash,+ });+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesSupersedeRetriedUserTurn.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesSupersedeRetriedUserTurn.test.tsindex 12bd90de92..4d9ff18cd3 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesSupersedeRetriedUserTurn.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesSupersedeRetriedUserTurn.test.ts@@ -45,6 +45,7 @@ vi.mock('../../client/current', () => ({getDbClient: () => ({ drizzle: h.db }),}));vi.mock('../../../device-link/broadcast-tap', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: h.tapWindowBroadcast,}));diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.tsindex 1e1b9688e2..e4bd9d6e33 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionAutoTitlePersist.test.ts@@ -30,7 +30,10 @@ vi.mock('../../../git-context/prRefsStore', () => ({}));vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn(async () => undefined) }));-vi.mock('../../../device-link/broadcast-tap.js', () => ({ tapWindowBroadcast: vi.fn() }));+vi.mock('../../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),+ tapWindowBroadcast: vi.fn(),+}));vi.mock('../../agentIslandSessionPatch', () => ({ notifyAgentIslandSessionPatch: vi.fn() }));vi.mock('../../../messagePersistBroadcaster', () => ({ noteSessionClearBoundary: vi.fn() }));vi.mock('../../../sessionIds', () => ({ resolveBusinessSessionId: (id: string) => id }));diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemoteHostIdReader.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemoteHostIdReader.test.tsindex de10fe207a..600ade4113 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemoteHostIdReader.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemoteHostIdReader.test.ts@@ -48,7 +48,10 @@ vi.mock('../../../git-context/prRefsStore', () => ({}));vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn(async () => undefined) }));-vi.mock('../../../device-link/broadcast-tap.js', () => ({ tapWindowBroadcast: vi.fn() }));+vi.mock('../../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),+ tapWindowBroadcast: vi.fn(),+}));vi.mock('../../agentIslandSessionPatch', () => ({ notifyAgentIslandSessionPatch: vi.fn() }));vi.mock('../../../messagePersistBroadcaster', () => ({ noteSessionClearBoundary: vi.fn() }));vi.mock('../../../sessionIds', () => ({ resolveBusinessSessionId: (id: string) => id }));diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.tsindex d1f420d375..468177c642 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts@@ -38,6 +38,7 @@ vi.mock('../../../git-context/prRefsStore', () => ({vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn(async () => undefined) }));vi.mock('../../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: h.tapWindowBroadcast,}));vi.mock('../../agentIslandSessionPatch', () => ({ notifyAgentIslandSessionPatch: vi.fn() }));diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 941102fd75..cca6af6d2b 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -46,6 +46,7 @@ vi.mock('../../../git-context/prRefsStore', () => ({vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn(async () => undefined) }));vi.mock('../../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: h.tapWindowBroadcast,}));vi.mock('../../../sessionTaskSummary.js', () => ({diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex a53103e510..ec057ca9c3 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -19,10 +19,16 @@ import {extractMessagePreview,} from '../mapper';import { throwIpcError, requireString } from '../../utils/ipcValidate';-import { tapWindowBroadcast } from '../../device-link/broadcast-tap';+import * as broadcastTap from '../../device-link/broadcast-tap';import { createLogger } from '../../logger';-import { commitMessageMediaRefs } from '../../cindy-media/chatAttachments';-import { removeRefs as removeMediaRefs } from '../../cindy-media/ledger';+import {+ collectCindyMediaHashes,+ commitMessageMediaRefs,+} from '../../cindy-media/chatAttachments';+import {+ removeRefs as removeMediaRefs,+ removeSessionAttachmentRefIfUnreferencedByLiveMessage,+} from '../../cindy-media/ledger';import { importExternalCodexMessagesForSession } from '../../maker-host/codex-local-sessions';import { importExternalClaudeCodeMessagesForSession } from '../../maker-host/claude-local-sessions';import { isDeviceLinkInvoke } from '../../device-link/invoke-context';@@ -57,11 +63,53 @@ const MESSAGE_DELETION_USER_BOUNDARY_PAGE_SIZE = 32;const messageRowid = sql<number>`rowid`;type MessageRow = typeof messages.$inferSelect;type MessageRowWithRowid = MessageRow & { rowid: number };+type DataOwnerBroadcastScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope>;++function captureOwnerBroadcastScope(): DataOwnerBroadcastScope | null {+ try {+ const capture = broadcastTap.captureDataOwnerBroadcastScope;+ return capture ? capture() : null;+ } catch {+ // Narrow unit-test mocks may intentionally expose only the legacy tap API.+ return null;+ }+}++function isOwnerBroadcastScopeCurrent(scope: DataOwnerBroadcastScope | null | undefined): boolean {+ if (scope === null || scope === undefined) return true;+ try {+ const isCurrent = broadcastTap.isDataOwnerBroadcastScopeCurrent;+ return isCurrent ? isCurrent(scope) : true;+ } catch {+ return true;+ }+}++function getSafeOwnerPushStamp(): ReturnType<typeof broadcastTap.getSafeDataOwnerPushStamp> {+ try {+ return broadcastTap.getSafeDataOwnerPushStamp?.();+ } catch {+ return undefined;+ }+}++/**+ * Resolve the stamp for a synchronous broadcast. A captured scope is never+ * relabeled with the current owner after an await; stale scopes are dropped.+ */+function ownerStampForBroadcast(+ scope: DataOwnerBroadcastScope | null | undefined,+): DataOwnerBroadcastScope['ownerStamp'] | null {+ if (!isOwnerBroadcastScopeCurrent(scope)) return null;+ if (scope !== undefined && scope !== null) return scope.ownerStamp;+ return getSafeOwnerPushStamp();+}const PERSISTED_CHAT_ATTACHMENT_ROWS_SQL = `SELECT m.contentFROM messages AS mJOIN sessions AS s ON s.id = m.session_idWHERE s.status != 'deleted'+ AND m.rewind_at IS NULLAND m.content LIKE '%chat-attachment-cache%'`;export interface EstimatedSessionValueEntry {@@ -102,7 +150,7 @@ export async function listSessionPersistedChatAttachmentPaths(const rows = await getDbClient().drizzle.select({ content: messages.content }).from(messages)- .where(eq(messages.sessionId, sessionId));+ .where(and(eq(messages.sessionId, sessionId), isNull(messages.rewindAt)));return uniqueStrings(rows.flatMap((row) => extractChatAttachmentPathsFromPersistedContent(row.content)),);@@ -131,7 +179,13 @@ export async function listPersistedChatAttachmentPathsForOtherSessions(.select({ content: messages.content }).from(messages).innerJoin(sessions, eq(messages.sessionId, sessions.id))- .where(and(ne(messages.sessionId, sessionId), ne(sessions.status, 'deleted')));+ .where(+ and(+ ne(messages.sessionId, sessionId),+ ne(sessions.status, 'deleted'),+ isNull(messages.rewindAt),+ ),+ );return uniqueStrings(rows.flatMap((row) => extractChatAttachmentPathsFromPersistedContent(row.content)),);@@ -607,12 +661,31 @@ export async function runMessagesListImportSideEffects(* handleMessageCreatedRaw 对已存在 clientId 走 merge/替换语义,因此**更新**行* (如 dismiss)复用同一事件即可让 peer 视图刷新,无需新增 onUpdated 通道。*/-export function broadcastMessageRow(sessionId: string, msg: Message): void {- tapWindowBroadcast('local-db:messages:created', { sessionId, message: msg });+export function broadcastMessageRow(+ sessionId: string,+ msg: Message,+ ownerScope?: DataOwnerBroadcastScope | null,+): void {+ const ownerStamp = ownerStampForBroadcast(ownerScope);+ if (ownerStamp === null) return;+ if (ownerScope !== undefined && ownerScope !== null) {+ broadcastTap.tapWindowBroadcast('local-db:messages:created', { sessionId, message: msg }, ownerStamp);+ } else if (ownerStamp === undefined) {+ broadcastTap.tapWindowBroadcast('local-db:messages:created', { sessionId, message: msg });+ } else {+ broadcastTap.tapWindowBroadcast('local-db:messages:created', { sessionId, message: msg }, ownerStamp);+ }+ const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;try {- win.webContents.send('local-db:messages:created', { sessionId, message: msg });+ if (hasCapturedScope) {+ win.webContents.send('local-db:messages:created', { sessionId, message: msg }, ownerStamp);+ } else if (ownerStamp === undefined) {+ win.webContents.send('local-db:messages:created', { sessionId, message: msg });+ } else {+ win.webContents.send('local-db:messages:created', { sessionId, message: msg }, ownerStamp);+ }} catch {/* swallow per-window broadcast failures */}@@ -933,22 +1006,137 @@ export async function commitMessageDeletion(};}-export function broadcastMessageDeleted(payload: MessageDeletedPayload): void {- tapWindowBroadcast('local-db:messages:deleted', payload);+export function broadcastMessageDeleted(+ payload: MessageDeletedPayload,+ ownerScope?: DataOwnerBroadcastScope | null,+): void {+ const ownerStamp = ownerStampForBroadcast(ownerScope);+ if (ownerStamp === null) return;+ if (ownerScope !== undefined && ownerScope !== null) {+ broadcastTap.tapWindowBroadcast('local-db:messages:deleted', payload, ownerStamp);+ } else if (ownerStamp === undefined) {+ broadcastTap.tapWindowBroadcast('local-db:messages:deleted', payload);+ } else {+ broadcastTap.tapWindowBroadcast('local-db:messages:deleted', payload, ownerStamp);+ }+ const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;try {- win.webContents.send('local-db:messages:deleted', payload);+ if (hasCapturedScope) win.webContents.send('local-db:messages:deleted', payload, ownerStamp);+ else if (ownerStamp === undefined) win.webContents.send('local-db:messages:deleted', payload);+ else win.webContents.send('local-db:messages:deleted', payload, ownerStamp);} catch {/* swallow per-window broadcast failures */}}}+/**+ * Hide a user row that was persisted after the session crossed `/clear`.+ *+ * This is deliberately narrower than `commitMessageDeletion`: a clear-race+ * cleanup must not create a context-rebuild marker, reset the native session,+ * or touch any other turn. The row stays as a rewind tombstone so the same+ * clientId remains idempotent across a weak-link retry.+ */+export async function rewindPersistedUserMessageAfterClear(+ sessionId: string,+ clientId: string,+): Promise<void> {+ const ownerScope = captureOwnerBroadcastScope();+ if (!isOwnerBroadcastScopeCurrent(ownerScope)) return;+ const dbClient = getDbClient();+ const db = dbClient.drizzle;+ const [row] = await db+ .select({ id: messages.id, clientId: messages.clientId, content: messages.content })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sessionId),+ eq(messages.clientId, clientId),+ eq(messages.role, 'user'),+ isNull(messages.rewindAt),+ ),+ )+ .limit(1);+ if (!isOwnerBroadcastScopeCurrent(ownerScope)) return;+ if (!row) return;++ const rewoundAt = Date.now();+ const updated = await dbClient.exec(+ `UPDATE messages+ SET rewind_at = ?+ WHERE session_id = ?+ AND client_id = ?+ AND role = 'user'+ AND rewind_at IS NULL`,+ [rewoundAt, sessionId, clientId],+ );+ if (!isOwnerBroadcastScopeCurrent(ownerScope)) return;+ if (updated.changes === 0) return;++ const attachmentPaths = extractChatAttachmentPathsFromPersistedContent(row.content);+ const mediaCleanup = await Promise.allSettled(+ [...new Set([row.id, row.clientId])].map((refId) =>+ removeMediaRefs({ refKind: 'message', refId }),+ ),+ );+ for (const [index, cleanup] of mediaCleanup.entries()) {+ if (cleanup.status === 'fulfilled') continue;+ log.warn('clear-race user media ref cleanup failed', {+ sessionId,+ clientId,+ refId: [row.id, row.clientId][index],+ error: cleanup.reason instanceof Error ? cleanup.reason.message : String(cleanup.reason),+ });+ }+ const mediaHashes = collectCindyMediaHashes(row.content);+ const mediaHashCleanup = await Promise.allSettled(+ mediaHashes.map((hash) =>+ removeSessionAttachmentRefIfUnreferencedByLiveMessage({ sessionId, hash }),+ ),+ );+ for (const [index, cleanup] of mediaHashCleanup.entries()) {+ if (cleanup.status === 'fulfilled') continue;+ log.warn('clear-race session media ref reconcile failed', {+ sessionId,+ clientId,+ hash: mediaHashes[index],+ error: cleanup.reason instanceof Error ? cleanup.reason.message : String(cleanup.reason),+ });+ }+ if (attachmentPaths.length > 0) {+ try {+ const [remaining, retainedByOtherSessions] = await Promise.all([+ listSessionPersistedChatAttachmentPaths(sessionId),+ listPersistedChatAttachmentPathsForOtherSessions(sessionId),+ ]);+ const remainingSet = new Set(remaining);+ const retainedSet = new Set(retainedByOtherSessions);+ await cleanupStagedChatAttachments(+ attachmentPaths.filter(+ (filePath) => !remainingSet.has(filePath) && !retainedSet.has(filePath),+ ),+ );+ } catch (error) {+ log.warn('clear-race staged attachment cleanup failed', {+ sessionId,+ clientId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }++ broadcastMessageDeleted({ sessionId, clientId, clientIds: [clientId] }, ownerScope);+ void recomputePrRefsForSession(sessionId).catch(() => undefined);+}+export async function dismissErrorMessage(sessionId: string,clientId: string,): Promise<Message | null> {+ const ownerScope = captureOwnerBroadcastScope();const db = getDbClient().drizzle;const [row] = await db.select()@@ -965,7 +1153,9 @@ export async function dismissErrorMessage(// 窗口的内存 errorDismissed 仍为 false,stale 尾部 banner 留着还能对已忽略的// 错误重复 enqueue 续跑。peer 端 handleMessageCreatedRaw 按 clientId merge,// banner 判定即时熄灭;发起端自身的乐观更新早已生效,重复广播幂等。- if (updated) broadcastMessageRow(sessionId, updated);+ if (updated && isOwnerBroadcastScopeCurrent(ownerScope)) {+ broadcastMessageRow(sessionId, updated, ownerScope);+ }return updated;}@@ -999,6 +1189,7 @@ export async function supersedeRetriedUserTurn(sessionId: string,args: { supersededUserClientId: string; retryUserClientId: string },): Promise<string[]> {+ const ownerScope = captureOwnerBroadcastScope();const db = getDbClient().drizzle;const [oldRow] = await db.select({@@ -1047,6 +1238,7 @@ export async function supersedeRetriedUserTurn().orderBy(asc(messages.createdAt), asc(messageRowid));const clientIds = [oldRow.clientId, ...errorRows.map((r) => r.clientId)];+ if (!isOwnerBroadcastScopeCurrent(ownerScope)) return [];await db.update(messages).set({ rewindAt: Date.now() })@@ -1057,7 +1249,9 @@ export async function supersedeRetriedUserTurn(isNull(messages.rewindAt),),);- broadcastMessageDeleted({ sessionId, clientId: oldRow.clientId, clientIds });+ if (isOwnerBroadcastScopeCurrent(ownerScope)) {+ broadcastMessageDeleted({ sessionId, clientId: oldRow.clientId, clientIds }, ownerScope);+ }return clientIds;}@@ -1182,30 +1376,147 @@ export async function createMessage(* final "is this still current?" check is actually meaningful.*/shouldBroadcast?: () => boolean;+ /**+ * Optional clear-boundary compare-and-set for optimistic user sends. The+ * insert is accepted only while the session still has this exact+ * `clearedAt` value. This closes the window where `/clear` wins the DB+ * update while an already-accepted `Session.send()` is still awaiting its+ * durable user row.+ */+ expectedClearBoundaryMs?: number | null;+ /**+ * Owner scope captured before an async main-side write. A stale scope+ * must not broadcast a row into the next signed-in owner.+ */+ broadcastOwnerScope?: DataOwnerBroadcastScope | null;},): Promise<Message> {- const db = getDbClient().drizzle;- const existing = await db- .select()- .from(messages)- .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, body.clientId)))- .limit(1);- if (existing.length > 0) {- return messageToCamel(existing[0]);+ const dbClient = getDbClient();+ const db = dbClient.drizzle;+ const guarded = opts !== undefined && Object.prototype.hasOwnProperty.call(opts, 'expectedClearBoundaryMs');+ const expected = guarded ? opts?.expectedClearBoundaryMs : undefined;+ if (+ guarded &&+ expected !== null &&+ (typeof expected !== 'number' || !Number.isFinite(expected) || expected < 0)+ ) {+ throw new Error('expectedClearBoundaryMs must be null or a non-negative finite number');+ }++ // The unguarded API keeps its historical fast idempotency read. Guarded+ // optimistic sends must skip it: a pre-clear row can otherwise be returned+ // before the compare-and-set boundary is checked.+ if (!guarded) {+ const existing = await db+ .select()+ .from(messages)+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, body.clientId)))+ .limit(1);+ if (existing.length > 0) return messageToCamel(existing[0]);}const id = createId();const now = Date.now();- const insertRow = messageCreateToRow(id, sessionId, body, now);+ const visibleCreatedAt =+ guarded && expected !== null && expected !== undefined+ ? Math.max(body.createdAt ?? now, expected + 1)+ : body.createdAt ?? now;+ const insertRow = messageCreateToRow(id, sessionId, body, visibleCreatedAt);try {- await db.insert(messages).values(insertRow);+ if (guarded) {+ // Keep the session compare and message insert in one SQLite statement.+ // A separate SELECT would allow /clear to win between the check and the+ // INSERT on the DB worker.+ const inserted = await dbClient.exec(+ `INSERT INTO messages (+ id, client_id, session_id, role, content, tool_use_id,+ agent_meta, agent_kind, created_at+ )+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?+ FROM sessions AS s+ WHERE s.id = ?+ AND COALESCE(s.cleared_at, -1) = COALESCE(?, -1)+ ON CONFLICT(session_id, client_id) DO NOTHING`,+ [+ insertRow.id,+ insertRow.clientId,+ insertRow.sessionId,+ insertRow.role,+ insertRow.content,+ insertRow.toolUseId,+ insertRow.agentMeta,+ insertRow.agentKind,+ insertRow.createdAt,+ sessionId,+ expected,+ ],+ );+ if (inserted.changes === 0) {+ const [existingAfterGuard] = await db+ .select()+ .from(messages)+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, body.clientId)))+ .limit(1);+ const [sessionAfterGuard] = await db+ .select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ const actual = sessionAfterGuard?.clearedAt ?? null;+ if (+ existingAfterGuard &&+ actual === expected &&+ existingAfterGuard.rewindAt === null &&+ (expected === null || existingAfterGuard.createdAt > expected)+ ) {+ return messageToCamel(existingAfterGuard);+ }+ if (actual !== expected) {+ throw Object.assign(+ new Error(+ `REMOTE_OPTIMISTIC_INPUT_CLEARED: expectedClearBoundaryMs=${expected ?? 'null'}; currentClearBoundaryMs=${actual ?? 'null'}`,+ ),+ { code: 'REMOTE_OPTIMISTIC_INPUT_CLEARED' },+ );+ }+ throw new Error('Message insert skipped without a clear-boundary change');+ }+ } else {+ await db.insert(messages).values(insertRow);+ }} catch (err) {const after = await db.select().from(messages).where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, body.clientId))).limit(1);- if (after.length > 0) return messageToCamel(after[0]);+ if (guarded) {+ const [sessionAfterError] = await db+ .select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ const actual = sessionAfterError?.clearedAt ?? null;+ const existingAfterError = after[0];+ if (+ existingAfterError &&+ actual === expected &&+ existingAfterError.rewindAt === null &&+ (expected === null || existingAfterError.createdAt > expected)+ ) {+ return messageToCamel(existingAfterError);+ }+ if (actual !== expected) {+ throw Object.assign(+ new Error(+ `REMOTE_OPTIMISTIC_INPUT_CLEARED: expectedClearBoundaryMs=${expected ?? 'null'}; currentClearBoundaryMs=${actual ?? 'null'}`,+ ),+ { code: 'REMOTE_OPTIMISTIC_INPUT_CLEARED' },+ );+ }+ } else if (after.length > 0) {+ return messageToCamel(after[0]);+ }throw err;}const [row] = await db.select().from(messages).where(eq(messages.id, id));@@ -1216,25 +1527,38 @@ export async function createMessage(// tool_result)。生成产物(art/mivo/codex)入仓时零引用,在这里补挂// session-attachment 引用;用户附件已在发送链路 commit 过,hasRef 幂等跳过。// 传 insertRow.content(已序列化字符串)避免二次 stringify(review P2)。- // fire-and-forget:挂账失败只警告,绝不影响消息落库本身。- void commitMessageMediaRefs({- sessionId,- role: body.role,- content: insertRow.content,- }).catch((err) => {- log.warn('message media ref commit failed', {- sessionId,- clientId: body.clientId,- error: err instanceof Error ? err.message : String(err),- });- });+ const commitMediaRefs = async (): Promise<void> => {+ try {+ await commitMessageMediaRefs({+ sessionId,+ role: body.role,+ content: insertRow.content,+ });+ } catch (err) {+ log.warn('message media ref commit failed', {+ sessionId,+ clientId: body.clientId,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ };+ // Optimistic user rows carry the clear token and are written through the+ // durable FIFO. Await their media commit so a later clear/rewind cannot be+ // overtaken by a fire-and-forget session-attachment ref. Other message roles+ // stay non-blocking on the hot event path.+ const shouldAwaitMediaRefs =+ body.role === 'user' &&+ opts !== undefined &&+ Object.prototype.hasOwnProperty.call(opts, 'expectedClearBoundaryMs');+ if (shouldAwaitMediaRefs) await commitMediaRefs();+ else void commitMediaRefs();// Broadcast 给所有 renderer window — 用于 main 端创建消息 (e.g. feishu /ctr// 接管路径下 persistUserMessage / persistAssistantMessage) 时让 renderer// 的 makerChatStore push 到 in-memory state, 让消息流实时刷新。// Renderer 自己调 createMessage IPC 时也会触发这个 broadcast, 但因为它已经// 主动 push 过, 监听端按 (sessionId, clientId) dedupe 就不会重复显示。if (opts?.shouldBroadcast?.() !== false) {- broadcastMessageRow(sessionId, msg);+ broadcastMessageRow(sessionId, msg, opts?.broadcastOwnerScope);}// chat-history-embedder hook (Phase 1.2) —— fire-and-forget, 不 await。// 内部已有 enabled / cutoff / role / size 守卫; 关闭状态下零成本直接 return。@@ -1375,6 +1699,7 @@ export async function patchMessageAgentMeta(export async function broadcastMessageAgentMetaUpdate(sessionId: string,clientId: string,+ ownerScope?: DataOwnerBroadcastScope | null,): Promise<boolean> {const db = getDbClient().drizzle;const [row] = await db@@ -1389,7 +1714,8 @@ export async function broadcastMessageAgentMetaUpdate().limit(1);if (!row) return false;- broadcastMessageRow(sessionId, messageToCamel(row));+ if (!isOwnerBroadcastScopeCurrent(ownerScope)) return false;+ broadcastMessageRow(sessionId, messageToCamel(row), ownerScope);return true;}@@ -1975,15 +2301,19 @@ export async function updateAgentSwitchBoundaryContent(sessionId: string,clientId: string,content: unknown,+ ownerScope: DataOwnerBroadcastScope | null = captureOwnerBroadcastScope(),): Promise<boolean> {const updated = await updateMessageContent(sessionId, clientId, content);if (!updated) return false;- broadcastMessageRow(sessionId, updated);+ if (isOwnerBroadcastScopeCurrent(ownerScope)) {+ broadcastMessageRow(sessionId, updated, ownerScope);+ }return true;}/** vendor accepted 后持久化最新 handoff 消费位;内存 registry 不等待这笔辅助写。 */export async function markLatestAgentHandoffConsumed(sessionId: string): Promise<void> {+ const ownerScope = captureOwnerBroadcastScope();const db = getDbClient().drizzle;const [sessRow] = await db.select({ clearedAt: sessions.clearedAt })@@ -2019,7 +2349,7 @@ export async function markLatestAgentHandoffConsumed(sessionId: string): Promiseif (parsed.consumed === true) return;const nextContent = { ...parsed, consumed: true };if (boundary.role === 'agent_switch') {- await updateAgentSwitchBoundaryContent(sessionId, boundary.clientId, nextContent);+ await updateAgentSwitchBoundaryContent(sessionId, boundary.clientId, nextContent, ownerScope);return;}await getDbClient()@@ -2038,6 +2368,7 @@ export async function markLatestAgentHandoffConsumed(sessionId: string): Promiseexport async function rebroadcastAgentSwitchBoundary(sessionId: string,boundaryClientId: string,+ ownerScope: DataOwnerBroadcastScope | null = captureOwnerBroadcastScope(),): Promise<void> {const db = getDbClient().drizzle;const [row] = await db@@ -2045,5 +2376,7 @@ export async function rebroadcastAgentSwitchBoundary(.from(messages).where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, boundaryClientId))).limit(1);- if (row) broadcastMessageRow(sessionId, messageToCamel(row));+ if (row && isOwnerBroadcastScopeCurrent(ownerScope)) {+ broadcastMessageRow(sessionId, messageToCamel(row), ownerScope);+ }}diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 59335115ea..013876dabd 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -11,10 +11,7 @@ import path from 'node:path';import { ipcMain, app, BrowserWindow } from 'electron';import { eq, ne, and, desc, count, inArray, isNotNull, isNull, sql, type SQL } from 'drizzle-orm';-import {- DEFAULT_DRAFT_SESSION_TITLE,- normalizeAutoTitle,-} from '@cindy/maker-shared/session-title';+import { DEFAULT_DRAFT_SESSION_TITLE, normalizeAutoTitle } from '@cindy/maker-shared/session-title';import { getDbClient } from '../client/current';import type { DbClient } from '../client/DbClient';@@ -41,7 +38,7 @@ import { createLogger } from '../../logger';import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../../shared/sessionSource.js';import { normalizeWorkingDirForStorage } from '../../../shared/workingDir.js';import type { SessionReference } from '../../../shared/sessionReference.js';-import { tapWindowBroadcast } from '../../device-link/broadcast-tap.js';+import * as broadcastTap from '../../device-link/broadcast-tap.js';import { notifyAgentIslandSessionPatch } from '../agentIslandSessionPatch';import { noteSessionClearBoundary } from '../../messagePersistBroadcaster';import {@@ -65,15 +62,65 @@ const log = createLogger('sessions');const REMOTE_EDITABLE_META = new Set(['status', 'title', 'pinnedAt']);const initialSessionListLogged = new Set<string>();const SLOW_SESSION_LIST_MS = 250;+type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;++function captureOwnerScope(): OwnerScope {+ try {+ const capture = broadcastTap.captureDataOwnerBroadcastScope;+ return capture ? capture() : null;+ } catch {+ // Narrow unit-test mocks may intentionally expose only the legacy tap API.+ return null;+ }+}++function isOwnerScopeCurrent(scope: OwnerScope): boolean {+ if (scope === null) return true;+ try {+ const isCurrent = broadcastTap.isDataOwnerBroadcastScopeCurrent;+ return isCurrent ? isCurrent(scope) : true;+ } catch {+ return true;+ }+}++function getSafeOwnerPushStamp(): ReturnType<typeof broadcastTap.getSafeDataOwnerPushStamp> {+ try {+ return broadcastTap.getSafeDataOwnerPushStamp?.();+ } catch {+ return undefined;+ }+}/*** 广播 sessions:patched 到本机所有窗口 + device-link tap。tap 让该 patch 经 topic 路由* 转发给订阅了 `sessions` 的控制端(push 驱动:控制端 applyPatch 即时镜像,无需重拉)。*/-export function broadcastSessionPatched(sessionId: string, patch: Record<string, unknown>): void {- tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch });+export function broadcastSessionPatched(+ sessionId: string,+ patch: Record<string, unknown>,+ ownerScope?: OwnerScope,+): void {+ if (ownerScope !== undefined && !isOwnerScopeCurrent(ownerScope)) return;+ const hasCapturedScope = ownerScope !== undefined && ownerScope !== null;+ const ownerStamp = hasCapturedScope ? ownerScope.ownerStamp : getSafeOwnerPushStamp();+ if (hasCapturedScope) {+ broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);+ } else if (ownerStamp === undefined) {+ broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch });+ } else {+ broadcastTap.tapWindowBroadcast('local-db:sessions:patched', { sessionId, patch }, ownerStamp);+ }for (const w of BrowserWindow.getAllWindows()) {- if (!w.isDestroyed()) w.webContents.send('local-db:sessions:patched', { sessionId, patch });+ if (!w.isDestroyed()) {+ if (hasCapturedScope) {+ w.webContents.send('local-db:sessions:patched', { sessionId, patch }, ownerStamp);+ } else if (ownerStamp === undefined) {+ w.webContents.send('local-db:sessions:patched', { sessionId, patch });+ } else {+ w.webContents.send('local-db:sessions:patched', { sessionId, patch }, ownerStamp);+ }+ }}}@@ -215,6 +262,7 @@ export async function applyAgentSwitchToSessionRow(fastMode?: boolean;},): Promise<void> {+ const ownerScope = captureOwnerScope();const db = getDbClient().drizzle;const nextSdkSessionId = patch.sdkSessionId ?? null;const setObj: Partial<typeof sessions.$inferInsert> = {@@ -231,14 +279,19 @@ export async function applyAgentSwitchToSessionRow(}if (patch.fastMode !== undefined) setObj.fastMode = patch.fastMode;await db.update(sessions).set(setObj).where(eq(sessions.id, sessionId));- broadcastSessionPatched(sessionId, {- agentKind: patch.agentKind,- model: patch.model,- sdkSessionId: nextSdkSessionId,- ...(patch.providerId !== undefined ? { providerId: patch.providerId } : {}),- ...(patch.effort !== undefined ? { effort: patch.effort } : {}),- ...(patch.fastMode !== undefined ? { fastMode: patch.fastMode } : {}),- });+ if (!isOwnerScopeCurrent(ownerScope)) return;+ broadcastSessionPatched(+ sessionId,+ {+ agentKind: patch.agentKind,+ model: patch.model,+ sdkSessionId: nextSdkSessionId,+ ...(patch.providerId !== undefined ? { providerId: patch.providerId } : {}),+ ...(patch.effort !== undefined ? { effort: patch.effort } : {}),+ ...(patch.fastMode !== undefined ? { fastMode: patch.fastMode } : {}),+ },+ ownerScope,+ );}/** resume 停泊失败的原子 DB 回落,提交成功后再把 session 与边界新状态广播。 */@@ -247,6 +300,7 @@ export async function applyAgentSwitchResumeFallbackAtomically(boundaryClientId: string,content: unknown,): Promise<void> {+ const ownerScope = captureOwnerScope();let boundaryContent: string;try {boundaryContent = JSON.stringify(content);@@ -259,8 +313,9 @@ export async function applyAgentSwitchResumeFallbackAtomically(boundaryContent,updatedAt: Date.now(),});- broadcastSessionPatched(sessionId, { sdkSessionId: null });- await rebroadcastAgentSwitchBoundary(sessionId, boundaryClientId).catch((err) => {+ if (!isOwnerScopeCurrent(ownerScope)) return;+ broadcastSessionPatched(sessionId, { sdkSessionId: null }, ownerScope);+ await rebroadcastAgentSwitchBoundary(sessionId, boundaryClientId, ownerScope).catch((err) => {// DB 事务已提交,广播失败不能让上层误判为“原子回落失败”并重复事务。log.warn('agent-switch fallback boundary broadcast failed', {sessionId,@@ -277,6 +332,7 @@ export async function applyAgentSwitchResumeFallbackAtomically(* 返回 true = 写库后(或并发用户恰好也切到 ask 时)持久态已是 'ask'。*/export async function persistSessionPermissionModeIfAuto(sessionId: string): Promise<boolean> {+ const ownerScope = captureOwnerScope();const db = getDbClient().drizzle;await db.update(sessions)@@ -288,7 +344,9 @@ export async function persistSessionPermissionModeIfAuto(sessionId: string): Pro.where(eq(sessions.id, sessionId)).get();const applied = row?.permissionMode === 'ask';- if (applied) broadcastSessionPatched(sessionId, { permissionMode: 'ask' });+ if (applied && isOwnerScopeCurrent(ownerScope)) {+ broadcastSessionPatched(sessionId, { permissionMode: 'ask' }, ownerScope);+ }return applied;}@@ -296,6 +354,7 @@ export async function persistSessionFields(sessionId: string,patch: Record<string, unknown>,): Promise<void> {+ const ownerScope = captureOwnerScope();const clean: Record<string, unknown> = {};for (const k of Object.keys(patch)) {if (REMOTE_PERSIST_FIELDS.has(k)) clean[k] = patch[k];@@ -306,7 +365,7 @@ export async function persistSessionFields(bumpUpdatedAt: false,});await db.update(sessions).set(setObj).where(eq(sessions.id, sessionId));- broadcastSessionPatched(sessionId, clean);+ if (isOwnerScopeCurrent(ownerScope)) broadcastSessionPatched(sessionId, clean, ownerScope);}const MAX_LIMIT = 1000;@@ -415,7 +474,7 @@ export function createSessionRemoteHostIdReader(): (sessionId: string) => Promis};}-export async function getSessionRowSnapshot(id: string): Promise<{+export interface SessionRowSnapshot {status: string;title: string | null;userSendAt: number | null;@@ -428,27 +487,47 @@ export async function getSessionRowSnapshot(id: string): Promise<{orcaRole?: 'lead' | 'worker' | null;/** Collab policy gate: remote session 的 codex / claude-code 均放行。 */agentKind?: string | null;-} | null> {+ /** Authoritative `/clear` visibility boundary (unix ms). */+ clearedAt?: number | null;+}++async function selectSessionRowSnapshot(id: string): Promise<SessionRowSnapshot | null> {+ const db = getDbClient().drizzle;+ const [row] = await db+ .select({+ status: sessions.status,+ title: sessions.title,+ userSendAt: sessions.userSendAt,+ workingDir: sessions.workingDir,+ workspaceKind: sessions.workspaceKind,+ // heartbeat 任务 providerId 留空时,沿用绑定会话在聊天里选的来源(与 model+ // 留空沿用 meta.model 对称)。零新增查询,复用 runner 已并行取的这行快照。+ providerId: sessions.providerId,+ clearedAt: sessions.clearedAt,+ remoteHostId: sessions.remoteHostId,+ orcaRole: sessions.orcaRole,+ agentKind: sessions.agentKind,+ })+ .from(sessions)+ .where(eq(sessions.id, id))+ .limit(1);+ return row ?? null;+}++/**+ * 严格读取发送前的 session 行。+ *+ * 远控输入必须区分「明确不存在」和「数据库暂时不可读」:前者是可恢复之外的+ * 终态拒绝,后者则应让 renderer 保留草稿并稍后重试。普通 scheduler / 展示路径+ * 继续使用下面的 swallow 版本,避免扩大既有错误语义。+ */+export async function getSessionRowSnapshotStrict(id: string): Promise<SessionRowSnapshot | null> {+ return selectSessionRowSnapshot(id);+}++export async function getSessionRowSnapshot(id: string): Promise<SessionRowSnapshot | null> {try {- const db = getDbClient().drizzle;- const [row] = await db- .select({- status: sessions.status,- title: sessions.title,- userSendAt: sessions.userSendAt,- workingDir: sessions.workingDir,- workspaceKind: sessions.workspaceKind,- // heartbeat 任务 providerId 留空时,沿用绑定会话在聊天里选的来源(与 model- // 留空沿用 meta.model 对称)。零新增查询,复用 runner 已并行取的这行快照。- providerId: sessions.providerId,- remoteHostId: sessions.remoteHostId,- orcaRole: sessions.orcaRole,- agentKind: sessions.agentKind,- })- .from(sessions)- .where(eq(sessions.id, id))- .limit(1);- return row ?? null;+ return await selectSessionRowSnapshot(id);} catch (err) {log.warn('getSessionRowSnapshot failed', {sessionId: id,@@ -500,6 +579,7 @@ export async function getSessionFsSnapshot(id: string): Promise<{* 状态机同源,否则 retry / rollback 时会出现 DB 已 bump 但输入没有被接受的分裂。*/export async function touchUserSendInDb(id: string, atMs?: number): Promise<void> {+ const ownerScope = captureOwnerScope();const ts =typeof atMs === 'number' && Number.isFinite(atMs) && atMs > 0 ? Math.floor(atMs) : Date.now();const db = getDbClient().drizzle;@@ -538,10 +618,16 @@ export async function touchUserSendInDb(id: string, atMs?: number): Promise<void// renderer 不会乐观更新 —— 没有这条广播,被控端 sidebar 会把控制端新建的远程会话一直// 当草稿挂在项目外。经 device-link tap 同时把权威 userSendAt 推给控制端,两端收敛。// userSendAt 按 renderer 约定用 ISO 字符串(与 sessionToCamel 的 msToIso 对齐)。- broadcastSessionPatched(id, {- userSendAt: new Date(updated[0].userSendAt!).toISOString(),- updatedAt: new Date(updated[0].updatedAt).toISOString(),- });+ if (isOwnerScopeCurrent(ownerScope)) {+ broadcastSessionPatched(+ id,+ {+ userSendAt: new Date(updated[0].userSendAt!).toISOString(),+ updatedAt: new Date(updated[0].updatedAt).toISOString(),+ },+ ownerScope,+ );+ }}/** fork 出来的会话的占位标题前缀("[Fork] …" / "[Fork·已剥离] …")。 */@@ -608,7 +694,8 @@ export async function getOverwritableAutoTitle(const db = getDbClient().drizzle;const row = await selectSessionWithCount(db, id);if (!row) return null;- const agentKind = row.agentKind === 'codex' || row.agentKind === 'pi' ? row.agentKind : 'claude-code';+ const agentKind =+ row.agentKind === 'codex' || row.agentKind === 'pi' ? row.agentKind : 'claude-code';const overwritable =row.title === DEFAULT_DRAFT_SESSION_TITLE ||(!!row.parentSessionId && row.title.startsWith(FORK_PLACEHOLDER_TITLE_PREFIX)) ||@@ -645,6 +732,7 @@ export async function persistSessionTitleIfStillDraft(title: string,expectedTitle: string = DEFAULT_DRAFT_SESSION_TITLE,): Promise<boolean> {+ const ownerScope = captureOwnerScope();const cleanTitle = normalizeAutoTitle(title);if (!cleanTitle || cleanTitle === DEFAULT_DRAFT_SESSION_TITLE) return false;@@ -673,7 +761,9 @@ export async function persistSessionTitleIfStillDraft(workingDir: updated.workingDir,workspaceKind: updated.workspaceKind,});- broadcastSessionPatched(sessionId, { title: cleanTitle });+ if (isOwnerScopeCurrent(ownerScope)) {+ broadcastSessionPatched(sessionId, { title: cleanTitle }, ownerScope);+ }return true;}@@ -685,19 +775,40 @@ export async function persistSessionTitleIfStillDraft(* 补这一步。广播让被控端窗口和控制端镜像都收敛到同一个 clearedAt 边界。*/export async function clearSessionContextInDb(sessionId: string, atMs?: number): Promise<void> {+ const ownerScope = captureOwnerScope();const ts =typeof atMs === 'number' && Number.isFinite(atMs) && atMs > 0 ? Math.floor(atMs) : Date.now();const db = getDbClient().drizzle;await db.update(sessions)- .set({ sdkSessionId: null, clearedAt: ts, updatedAt: ts })+ .set({+ sdkSessionId: null,+ // Concurrent /clear calls may finish their DB awaits out of order. Keep+ // both persisted boundaries monotonic so the older completion cannot+ // make pre-clear history visible again or invalidate a newer input token.+ clearedAt: sql<number>`MAX(COALESCE(${sessions.clearedAt}, 0), ${ts})`,+ updatedAt: sql<number>`MAX(COALESCE(${sessions.updatedAt}, 0), ${ts})`,+ }).where(eq(sessions.id, sessionId));+ const [updated] = await db+ .select({ clearedAt: sessions.clearedAt, updatedAt: sessions.updatedAt })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ const effectiveClearedAt = updated?.clearedAt ?? ts;+ const effectiveUpdatedAt = updated?.updatedAt ?? effectiveClearedAt;void recomputePrRefsForSession(sessionId).catch(() => undefined);- broadcastSessionPatched(sessionId, {- sdkSessionId: null,- clearedAt: new Date(ts).toISOString(),- updatedAt: new Date(ts).toISOString(),- });+ if (isOwnerScopeCurrent(ownerScope)) {+ broadcastSessionPatched(+ sessionId,+ {+ sdkSessionId: null,+ clearedAt: new Date(effectiveClearedAt).toISOString(),+ updatedAt: new Date(effectiveUpdatedAt).toISOString(),+ },+ ownerScope,+ );+ }}export function registerSessionIpc(@@ -709,8 +820,14 @@ export function registerSessionIpc(// 只有「忽略」ack 会广播,正常收尾静默写导致快照永不纠正,任务正常结束后切回// 会话仍弹「应用退出中断」。注入而非让 sessionActiveTurn 直接 import,避免// 反向依赖成环(本文件已 import sessionActiveTurn)。- setOnSessionTurnEndedPersisted((sid, endedAt) =>- broadcastSessionPatched(sid, { lastTurnEndedAt: endedAt }),+ setOnSessionTurnEndedPersisted(+ (sid, endedAt, capturedOwnerScope) =>+ broadcastSessionPatched(+ sid,+ { lastTurnEndedAt: endedAt },+ capturedOwnerScope as OwnerScope | undefined,+ ),+ captureOwnerScope,);ipcMain.handle('local-db:sessions:list',@@ -1015,6 +1132,7 @@ export function registerSessionIpc('local-db:sessions:restore-if-archived',async (_e, id: unknown, expected: unknown) => {const sid = requireString(id, 'id');+ const ownerScope = captureOwnerScope();const identity = requireObject(expected, 'expected');const expectedWorkingDir = identity.workingDir;const expectedWorkspaceKind = identity.workspaceKind;@@ -1069,7 +1187,9 @@ export function registerSessionIpc(workingDir: updated.workingDir,workspaceKind: updated.workspaceKind,});- broadcastSessionPatched(sid, { status: 'active' });+ if (isOwnerScopeCurrent(ownerScope)) {+ broadcastSessionPatched(sid, { status: 'active' }, ownerScope);+ }scheduleWorktreeRecycleForStatusChange(sid, 'active');notifyGhostSessionStatusChange(sid, 'active', updated.workingDir);return updated;@@ -1078,6 +1198,7 @@ export function registerSessionIpc(ipcMain.handle('local-db:sessions:update', async (_e, id: unknown, patch: unknown) => {const sid = requireString(id, 'id');+ const ownerScope = captureOwnerScope();const p = requireObject(patch, 'patch');const db = getDbClient().drizzle;if (p.workspaceKind !== undefined) {@@ -1153,7 +1274,9 @@ export function registerSessionIpc(// 广播 summary:null,让已挂载的 sidebar 立即清掉旧摘要(codex review)——renderer 的// clearSession 乐观 patch 只带 sdkSessionId/clearedAt、不含 summary,本 update handler// 也不另发 patched;不广播则卡片/rail 会继续显示 clear 前摘要直到一次全量 refresh。- broadcastSessionPatched(sid, { summary: null });+ if (isOwnerScopeCurrent(ownerScope)) {+ broadcastSessionPatched(sid, { summary: null }, ownerScope);+ }void recomputePrRefsForSession(sid).catch(() => undefined);}// workingDir 实际变化的本机 cc 会话:迁移 CLI 转录后再查询返回行/广播,保证@@ -1203,7 +1326,9 @@ export function registerSessionIpc(await upsertRecentWorkdir(row.workingDir, Date.now());}if (projectTargetChanged || settingsChanged || titleChanged || p.pinnedAt !== undefined) {- broadcastSessionPatched(sid, broadcastPatch);+ if (isOwnerScopeCurrent(ownerScope)) {+ broadcastSessionPatched(sid, broadcastPatch, ownerScope);+ }}// sidebar-card-mode: 会话被置顶那一刻补生成任务摘要(turn-done 路径只覆盖// "置顶后又跑过 turn"的会话)。动态 import 避免 localDb → maker-host 的静态@@ -1264,6 +1389,7 @@ export async function patchSessionMetaInDb(pinnedAt?: string | null;},): Promise<ReturnType<typeof sessionToCamel>> {+ const ownerScope = captureOwnerScope();for (const k of Object.keys(patch)) {if (!REMOTE_EDITABLE_META.has(k)) {throwIpcError('INVALID_PARAMS', `field not allowed in patch-meta: ${k}`);@@ -1337,7 +1463,7 @@ export async function patchSessionMetaInDb(// - sessionsStore.onPatched → patchLocal,即时反映到 sidebar(删/归档移出 active 桶、改名/置顶刷新);// - CCAgentSessionView.onPatched → 合并进 serverSession。// 经 tap 转发:订阅了该被控端 `sessions` topic 的控制端也即时收到这条 patched(push 驱动镜像)。- broadcastSessionPatched(sessionId, patch);+ if (isOwnerScopeCurrent(ownerScope)) broadcastSessionPatched(sessionId, patch, ownerScope);return updated;}@@ -1361,6 +1487,7 @@ export async function renameSessionTitlesInDb(dryRun: boolean,): Promise<RenameSessionMetaItem[]> {if (changes.length === 0) return [];+ const ownerScope = captureOwnerScope();const db = getDbClient().drizzle;const ids = changes.map((change) => change.sessionId);@@ -1415,12 +1542,13 @@ export async function renameSessionTitlesInDb(throw err;});+ if (!isOwnerScopeCurrent(ownerScope)) return applied;for (const item of applied) {notifyAgentIslandSessionPatch(item.sessionId, {title: item.newTitle,workingDir: item.workingDir,});- broadcastSessionPatched(item.sessionId, { title: item.newTitle });+ broadcastSessionPatched(item.sessionId, { title: item.newTitle }, ownerScope);}return applied;}@@ -1447,6 +1575,7 @@ export async function setSessionsStatusInDb(status: 'active' | 'archived',): Promise<SessionStatusChangeRow[]> {if (sessionIds.length === 0) return [];+ const ownerScope = captureOwnerScope();const applied = await getDbClient().tx('sessions.setStatus', { sessionIds, status }).catch((err) => {@@ -1457,6 +1586,13 @@ export async function setSessionsStatusInDb(}throw err;});+ if (!isOwnerScopeCurrent(ownerScope))+ return applied.map((item) => ({+ sessionId: item.sessionId,+ title: item.title,+ workingDir: item.workingDir,+ status: item.status,+ }));for (const item of applied) {notifyAgentIslandSessionPatch(item.sessionId, {status: item.status,@@ -1464,7 +1600,7 @@ export async function setSessionsStatusInDb(workingDir: item.workingDir,workspaceKind: item.workspaceKind,});- broadcastSessionPatched(item.sessionId, { status: item.status });+ broadcastSessionPatched(item.sessionId, { status: item.status }, ownerScope);scheduleWorktreeRecycleForStatusChange(item.sessionId, item.status);notifyGhostSessionStatusChange(item.sessionId, item.status, item.workingDir);removeHookAttachmentDir(item.sessionId, item.status);@@ -1667,7 +1803,10 @@ export async function setSessionProviderIdInDb(}/** Persist the provider-facing source for a newly-created shared IM session. */-export async function setSessionSourceInDb(sessionId: string, source: 'telegram' | 'x'): Promise<void> {+export async function setSessionSourceInDb(+ sessionId: string,+ source: 'telegram' | 'x',+): Promise<void> {try {const db = getDbClient().drizzle;await db.update(sessions).set({ source }).where(eq(sessions.id, sessionId));diff --git a/apps/desktop/src/main/localDb/sessionActiveTurn.ts b/apps/desktop/src/main/localDb/sessionActiveTurn.tsindex 68da95664b..3eb1628d0f 100644--- a/apps/desktop/src/main/localDb/sessionActiveTurn.ts+++ b/apps/desktop/src/main/localDb/sessionActiveTurn.ts@@ -77,13 +77,41 @@ export function freezeSessionActiveTurnMarkers(): void {* 因为 ipc/sessions.ts 已 import 本模块(ack 路径),反向依赖会成环;注入也让单测* 无需 mock electron。回调异常吞掉,绝不影响写链。*/-let _onTurnEndedPersisted: ((sessionId: string, endedAt: number) => void) | null = null;+let _onTurnEndedPersisted:+ | ((sessionId: string, endedAt: number, context: unknown) => void)+ | null = null;+let _captureTurnEndedPersistedContext: (() => unknown) | null = null;/** 注入 ended 落库后的广播回调(传 null 清除;测试与 registerSessionIpc 用)。 */export function setOnSessionTurnEndedPersisted(- fn: ((sessionId: string, endedAt: number) => void) | null,+ fn: ((sessionId: string, endedAt: number, context: unknown) => void) | null,+ captureContext: (() => unknown) | null = null,): void {_onTurnEndedPersisted = fn;+ _captureTurnEndedPersistedContext = fn ? captureContext : null;+}++function captureTurnEndedPersistedContext(): unknown {+ try {+ return _captureTurnEndedPersistedContext?.();+ } catch (err) {+ log.warn('capture turn-ended notify context failed', {+ error: err instanceof Error ? err.message : String(err),+ });+ return undefined;+ }+}++function notifyTurnEndedPersisted(sessionId: string, endedAt: number, context: unknown): void {+ if (!_onTurnEndedPersisted) return;+ try {+ _onTurnEndedPersisted(sessionId, endedAt, context);+ } catch (notifyErr) {+ log.warn('onTurnEndedPersisted notify failed', {+ sessionId,+ error: notifyErr instanceof Error ? notifyErr.message : String(notifyErr),+ });+ }}/** started / ended 的 per-session 写链:只做 UPDATE 排队保序,无读改写。 */@@ -131,7 +159,12 @@ export function markSessionTurnStarted(sessionId: string): void {*/export function markSessionTurnEnded(sessionId: string, endedAtOverride?: number): void {if (_quitFrozen) return;- enqueueEndedWrite(sessionId, Math.min(endedAtOverride ?? Date.now(), Date.now()));+ const notifyContext = captureTurnEndedPersistedContext();+ enqueueEndedWrite(+ sessionId,+ Math.min(endedAtOverride ?? Date.now(), Date.now()),+ notifyContext,+ );}/**@@ -146,9 +179,10 @@ export function markSessionTurnEnded(sessionId: string, endedAtOverride?: numberexport function markSessionTurnEndedAfterBarrier(sessionId: string, barrier: Promise<unknown>): void {if (_quitFrozen) return;const endedAt = Date.now();+ const notifyContext = captureTurnEndedPersistedContext();void barrier.then(- () => enqueueEndedWrite(sessionId, endedAt),- () => enqueueEndedWrite(sessionId, endedAt),+ () => enqueueEndedWrite(sessionId, endedAt, notifyContext),+ () => enqueueEndedWrite(sessionId, endedAt, notifyContext),);}@@ -166,7 +200,8 @@ export async function ackSessionTurnEndedDurable(endedAtOverride?: number,): Promise<number> {const endedAt = Math.min(endedAtOverride ?? Date.now(), Date.now());- if (!_quitFrozen) await enqueueEndedWrite(sessionId, endedAt);+ const notifyContext = captureTurnEndedPersistedContext();+ if (!_quitFrozen) await enqueueEndedWrite(sessionId, endedAt, notifyContext);return endedAt;}@@ -188,6 +223,7 @@ export async function ackSessionTurnEndedIfUnchanged(): Promise<boolean> {if (_quitFrozen) return false;const endedAt = Date.now();+ const notifyContext = captureTurnEndedPersistedContext();let landed = false;await chainWrite(sessionId, async () => {try {@@ -209,14 +245,7 @@ export async function ackSessionTurnEndedIfUnchanged(row.endedAt != null &&row.endedAt >= expectedStartedAt;if (landed && _onTurnEndedPersisted && row?.endedAt != null) {- try {- _onTurnEndedPersisted(sessionId, row.endedAt);- } catch (notifyErr) {- log.warn('onTurnEndedPersisted notify failed', {- sessionId,- error: notifyErr instanceof Error ? notifyErr.message : String(notifyErr),- });- }+ notifyTurnEndedPersisted(sessionId, row.endedAt, notifyContext);}} catch (err) {log.warn('ackSessionTurnEndedIfUnchanged failed', {@@ -229,7 +258,7 @@ export async function ackSessionTurnEndedIfUnchanged(}/** ended 写入的唯一落库实现:MAX 守卫 + per-session 链,见 markSessionTurnEnded 注释。 */-function enqueueEndedWrite(sessionId: string, endedAt: number): Promise<void> {+function enqueueEndedWrite(sessionId: string, endedAt: number, notifyContext: unknown): Promise<void> {return chainWrite(sessionId, async () => {try {const db = getDbClient().drizzle;@@ -246,14 +275,7 @@ function enqueueEndedWrite(sessionId: string, endedAt: number): Promise<void> {.from(sessions).where(eq(sessions.id, sessionId));if (row?.endedAt != null) {- try {- _onTurnEndedPersisted(sessionId, row.endedAt);- } catch (notifyErr) {- log.warn('onTurnEndedPersisted notify failed', {- sessionId,- error: notifyErr instanceof Error ? notifyErr.message : String(notifyErr),- });- }+ notifyTurnEndedPersisted(sessionId, row.endedAt, notifyContext);}}} catch (err) {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex afa6f18d03..3913516c5e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -101,19 +101,24 @@ async function persistQueuedUserMessage(const persist = sendOpts.persistUserMessage;if (!persist) return;(persist as { onPersisting?: () => void }).onPersisting?.();- await mocks.createMessage(- sessionId,- {- clientId: persist.clientId,- role: 'user',- content: persist.content,- agentMeta: {- delivery: persist.delivery,- sdkSessionId: persist.sdkSessionId,+ try {+ await mocks.createMessage(+ sessionId,+ {+ clientId: persist.clientId,+ role: 'user',+ content: persist.content,+ agentMeta: {+ delivery: persist.delivery,+ sdkSessionId: persist.sdkSessionId,+ },},- },- { shouldBroadcast: persist.shouldBroadcast },- );+ { shouldBroadcast: persist.shouldBroadcast },+ );+ } catch (err) {+ (persist as { onPersistFailed?: () => void }).onPersistFailed?.();+ throw err;+ }await persist.onPersisted?.();}@@ -152,11 +157,11 @@ function sessionRunningError(): Error & { code: string } {});}-function unsupportedChatBridgeImageError(- feature = "input content part 'input_image'",-): string {- return 'unexpected status 400 Bad Request: Responses feature is not supported by the '- + `Chat Completions bridge: ${feature}, url: http://127.0.0.1/v1/responses`;+function unsupportedChatBridgeImageError(feature = "input content part 'input_image'"): string {+ return (+ 'unexpected status 400 Bad Request: Responses feature is not supported by the ' ++ `Chat Completions bridge: ${feature}, url: http://127.0.0.1/v1/responses`+ );}function createHarness() {@@ -166,26 +171,53 @@ function createHarness() {let agentKind: AgentInputCreateOpts['agentKind'] | null = 'claude-code';const projections: AgentInputProjection[] = [];- const sendToAgent = vi.fn<AgentInputCoordinatorDeps['sendToAgent']>(async (sessionId, _message, _createOpts, sendOpts) => {- await persistQueuedUserMessage(sessionId, sendOpts);- running = true;- return sendSuccess();- });+ const sendToAgent = vi.fn<AgentInputCoordinatorDeps['sendToAgent']>(+ async (sessionId, _message, _createOpts, sendOpts) => {+ await persistQueuedUserMessage(sessionId, sendOpts);+ running = true;+ return sendSuccess();+ },+ );const steerToAgent = vi.fn<AgentInputCoordinatorDeps['steerToAgent']>(async () => {});const abortSession = vi.fn<AgentInputCoordinatorDeps['abortSession']>(async () => {});- const getSdkSessionId = vi.fn<AgentInputCoordinatorDeps['getSdkSessionId']>(async () => 'sdk-session');- const reconcileTurnIdle = vi.fn<NonNullable<AgentInputCoordinatorDeps['reconcileTurnIdle']>>(() => false);- const beforeDispatchUserTurn = vi.fn<NonNullable<AgentInputCoordinatorDeps['beforeDispatchUserTurn']>>(() => {});- const onUndispatchedUserTurn = vi.fn<NonNullable<AgentInputCoordinatorDeps['onUndispatchedUserTurn']>>(() => {});- const onAcceptedQueuedMessage = vi.fn<NonNullable<AgentInputCoordinatorDeps['onAcceptedQueuedMessage']>>(() => {});- const onDispatchedUserTurn = vi.fn<NonNullable<AgentInputCoordinatorDeps['onDispatchedUserTurn']>>(() => {});+ const getSdkSessionId = vi.fn<AgentInputCoordinatorDeps['getSdkSessionId']>(+ async () => 'sdk-session',+ );+ const reconcileTurnIdle = vi.fn<NonNullable<AgentInputCoordinatorDeps['reconcileTurnIdle']>>(+ () => false,+ );+ const beforeDispatchUserTurn = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['beforeDispatchUserTurn']>+ >(() => {});+ const onUndispatchedUserTurn = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['onUndispatchedUserTurn']>+ >(() => {});+ const onUserMessagePersisting = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['onUserMessagePersisting']>+ >(() => {});+ const onUserMessagePersisted = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['onUserMessagePersisted']>+ >(() => {});+ const onUserMessagePersistenceFailed = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['onUserMessagePersistenceFailed']>+ >(() => {});+ const onAcceptedQueuedMessage = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['onAcceptedQueuedMessage']>+ >(() => {});+ const onDispatchedUserTurn = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['onDispatchedUserTurn']>+ >(() => {});// host 是否接管自愈。null = 不接管(走常规错误呈现),与「没装自愈」的行为一致;// 非 null 时返回的就是要透到 UI 的展示信息(原因 + 本轮次数 + 会话累计)。- let resumableTurnErrorTakeover: { error?: string; attempt: number; maxAttempts: number; sessionTotal: number } | null =- null;- const onResumableTurnError = vi.fn<NonNullable<AgentInputCoordinatorDeps['onResumableTurnError']>>(- () => resumableTurnErrorTakeover,- );+ let resumableTurnErrorTakeover: {+ error?: string;+ attempt: number;+ maxAttempts: number;+ sessionTotal: number;+ } | null = null;+ const onResumableTurnError = vi.fn<+ NonNullable<AgentInputCoordinatorDeps['onResumableTurnError']>+ >(() => resumableTurnErrorTakeover);// 纯判定(无副作用):这条 error 有没有可能被接管。host 侧接的是 isInterruptedTurnError,// 这里默认认所有带 sdkError='server_error' 的,够表达"候选 / 非候选"两种分支。let resumableTurnErrorCandidate: (signals: { sdkError?: string }) => boolean = (signals) =>@@ -196,7 +228,8 @@ function createHarness() {const onResumableTurnErrorDiscarded = vi.fn<NonNullable<AgentInputCoordinatorDeps['onResumableTurnErrorDiscarded']>>(() => {});- const noteSessionClearBoundary = vi.fn<NonNullable<AgentInputCoordinatorDeps['noteSessionClearBoundary']>>();+ const noteSessionClearBoundary =+ vi.fn<NonNullable<AgentInputCoordinatorDeps['noteSessionClearBoundary']>>();const resolveSessionReferences = vi.fn<NonNullable<AgentInputCoordinatorDeps['resolveSessionReferences']>>(async () => []);@@ -213,13 +246,12 @@ function createHarness() {NonNullable<AgentInputCoordinatorDeps['onUserMessageRewritten']>>(() => {});let hasAssistantProgressAfter:- | ((sessionId: string, userClientId: string) => Promise<boolean>)- | null = null;+ ((sessionId: string, userClientId: string) => Promise<boolean>) | null = null;let loadQueueSnapshot: ((sessionId: string) => Promise<AgentInputQueuedMessage[]>) | null = null;- let getPersistedClientIds: ((sessionId: string, clientIds: string[]) => Promise<Set<string>>) | undefined;- const persistQueueSnapshot = vi.fn<- NonNullable<AgentInputCoordinatorDeps['persistQueueSnapshot']>- >();+ let getPersistedClientIds:+ ((sessionId: string, clientIds: string[]) => Promise<Set<string>>) | undefined;+ const persistQueueSnapshot =+ vi.fn<NonNullable<AgentInputCoordinatorDeps['persistQueueSnapshot']>>();const onUiRetry = vi.fn<NonNullable<AgentInputCoordinatorDeps['onUiRetry']>>(() => {});const onAutomaticEnqueue = vi.fn<NonNullable<AgentInputCoordinatorDeps['onAutomaticEnqueue']>@@ -228,9 +260,9 @@ function createHarness() {const onDiscardedQueuedMessage = vi.fn<NonNullable<AgentInputCoordinatorDeps['onDiscardedQueuedMessage']>>(() => {});- const onRejectedUserTurn = vi.fn<- NonNullable<AgentInputCoordinatorDeps['onRejectedUserTurn']>- >(() => {});+ const onRejectedUserTurn = vi.fn<NonNullable<AgentInputCoordinatorDeps['onRejectedUserTurn']>>(+ () => {},+ );const supersedeRetriedUserTurn = vi.fn<NonNullable<AgentInputCoordinatorDeps['supersedeRetriedUserTurn']>>(async () => []);@@ -256,6 +288,9 @@ function createHarness() {: Promise.resolve(false),beforeDispatchUserTurn,onUndispatchedUserTurn,+ onUserMessagePersisting,+ onUserMessagePersisted,+ onUserMessagePersistenceFailed,onAcceptedQueuedMessage,onDispatchedUserTurn,onResumableTurnError,@@ -273,7 +308,9 @@ function createHarness() {loadQueueSnapshot: (sessionId) =>loadQueueSnapshot ? loadQueueSnapshot(sessionId) : Promise.resolve([]),getPersistedClientIds: (sessionId, clientIds) =>- getPersistedClientIds ? getPersistedClientIds(sessionId, clientIds) : Promise.resolve(new Set()),+ getPersistedClientIds+ ? getPersistedClientIds(sessionId, clientIds)+ : Promise.resolve(new Set()),});return {@@ -285,6 +322,9 @@ function createHarness() {reconcileTurnIdle,beforeDispatchUserTurn,onUndispatchedUserTurn,+ onUserMessagePersisting,+ onUserMessagePersisted,+ onUserMessagePersistenceFailed,onAcceptedQueuedMessage,onDispatchedUserTurn,onResumableTurnError,@@ -317,9 +357,7 @@ function createHarness() {},onUserMessageBlocked,onUserMessageRewritten,- setScreenUserMessage(- fn: NonNullable<AgentInputCoordinatorDeps['screenUserMessage']> | null,- ) {+ setScreenUserMessage(fn: NonNullable<AgentInputCoordinatorDeps['screenUserMessage']> | null) {screenUserMessage = fn;},setHasAssistantProgressAfter(@@ -329,9 +367,7 @@ function createHarness() {},/** 模拟 host 决定接管自愈(判定命中 + 额度允许);传 null = 不接管。 */setResumableTurnErrorTakeover(- value:- | { error?: string; attempt: number; maxAttempts: number; sessionTotal: number }- | null,+ value: { error?: string; attempt: number; maxAttempts: number; sessionTotal: number } | null,) {resumableTurnErrorTakeover = value;},@@ -340,9 +376,7 @@ function createHarness() {resumableTurnErrorCandidate = fn;},persistQueueSnapshot,- setLoadQueueSnapshot(- fn: ((sessionId: string) => Promise<AgentInputQueuedMessage[]>) | null,- ) {+ setLoadQueueSnapshot(fn: ((sessionId: string) => Promise<AgentInputQueuedMessage[]>) | null) {loadQueueSnapshot = fn;},setGetPersistedClientIds(@@ -407,7 +441,9 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {expect(h.resolveSessionReferences).not.toHaveBeenCalled();expect(h.sendToAgent).toHaveBeenCalledTimes(1);- expect(JSON.stringify(h.sendToAgent.mock.calls[0]?.[1])).toContain('authoritative remote history');+ expect(JSON.stringify(h.sendToAgent.mock.calls[0]?.[1])).toContain(+ 'authoritative remote history',+ );expect(mocks.createMessage.mock.calls[0]?.[1]).toMatchObject({content: expect.stringContaining('"sessionReferences"'),});@@ -415,10 +451,13 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {it('fails closed instead of interpreting a controller ref against local SQLite', async () => {const h = createHarness();- h.coordinator.enqueue('target-session', makeItem('quoted-2', 'compare cindy://session/source-session', {- sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],- sessionReferencesRequireTrustedSnapshot: true,- }));+ h.coordinator.enqueue(+ 'target-session',+ makeItem('quoted-2', 'compare cindy://session/source-session', {+ sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],+ sessionReferencesRequireTrustedSnapshot: true,+ }),+ );await flush();expect(h.resolveSessionReferences).not.toHaveBeenCalled();@@ -429,11 +468,14 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {it('does not expose quoted history bodies through renderer projections', () => {const h = createHarness();h.setRunning(true);- const projection = h.coordinator.enqueue('target-session', makeItem('quoted-3', 'queued quote', {- sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],- trustedSessionReferenceContexts: [trustedContext],- sessionReferencesRequireTrustedSnapshot: true,- }));+ const projection = h.coordinator.enqueue(+ 'target-session',+ makeItem('quoted-3', 'queued quote', {+ sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],+ trustedSessionReferenceContexts: [trustedContext],+ sessionReferencesRequireTrustedSnapshot: true,+ }),+ );expect(projection.pendingQueue[0]?.sessionRefs).toHaveLength(1);expect(projection.pendingQueue[0]?.trustedSessionReferenceContexts).toBeUndefined();@@ -445,20 +487,27 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {const h = createHarness();const sid = 'target-session';h.setRunning(true);- const projection = h.coordinator.enqueue(sid, makeItem('quoted-steer', 'queued quote', {- sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],- trustedSessionReferenceContexts: [trustedContext],- sessionReferencesRequireTrustedSnapshot: true,- }));+ const projection = h.coordinator.enqueue(+ sid,+ makeItem('quoted-steer', 'queued quote', {+ sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],+ trustedSessionReferenceContexts: [trustedContext],+ sessionReferencesRequireTrustedSnapshot: true,+ }),+ );const projectedItem = projection.pendingQueue[0];expect(projectedItem?.trustedSessionReferenceContexts).toBeUndefined();expect(projectedItem?.sessionReferencesRequireTrustedSnapshot).toBeUndefined();- await expect(h.coordinator.steer(sid, projectedItem!, { removeFromQueue: true })).resolves.toBe(true);+ await expect(h.coordinator.steer(sid, projectedItem!, { removeFromQueue: true })).resolves.toBe(+ true,+ );expect(h.resolveSessionReferences).not.toHaveBeenCalled();expect(h.steerToAgent).toHaveBeenCalledTimes(1);- expect(JSON.stringify(h.steerToAgent.mock.calls[0]?.[1])).toContain('authoritative remote history');+ expect(JSON.stringify(h.steerToAgent.mock.calls[0]?.[1])).toContain(+ 'authoritative remote history',+ );expect(latestProjection(h.projections).pendingQueue).toHaveLength(0);});@@ -467,10 +516,13 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {const sid = 'target-session';h.setRunning(true);const refs = [{ sessionId: 'source-session', deviceId: 'source-device' }];- h.coordinator.enqueue(sid, makeItem('quoted-restored', 'queued quote', {- sessionRefs: refs,- sessionReferencesRequireTrustedSnapshot: true,- }));+ h.coordinator.enqueue(+ sid,+ makeItem('quoted-restored', 'queued quote', {+ sessionRefs: refs,+ sessionReferencesRequireTrustedSnapshot: true,+ }),+ );const incoming = makeItem('quoted-restored', 'queued quote', {sessionRefs: refs,@@ -481,7 +533,9 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {expect(h.resolveSessionReferences).not.toHaveBeenCalled();expect(h.steerToAgent).toHaveBeenCalledTimes(1);- expect(JSON.stringify(h.steerToAgent.mock.calls[0]?.[1])).toContain('authoritative remote history');+ expect(JSON.stringify(h.steerToAgent.mock.calls[0]?.[1])).toContain(+ 'authoritative remote history',+ );});it('does not pass trusted reference bodies to crash-recovery persistence', async () => {@@ -490,11 +544,14 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {await h.coordinator.ensureQueueRestored(sid);h.setRunning(true);- h.coordinator.enqueue(sid, makeItem('quoted-persist', 'queued quote', {- sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],- trustedSessionReferenceContexts: [trustedContext],- sessionReferencesRequireTrustedSnapshot: true,- }));+ h.coordinator.enqueue(+ sid,+ makeItem('quoted-persist', 'queued quote', {+ sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],+ trustedSessionReferenceContexts: [trustedContext],+ sessionReferencesRequireTrustedSnapshot: true,+ }),+ );await flush();const persisted = h.persistQueueSnapshot.mock.calls.at(-1)?.[1][0];@@ -511,11 +568,14 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {ghostId: 'ghost-1',ghostName: 'rewrite-test',}));- h.coordinator.enqueue('target-session', makeItem('quoted-4', 'compare cindy://session/source-session', {- sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],- trustedSessionReferenceContexts: [trustedContext],- sessionReferencesRequireTrustedSnapshot: true,- }));+ h.coordinator.enqueue(+ 'target-session',+ makeItem('quoted-4', 'compare cindy://session/source-session', {+ sessionRefs: [{ sessionId: 'source-session', deviceId: 'source-device' }],+ trustedSessionReferenceContexts: [trustedContext],+ sessionReferencesRequireTrustedSnapshot: true,+ }),+ );await flush();expect(h.resolveSessionReferences).toHaveBeenCalledTimes(1);@@ -525,17 +585,20 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {it('sends a foreign session link as ordinary Agent text when history enrichment fails', async () => {const h = createHarness();- h.resolveSessionReferences.mockRejectedValueOnce(new Error('session belongs to another account'));+ h.resolveSessionReferences.mockRejectedValueOnce(+ new Error('session belongs to another account'),+ );const text = 'inspect cindy://session/foreign-session';- h.coordinator.enqueue('target-session', makeItem('quoted-foreign', text, {- sessionRefs: [{ sessionId: 'foreign-session' }],- }));+ h.coordinator.enqueue(+ 'target-session',+ makeItem('quoted-foreign', text, {+ sessionRefs: [{ sessionId: 'foreign-session' }],+ }),+ );await flush();- expect(h.resolveSessionReferences).toHaveBeenCalledWith([- { sessionId: 'foreign-session' },- ]);+ expect(h.resolveSessionReferences).toHaveBeenCalledWith([{ sessionId: 'foreign-session' }]);expect(h.sendToAgent).toHaveBeenCalledWith('target-session',{ type: 'user', content: text },@@ -558,9 +621,13 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {});h.coordinator.enqueue('target-session', item);- h.coordinator.updateContent('target-session', item.clientId, makeItem(item.clientId, 'compare cindy://session/controller', {- sessionRefs: [],- }));+ h.coordinator.updateContent(+ 'target-session',+ item.clientId,+ makeItem(item.clientId, 'compare cindy://session/controller', {+ sessionRefs: [],+ }),+ );const updated = latestProjection(h.projections).pendingQueue[0];expect(updated?.sessionRefs).toBeUndefined();@@ -610,7 +677,10 @@ describe('AgentInputCoordinator send transaction', () => {h.sendToAgent.mockImplementationOnce(async () => {h.setRunning(true);- return hostSendFailure('SESSION_RUNNING', '[SESSION_RUNNING] Session is already running a turn');+ return hostSendFailure(+ 'SESSION_RUNNING',+ '[SESSION_RUNNING] Session is already running a turn',+ );});h.coordinator.enqueue(sid, first);@@ -651,7 +721,8 @@ describe('AgentInputCoordinator send transaction', () => {'CREDENTIAL_SWITCH_BUSY','CREDENTIAL_SWITCH_BUSY: Cannot switch Codex credential mode (oauth-bearer -> gateway-key) while local Codex session(s) are busy: other-session',{ busySessionIds: ['other-session'] },- ));+ ),+ );h.coordinator.enqueue(sid, first);await flush();@@ -718,7 +789,8 @@ describe('AgentInputCoordinator send transaction', () => {h.sendToAgent.mockImplementation(async () =>hostSendFailure('CREDENTIAL_SWITCH_BUSY', 'CREDENTIAL_SWITCH_BUSY: busy', {busySessionIds: ['other-session'],- }));+ }),+ );h.coordinator.enqueue(sid, makeItem('q-1', 'first'));await flush();@@ -762,11 +834,10 @@ describe('AgentInputCoordinator send transaction', () => {const first = makeItem('q-1', 'first');h.sendToAgent.mockImplementationOnce(async () =>- hostSendFailure(- 'CREDENTIAL_SWITCH_BUSY',- 'CREDENTIAL_SWITCH_BUSY: busy',- { busySessionIds: ['other-session'] },- ));+ hostSendFailure('CREDENTIAL_SWITCH_BUSY', 'CREDENTIAL_SWITCH_BUSY: busy', {+ busySessionIds: ['other-session'],+ }),+ );h.coordinator.enqueue(sid, first);await flush();@@ -795,7 +866,8 @@ describe('AgentInputCoordinator send transaction', () => {h.sendToAgent.mockImplementation(async () =>hostSendFailure('CREDENTIAL_SWITCH_BUSY', 'CREDENTIAL_SWITCH_BUSY: busy', {busySessionIds: ['other-session'],- }));+ }),+ );h.coordinator.enqueue(sid, makeItem('q-1', 'first'));await flush();@@ -1073,7 +1145,9 @@ describe('AgentInputCoordinator send transaction', () => {h.coordinator.onTurnEvent(sid, 'done');await flush();projection = latestProjection(h.projections);- expect(projection.error, 'paired done must NOT wipe the terminal error projection').toBe('claude turn failed');+ expect(projection.error, 'paired done must NOT wipe the terminal error projection').toBe(+ 'claude turn failed',+ );});it('falls back and drains after a Codex terminal error when no done follows', async () => {@@ -1457,10 +1531,13 @@ describe('AgentInputCoordinator send transaction', () => {const sid = 'orca-origin';h.setRunning(true);- h.coordinator.enqueue(sid, makeItem('q-orca', '[From Orca Lead]\nhello', {- persistedContent: JSON.stringify({ orcaSource: 'lead', content: 'hello' }),- origin: { kind: 'orca', senderLabel: 'Lead', displayText: 'hello' },- }));+ h.coordinator.enqueue(+ sid,+ makeItem('q-orca', '[From Orca Lead]\nhello', {+ persistedContent: JSON.stringify({ orcaSource: 'lead', content: 'hello' }),+ origin: { kind: 'orca', senderLabel: 'Lead', displayText: 'hello' },+ }),+ );expect(latestProjection(h.projections).pendingQueue[0]?.origin).toEqual({kind: 'orca',@@ -1505,7 +1582,7 @@ describe('AgentInputCoordinator send transaction', () => {h.coordinator.enqueue(sid, item);await flush();- expect(h.onAcceptedQueuedMessage).toHaveBeenCalledWith(sid, item);+ expect(h.onAcceptedQueuedMessage).toHaveBeenCalledWith(sid, expect.objectContaining(item));});it('awaits async onAcceptedQueuedMessage side effects before the accepted boundary resolves', async () => {@@ -1526,9 +1603,12 @@ describe('AgentInputCoordinator send transaction', () => {return sendSuccess();});- h.coordinator.enqueue(sid, makeItem('q-await', 'hello', {- origin: { kind: 'orca', senderLabel: 'Lead' },- }));+ h.coordinator.enqueue(+ sid,+ makeItem('q-await', 'hello', {+ origin: { kind: 'orca', senderLabel: 'Lead' },+ }),+ );await flush();expect(callbackDoneAtSendResolve).toBe(true);@@ -1556,7 +1636,7 @@ describe('AgentInputCoordinator send transaction', () => {h.coordinator.enqueue(sid, item);await flush();- expect(h.beforeDispatchUserTurn).toHaveBeenCalledWith(sid, item);+ expect(h.beforeDispatchUserTurn).toHaveBeenCalledWith(sid, expect.objectContaining(item));expect(events).toEqual(['before-dispatch:start','before-dispatch:end',@@ -1574,20 +1654,20 @@ describe('AgentInputCoordinator send transaction', () => {const h = createHarness();const sid = 'orca-stop-drop';h.setRunning(true);- h.coordinator.enqueue(sid, makeItem('q-orca', 'hello', {- origin: { kind: 'orca', senderLabel: 'developer', displayText: 'hello' },- }));+ h.coordinator.enqueue(+ sid,+ makeItem('q-orca', 'hello', {+ origin: { kind: 'orca', senderLabel: 'developer', displayText: 'hello' },+ }),+ );h.coordinator.stop(sid);- expect(mocks.logger.warn).toHaveBeenCalledWith(- 'dropping queued Orca message on stop',- {- sessionId: sid,- clientId: 'q-orca',- senderLabel: 'developer',- },- );+ expect(mocks.logger.warn).toHaveBeenCalledWith('dropping queued Orca message on stop', {+ sessionId: sid,+ clientId: 'q-orca',+ senderLabel: 'developer',+ });});it('persists a user bubble only after maker-core accepts the turn', async () => {@@ -1689,7 +1769,9 @@ describe('AgentInputCoordinator send transaction', () => {const sid = 'compact-queued-during-active-turn';h.setRunning(true);- await h.coordinator.compact(sid, makeItem('q-compact', 'ignored').createOpts, { userName: 'Carol' });+ await h.coordinator.compact(sid, makeItem('q-compact', 'ignored').createOpts, {+ userName: 'Carol',+ });await flush();expect(h.sendToAgent).not.toHaveBeenCalled();@@ -1755,7 +1837,10 @@ describe('AgentInputCoordinator send transaction', () => {h.sendToAgent.mockImplementationOnce(async () => {h.setRunning(true);- return hostSendFailure('SESSION_RUNNING', '[SESSION_RUNNING] Session is already running a turn');+ return hostSendFailure(+ 'SESSION_RUNNING',+ '[SESSION_RUNNING] Session is already running a turn',+ );});await h.coordinator.compact(sid, createOpts, { userName: 'Carol' });@@ -2121,9 +2206,7 @@ describe('AgentInputCoordinator send transaction', () => {const persist = h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage;expect(persist?.content).toBe(CONTINUE_AFTER_ERROR_PROMPT);expect(h.sendToAgent.mock.calls[1]?.[2]?.planMode).toBe(false);- expect(h.onDispatchedUserTurn.mock.calls[1]?.[1]?.originalSyntheticTrigger).toBe(- 'continue',- );+ expect(h.onDispatchedUserTurn.mock.calls[1]?.[1]?.originalSyntheticTrigger).toBe('continue');});it('active-turn retry falls back to resending the original text when the turn produced nothing', async () => {@@ -2187,33 +2270,41 @@ describe('AgentInputCoordinator send transaction', () => {];item.persistedContent = JSON.stringify({text: item.text,- images: [{- url: 'data:image/png;base64,aW1hZ2U=',- mimeType: 'image/png',- originalName: 'image.png',- }, {- url: 'xdt-image://session/clip.gif',- mimeType: 'image/gif',- originalName: 'clip.gif',- }],+ images: [+ {+ url: 'data:image/png;base64,aW1hZ2U=',+ mimeType: 'image/png',+ originalName: 'image.png',+ },+ {+ url: 'xdt-image://session/clip.gif',+ mimeType: 'image/gif',+ originalName: 'clip.gif',+ },+ ],files: [{ name: 'notes.pdf', path: '/repo/notes.pdf' }],});item.chatMessage = {...item.chatMessage,- images: [{- url: 'data:image/png;base64,aW1hZ2U=',- mimeType: 'image/png',- originalName: 'image.png',- }, {- url: 'xdt-image://session/clip.gif',- mimeType: 'image/gif',- originalName: 'clip.gif',- }],+ images: [+ {+ url: 'data:image/png;base64,aW1hZ2U=',+ mimeType: 'image/png',+ originalName: 'image.png',+ },+ {+ url: 'xdt-image://session/clip.gif',+ mimeType: 'image/gif',+ originalName: 'clip.gif',+ },+ ],files: [{ name: 'notes.pdf', path: '/repo/notes.pdf' }],};- (item.chatMessage as typeof item.chatMessage & {- retryFiles?: AgentInputQueuedMessage['files'];- }).retryFiles = item.files;+ (+ item.chatMessage as typeof item.chatMessage & {+ retryFiles?: AgentInputQueuedMessage['files'];+ }+ ).retryFiles = item.files;h.coordinator.enqueue(sid, item);await flush();@@ -2239,25 +2330,33 @@ describe('AgentInputCoordinator send transaction', () => {expect.objectContaining({ id: 'gif-1', ext: '.gif', category: 'image' }),expect.objectContaining({ id: 'file-1', category: 'pdf' }),]);- expect(retried?.chatMessage.images).toEqual([{- url: 'xdt-image://session/clip.gif',- mimeType: 'image/gif',- originalName: 'clip.gif',- }]);+ expect(retried?.chatMessage.images).toEqual([+ {+ url: 'xdt-image://session/clip.gif',+ mimeType: 'image/gif',+ originalName: 'clip.gif',+ },+ ]);expect(retried?.chatMessage.files).toEqual([{ name: 'notes.pdf', path: '/repo/notes.pdf' }]);- expect((retried?.chatMessage as typeof retried.chatMessage & {- retryFiles?: AgentInputQueuedMessage['files'];- }).retryFiles).toEqual([+ expect(+ (+ retried?.chatMessage as typeof retried.chatMessage & {+ retryFiles?: AgentInputQueuedMessage['files'];+ }+ ).retryFiles,+ ).toEqual([expect.objectContaining({ id: 'gif-1', ext: '.gif', category: 'image' }),expect.objectContaining({ id: 'file-1', category: 'pdf' }),]);expect(JSON.parse(retried?.persistedContent ?? '{}')).toEqual({text: 'describe this',- images: [{- url: 'xdt-image://session/clip.gif',- mimeType: 'image/gif',- originalName: 'clip.gif',- }],+ images: [+ {+ url: 'xdt-image://session/clip.gif',+ mimeType: 'image/gif',+ originalName: 'clip.gif',+ },+ ],files: [{ name: 'notes.pdf', path: '/repo/notes.pdf' }],});});@@ -2267,32 +2366,38 @@ describe('AgentInputCoordinator send transaction', () => {const sid = 'retry-unsupported-image-only';h.setHasAssistantProgressAfter(async () => false);const item = makeItem('q-first', '');- item.files = [{- id: 'image-1',- name: 'image.png',- path: 'clipboard://image.png',- ext: '.png',- size: 4,- category: 'image',- mimeType: 'image/png',- url: 'data:image/png;base64,aW1hZ2U=',- }];+ item.files = [+ {+ id: 'image-1',+ name: 'image.png',+ path: 'clipboard://image.png',+ ext: '.png',+ size: 4,+ category: 'image',+ mimeType: 'image/png',+ url: 'data:image/png;base64,aW1hZ2U=',+ },+ ];item.persistedContent = JSON.stringify({text: '',- images: [{- url: 'data:image/png;base64,aW1hZ2U=',- mimeType: 'image/png',- originalName: 'image.png',- }],+ images: [+ {+ url: 'data:image/png;base64,aW1hZ2U=',+ mimeType: 'image/png',+ originalName: 'image.png',+ },+ ],files: [],});item.chatMessage = {...item.chatMessage,- images: [{- url: 'data:image/png;base64,aW1hZ2U=',- mimeType: 'image/png',- originalName: 'image.png',- }],+ images: [+ {+ url: 'data:image/png;base64,aW1hZ2U=',+ mimeType: 'image/png',+ originalName: 'image.png',+ },+ ],};h.coordinator.enqueue(sid, item);@@ -2320,16 +2425,18 @@ describe('AgentInputCoordinator send transaction', () => {const sid = 'retry-unsupported-image-legacy-error';h.setHasAssistantProgressAfter(async () => false);const item = makeItem('q-first', 'describe this');- item.files = [{- id: 'image-1',- name: 'image.png',- path: 'clipboard://image.png',- ext: '.png',- size: 4,- category: 'image',- mimeType: 'image/png',- url: 'data:image/png;base64,aW1hZ2U=',- }];+ item.files = [+ {+ id: 'image-1',+ name: 'image.png',+ path: 'clipboard://image.png',+ ext: '.png',+ size: 4,+ category: 'image',+ mimeType: 'image/png',+ url: 'data:image/png;base64,aW1hZ2U=',+ },+ ];h.coordinator.enqueue(sid, item);await flush();@@ -2392,9 +2499,7 @@ describe('AgentInputCoordinator send transaction', () => {expect(h.sendToAgent).toHaveBeenCalledTimes(2);expect(h.supersedeRetriedUserTurn).not.toHaveBeenCalled();- expect(- h.onDispatchedUserTurn.mock.calls[1]?.[1]?.supersedesUserClientId,- ).toBeUndefined();+ expect(h.onDispatchedUserTurn.mock.calls[1]?.[1]?.supersedesUserClientId).toBeUndefined();});it('chained zero-progress retries anchor each supersede on the previous clone', async () => {@@ -2412,8 +2517,7 @@ describe('AgentInputCoordinator send transaction', () => {await flush();await h.coordinator.retryLastError(sid);await flush();- const firstClone =- h.supersedeRetriedUserTurn.mock.calls[0]?.[1]?.retryUserClientId;+ const firstClone = h.supersedeRetriedUserTurn.mock.calls[0]?.[1]?.retryUserClientId;expect(firstClone).toEqual(expect.any(String));h.setRunning(false);@@ -2474,9 +2578,9 @@ describe('AgentInputCoordinator send transaction', () => {await flush();expect(h.sendToAgent).toHaveBeenCalledTimes(2);- expect(- h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage?.clientId,- ).toEqual(expect.any(String));+ expect(h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage?.clientId).toEqual(+ expect.any(String),+ );expect(h.supersedeRetriedUserTurn).not.toHaveBeenCalled();});@@ -2602,7 +2706,10 @@ describe('AgentInputCoordinator send transaction', () => {h.coordinator.enqueue(sid, makeItem('q-head', 'never dispatched'));await flush();- expect(latestProjection(h.projections).recovery).toEqual({ kind: 'queue-head', clientId: 'q-head' });+ expect(latestProjection(h.projections).recovery).toEqual({+ kind: 'queue-head',+ clientId: 'q-head',+ });await h.coordinator.retryLastError(sid);await flush();@@ -2635,7 +2742,10 @@ describe('AgentInputCoordinator send transaction', () => {expect(projection.error).toBeNull();expect(projection.pendingQueue).toHaveLength(0);expect(h.sendToAgent).toHaveBeenCalledTimes(2);- expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'brand new message' });+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({+ type: 'user',+ content: 'brand new message',+ });// 新输入之后再点「重试」:recovery 已被放弃,retryLastError 必须 no-op,不得双发。h.setRunning(false);@@ -2653,7 +2763,10 @@ describe('AgentInputCoordinator send transaction', () => {h.coordinator.enqueue(sid, makeItem('q-head', 'never dispatched'));await flush();- expect(latestProjection(h.projections).recovery).toEqual({ kind: 'queue-head', clientId: 'q-head' });+ expect(latestProjection(h.projections).recovery).toEqual({+ kind: 'queue-head',+ clientId: 'q-head',+ });// queue-head recovery 语义不变:失败消息还躺在队首,新消息只排队,// 不触发对失败队首的静默重发。@@ -2823,10 +2936,11 @@ describe('AgentInputCoordinator send transaction', () => {it('preserves the Pi image-capability marker for display-side localization', async () => {const h = createHarness();const sid = 'pi-image-capability';- h.sendToAgent.mockRejectedValueOnce(Object.assign(- new Error('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled'),- { code: 'PI_IMAGE_INPUT_UNSUPPORTED' },- ));+ h.sendToAgent.mockRejectedValueOnce(+ Object.assign(new Error('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled'), {+ code: 'PI_IMAGE_INPUT_UNSUPPORTED',+ }),+ );h.coordinator.enqueue(sid, makeItem('q-image', 'describe the screenshot'));await flush();@@ -2919,7 +3033,9 @@ describe('AgentInputCoordinator send transaction', () => {const sid = 'host-preflight-failure';const first = makeItem('q-1', 'first');- h.sendToAgent.mockResolvedValueOnce(hostSendFailure('WORKDIR_MISSING', 'working directory is missing'));+ h.sendToAgent.mockResolvedValueOnce(+ hostSendFailure('WORKDIR_MISSING', 'working directory is missing'),+ );h.coordinator.enqueue(sid, first);await flush();@@ -2931,11 +3047,13 @@ describe('AgentInputCoordinator send transaction', () => {expect(projection.error).toContain('working directory is missing');expect(mocks.createMessage).not.toHaveBeenCalled();expect(h.sendToAgent).toHaveBeenCalledTimes(1);- expect(latestWarnPayload()).toEqual(expect.objectContaining({- kind: 'host-send',- code: 'WORKDIR_MISSING',- clientId: 'q-1',- }));+ expect(latestWarnPayload()).toEqual(+ expect.objectContaining({+ kind: 'host-send',+ code: 'WORKDIR_MISSING',+ clientId: 'q-1',+ }),+ );});it('keeps a maker-core dispatch failure recoverable with session-dispatch reason and no dispatch', async () => {@@ -2943,7 +3061,9 @@ describe('AgentInputCoordinator send transaction', () => {const sid = 'session-dispatch-failure';const first = makeItem('q-1', 'first');- h.sendToAgent.mockResolvedValueOnce(sessionDispatchFailure('SEND/session-dispatch-failure/send'));+ h.sendToAgent.mockResolvedValueOnce(+ sessionDispatchFailure('SEND/session-dispatch-failure/send'),+ );h.coordinator.enqueue(sid, first);await flush();@@ -2955,37 +3075,47 @@ describe('AgentInputCoordinator send transaction', () => {expect(projection.error).toContain('SEND/session-dispatch-failure/send');expect(mocks.createMessage).not.toHaveBeenCalled();expect(h.sendToAgent).toHaveBeenCalledTimes(1);- expect(latestWarnPayload()).toEqual(expect.objectContaining({- kind: 'session-dispatch',- source: 'maker-ipc',- reason: 'cancelled-before-dispatch',- context: 'SEND/session-dispatch-failure/send',- clientId: 'q-1',- }));+ expect(latestWarnPayload()).toEqual(+ expect.objectContaining({+ kind: 'session-dispatch',+ source: 'maker-ipc',+ reason: 'cancelled-before-dispatch',+ context: 'SEND/session-dispatch-failure/send',+ clientId: 'q-1',+ }),+ );});it('does not collapse host and maker-core dispatch failures into the same recovery text or log reason', async () => {const host = createHarness();const dispatch = createHarness();- host.sendToAgent.mockResolvedValueOnce(hostSendFailure('WORKDIR_MISSING', 'working directory is missing'));+ host.sendToAgent.mockResolvedValueOnce(+ hostSendFailure('WORKDIR_MISSING', 'working directory is missing'),+ );host.coordinator.enqueue('host-failure-reason', makeItem('host-q', 'host'));await flush();const hostProjection = latestProjection(host.projections);const hostWarn = latestWarnPayload();- dispatch.sendToAgent.mockResolvedValueOnce(sessionDispatchFailure('SEND/dispatch-failure-reason/send'));+ dispatch.sendToAgent.mockResolvedValueOnce(+ sessionDispatchFailure('SEND/dispatch-failure-reason/send'),+ );dispatch.coordinator.enqueue('dispatch-failure-reason', makeItem('dispatch-q', 'dispatch'));await flush();const dispatchProjection = latestProjection(dispatch.projections);const dispatchWarn = latestWarnPayload();expect(hostProjection.error).not.toBe(dispatchProjection.error);- expect(hostWarn).toEqual(expect.objectContaining({ kind: 'host-send', code: 'WORKDIR_MISSING' }));- expect(dispatchWarn).toEqual(expect.objectContaining({- kind: 'session-dispatch',- reason: 'cancelled-before-dispatch',- }));+ expect(hostWarn).toEqual(+ expect.objectContaining({ kind: 'host-send', code: 'WORKDIR_MISSING' }),+ );+ expect(dispatchWarn).toEqual(+ expect.objectContaining({+ kind: 'session-dispatch',+ reason: 'cancelled-before-dispatch',+ }),+ );});it('does not auto-retry a failed queue head from later enqueue or Cancel', async () => {@@ -3180,6 +3310,33 @@ describe('AgentInputCoordinator send transaction', () => {expect(latestProjection(h.projections).pendingQueue).toEqual([]);});+ it('keeps the clear boundary monotonic when an older clear arrives later', () => {+ const h = createHarness();+ const sid = 'clear-boundary-monotonic';+ const newerBoundary = Date.parse('2026-06-20T12:00:00.000Z');+ const olderBoundary = Date.parse('2026-06-20T11:00:00.000Z');++ h.coordinator.clearSession(sid, newerBoundary);+ const generationAfterNewerClear = h.coordinator.getGeneration(sid);+ h.coordinator.clearSession(sid, olderBoundary);++ expect(h.coordinator.getGeneration(sid)).toBe(generationAfterNewerClear + 1);+ expect(h.coordinator.getClearBoundaryMs(sid)).toBe(newerBoundary);+ expect(latestProjection(h.projections).clearBoundaryMs).toBe(newerBoundary);+ });++ it('invalidates an IPC preparation generation when clearSession wins', () => {+ const h = createHarness();+ const sid = 'clear-invalidates-ipc-preparation';+ const generation = h.coordinator.getGeneration(sid);++ expect(h.coordinator.isGenerationCurrent(sid, generation)).toBe(true);+ h.coordinator.clearSession(sid);++ expect(h.coordinator.isGenerationCurrent(sid, generation)).toBe(false);+ expect(h.coordinator.getGeneration(sid)).toBe(generation + 1);+ });+it('suppresses local-db broadcasts if clearSession wins during accepted persistence', async () => {const h = createHarness();const sid = 'clear-during-persist';@@ -3200,6 +3357,31 @@ describe('AgentInputCoordinator send transaction', () => {expect(latestProjection(h.projections).pendingQueue).toEqual([]);});+ it('settles a persistence failure after clear without treating the row as durable', async () => {+ const h = createHarness();+ const sid = 'clear-during-persist-failure';+ const first = makeItem('q-1', 'first');+ mocks.createMessage.mockImplementationOnce(async () => {+ h.coordinator.clearSession(sid);+ throw new Error('sqlite write failed');+ });++ h.coordinator.enqueue(sid, first);+ await flush();++ expect(h.onUserMessagePersisting).toHaveBeenCalledWith(sid, expect.objectContaining(first));+ expect(h.onUserMessagePersistenceFailed).toHaveBeenCalledWith(+ sid,+ expect.objectContaining(first),+ {+ retainForRetry: true,+ },+ );+ expect(h.onUserMessagePersisted).not.toHaveBeenCalled();+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledWith(sid, expect.objectContaining(first));+ expect(latestProjection(h.projections).pendingQueue).toEqual([]);+ });+it('keeps Retry visible for accepted-turn errors with tail rows and drains the tail after Cancel', async () => {const h = createHarness();const sid = 'accepted-error-with-tail';@@ -3251,7 +3433,11 @@ describe('AgentInputCoordinator send transaction', () => {expect(projection.error).toBe('turn/start failed');expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });expect(projection.errorRetryText).toBe('first');- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'failed');+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(+ sid,+ expect.objectContaining(first),+ 'failed',+ );});it('recovers a persisted turn when terminal error arrives before send resolves', async () => {@@ -3395,7 +3581,11 @@ describe('AgentInputCoordinator send transaction', () => {expect(projection.error).toContain('cancelled-before-dispatch');expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });expect(projection.errorRetryText).toBe('first');- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'failed');+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(+ sid,+ expect.objectContaining(first),+ 'failed',+ );});it('keeps a persisted ordinary send recoverable when a host failure is reported late', async () => {@@ -3426,7 +3616,11 @@ describe('AgentInputCoordinator send transaction', () => {expect(projection.error).toContain('WORKDIR_MISSING');expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });expect(projection.errorRetryText).toBe('first');- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'failed');+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(+ sid,+ expect.objectContaining(first),+ 'failed',+ );});it('keeps ordinary send DB writes linear while draining queued turns', async () => {@@ -3488,7 +3682,11 @@ describe('AgentInputCoordinator send transaction', () => {expect(projection.pendingQueue).toEqual([second]);expect(projection.error).toContain('cancelled-before-dispatch');expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'cancelled');+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(+ sid,+ expect.objectContaining(first),+ 'cancelled',+ );expect(h.onRejectedUserTurn).not.toHaveBeenCalled();h.coordinator.resume(sid);@@ -3660,7 +3858,11 @@ describe('AgentInputCoordinator send transaction', () => {expect(projection.pendingQueue).toEqual([second]);expect(projection.error).toBeNull();expect(projection.recovery).toEqual({ kind: 'active-turn', item: first });- expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(sid, first, 'cancelled');+ expect(h.onUndispatchedUserTurn).toHaveBeenCalledWith(+ sid,+ expect.objectContaining(first),+ 'cancelled',+ );h.coordinator.resume(sid);await flush();@@ -3698,16 +3900,21 @@ describe('AgentInputCoordinator send transaction', () => {const h = createHarness();const sid = 'file-only-active-retry';const fileOnly = makeItem('q-file', '', {- persistedContent: JSON.stringify({ text: '', files: [{ name: 'spec.pdf', path: '/repo/spec.pdf' }] }),- files: [{- id: 'file-1',- name: 'spec.pdf',- path: '/repo/spec.pdf',- ext: '.pdf',- size: 123,- category: 'pdf',- mimeType: 'application/pdf',- }],+ persistedContent: JSON.stringify({+ text: '',+ files: [{ name: 'spec.pdf', path: '/repo/spec.pdf' }],+ }),+ files: [+ {+ id: 'file-1',+ name: 'spec.pdf',+ path: '/repo/spec.pdf',+ ext: '.pdf',+ size: 123,+ category: 'pdf',+ mimeType: 'application/pdf',+ },+ ],chatMessage: {clientId: 'q-file',role: 'user',@@ -3752,7 +3959,10 @@ describe('AgentInputCoordinator send transaction', () => {firstAttempt.reject(new Error('workdir missing'));await flush();- expect(latestProjection(h.projections).pendingQueue.map((q) => q.text)).toEqual(['first', 'second']);+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.text)).toEqual([+ 'first',+ 'second',+ ]);h.coordinator.remove(sid, first.clientId);await flush();@@ -4039,52 +4249,49 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {{ agentKind: 'claude-code' as const, providerId: 'xd', model: 'claude-opus-5' },{ agentKind: 'codex' as const, providerId: 'xd', model: 'gpt-5.5' },{ agentKind: 'pi' as const, providerId: 'openai', model: 'gpt-5.5' },- ])('retries abort reconciliation after $agentKind abort settles before the live turn is idle', async ({- agentKind,- providerId,- model,- }) => {- vi.useFakeTimers();- const h = createHarness();- const sid = `stop-delayed-idle-${agentKind}`;- const first = makeItem('q-1', 'first', {- createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind, providerId, model },- });- const second = makeItem('q-2', 'second', {- createOpts: { ...makeItem('tmp2', 'tmp2').createOpts, agentKind, providerId, model },- });- const abort = deferred<void>();- h.setAgentKind(agentKind);- h.abortSession.mockImplementationOnce(() => abort.promise);- h.reconcileTurnIdle- .mockReturnValueOnce(false)- .mockImplementationOnce(() => {+ ])(+ 'retries abort reconciliation after $agentKind abort settles before the live turn is idle',+ async ({ agentKind, providerId, model }) => {+ vi.useFakeTimers();+ const h = createHarness();+ const sid = `stop-delayed-idle-${agentKind}`;+ const first = makeItem('q-1', 'first', {+ createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind, providerId, model },+ });+ const second = makeItem('q-2', 'second', {+ createOpts: { ...makeItem('tmp2', 'tmp2').createOpts, agentKind, providerId, model },+ });+ const abort = deferred<void>();+ h.setAgentKind(agentKind);+ h.abortSession.mockImplementationOnce(() => abort.promise);+ h.reconcileTurnIdle.mockReturnValueOnce(false).mockImplementationOnce(() => {h.setRunning(false);return true;});- h.coordinator.enqueue(sid, first);- await flush();- h.coordinator.enqueue(sid, second);- await flush();+ h.coordinator.enqueue(sid, first);+ await flush();+ h.coordinator.enqueue(sid, second);+ await flush();- h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });- h.coordinator.resume(sid);- abort.resolve();- await flush();+ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });+ h.coordinator.resume(sid);+ abort.resolve();+ await flush();- expect(h.reconcileTurnIdle).toHaveBeenCalledTimes(1);- expect(h.sendToAgent).toHaveBeenCalledTimes(1);- expect(latestProjection(h.projections).pendingQueue).toEqual([second]);+ expect(h.reconcileTurnIdle).toHaveBeenCalledTimes(1);+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).pendingQueue).toEqual([second]);- await vi.advanceTimersByTimeAsync(250);- await flush();+ await vi.advanceTimersByTimeAsync(250);+ await flush();- expect(h.reconcileTurnIdle).toHaveBeenCalledTimes(2);- expect(h.sendToAgent).toHaveBeenCalledTimes(2);- expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'second' });- expect(latestProjection(h.projections).queueAbortPending).toBe(false);- });+ expect(h.reconcileTurnIdle).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'second' });+ expect(latestProjection(h.projections).queueAbortPending).toBe(false);+ },+ );it('retains an abort lock when owner switching hides the agent kind and live idle cannot be confirmed', async () => {vi.useFakeTimers();@@ -4094,9 +4301,7 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {const first = makeItem('q-1', 'first');const second = makeItem('q-2', 'second');h.setAgentKind(null);- h.reconcileTurnIdle- .mockReturnValueOnce(false)- .mockImplementationOnce(() => true);+ h.reconcileTurnIdle.mockReturnValueOnce(false).mockImplementationOnce(() => true);h.coordinator.enqueue(sid, first);await flush();@@ -4128,77 +4333,30 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {it('ignores an old abort completion after clearSession starts a new turn', async () => {const h = createHarness();- const sid = 'stop-abort-clear-new-turn';- const first = makeItem('q-1', 'first', {- createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind: 'codex' },- });- const replacement = makeItem('q-new', 'replacement', {- createOpts: { ...makeItem('tmp-new', 'tmp-new').createOpts, agentKind: 'codex' },- });- const abort = deferred<void>();- h.setAgentKind('codex');- h.abortSession.mockImplementationOnce(() => abort.promise);-- h.coordinator.enqueue(sid, first);- await flush();- h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });-- // The user explicitly resets the session while the old abort RPC is still- // pending, then starts a new turn in the replacement state.- h.coordinator.clearSession(sid);- h.setRunning(false);- h.coordinator.enqueue(sid, replacement);- await flush();- expect(h.sendToAgent).toHaveBeenCalledTimes(2);-- h.reconcileTurnIdle.mockReturnValueOnce(true);- abort.resolve();- await flush();-- const state = (- h.coordinator as unknown as {- getState: (id: string) => { activeTurn: { item: AgentInputQueuedMessage | null } | null };- }- ).getState(sid);- expect(state.activeTurn?.item?.clientId).toBe('q-new');- expect(h.reconcileTurnIdle).not.toHaveBeenCalled();- });-- it.each([- { agentKind: 'claude-code' as const, providerId: 'xd', model: 'claude-opus-5' },- { agentKind: 'codex' as const, providerId: 'xd', model: 'gpt-5.5' },- ])('invalidates an old abort token when $agentKind starts a new turn after a non-preserving stop', async ({- agentKind,- providerId,- model,- }) => {- const h = createHarness();- const sid = `stop-abort-new-turn-${agentKind}`;+ const sid = 'stop-abort-clear-new-turn';const first = makeItem('q-1', 'first', {- createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind, providerId, model },+ createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind: 'codex' },});const replacement = makeItem('q-new', 'replacement', {- createOpts: { ...makeItem('tmp-new', 'tmp-new').createOpts, agentKind, providerId, model },+ createOpts: { ...makeItem('tmp-new', 'tmp-new').createOpts, agentKind: 'codex' },});const abort = deferred<void>();- const beforeDispatch = deferred<void>();- h.setAgentKind(agentKind);+ h.setAgentKind('codex');h.abortSession.mockImplementationOnce(() => abort.promise);- h.beforeDispatchUserTurn.mockImplementationOnce(() => beforeDispatch.promise);h.coordinator.enqueue(sid, first);await flush();- h.coordinator.stop(sid, { keepQueue: false });- h.setRunning(false);- beforeDispatch.resolve();- await flush();+ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });- // A non-preserving stop does not hold queueAbortPending, so a replacement- // turn can start while the old vendor abort promise is still unresolved.+ // The user explicitly resets the session while the old abort RPC is still+ // pending, then starts a new turn in the replacement state.+ h.coordinator.clearSession(sid);+ h.setRunning(false);h.coordinator.enqueue(sid, replacement);await flush();expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ h.reconcileTurnIdle.mockReturnValueOnce(true);abort.resolve();await flush();@@ -4211,6 +4369,52 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {expect(h.reconcileTurnIdle).not.toHaveBeenCalled();});+ it.each([+ { agentKind: 'claude-code' as const, providerId: 'xd', model: 'claude-opus-5' },+ { agentKind: 'codex' as const, providerId: 'xd', model: 'gpt-5.5' },+ ])(+ 'invalidates an old abort token when $agentKind starts a new turn after a non-preserving stop',+ async ({ agentKind, providerId, model }) => {+ const h = createHarness();+ const sid = `stop-abort-new-turn-${agentKind}`;+ const first = makeItem('q-1', 'first', {+ createOpts: { ...makeItem('tmp', 'tmp').createOpts, agentKind, providerId, model },+ });+ const replacement = makeItem('q-new', 'replacement', {+ createOpts: { ...makeItem('tmp-new', 'tmp-new').createOpts, agentKind, providerId, model },+ });+ const abort = deferred<void>();+ const beforeDispatch = deferred<void>();+ h.setAgentKind(agentKind);+ h.abortSession.mockImplementationOnce(() => abort.promise);+ h.beforeDispatchUserTurn.mockImplementationOnce(() => beforeDispatch.promise);++ h.coordinator.enqueue(sid, first);+ await flush();+ h.coordinator.stop(sid, { keepQueue: false });+ h.setRunning(false);+ beforeDispatch.resolve();+ await flush();++ // A non-preserving stop does not hold queueAbortPending, so a replacement+ // turn can start while the old vendor abort promise is still unresolved.+ h.coordinator.enqueue(sid, replacement);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);++ abort.resolve();+ await flush();++ const state = (+ h.coordinator as unknown as {+ getState: (id: string) => { activeTurn: { item: AgentInputQueuedMessage | null } | null };+ }+ ).getState(sid);+ expect(state.activeTurn?.item?.clientId).toBe('q-new');+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();+ },+ );+it('keeps Codex queue abort lock until a real turn boundary', async () => {const h = createHarness();const sid = 'stop-codex';@@ -4313,7 +4517,10 @@ describe('AgentInputCoordinator steer transaction', () => {h.coordinator.enqueue(sid, second);await flush();- const ok = await h.coordinator.steer(sid, second, { removeFromQueue: true, touchUserSend: true });+ const ok = await h.coordinator.steer(sid, second, {+ removeFromQueue: true,+ touchUserSend: true,+ });await flush();// 同轮注入(2026-07-12 统一):Claude 与 Codex 走同一条 steerToAgent 路径,@@ -4385,10 +4592,11 @@ describe('AgentInputCoordinator steer transaction', () => {const sid = 'steer-pi-image-capability-retry';const first = makeItem('q-1', 'first');const second = makeItem('q-2', 'describe the screenshot');- h.steerToAgent.mockRejectedValueOnce(Object.assign(- new Error('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled'),- { code: 'PI_IMAGE_INPUT_UNSUPPORTED' },- ));+ h.steerToAgent.mockRejectedValueOnce(+ Object.assign(new Error('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled'), {+ code: 'PI_IMAGE_INPUT_UNSUPPORTED',+ }),+ );h.coordinator.enqueue(sid, first);await flush();@@ -4433,10 +4641,11 @@ describe('AgentInputCoordinator steer transaction', () => {const sid = 'steer-pi-image-capability-active-error';const first = makeItem('q-1', 'first');const second = makeItem('q-2', 'describe the screenshot');- h.steerToAgent.mockRejectedValueOnce(Object.assign(- new Error('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled'),- { code: 'PI_IMAGE_INPUT_UNSUPPORTED' },- ));+ h.steerToAgent.mockRejectedValueOnce(+ Object.assign(new Error('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled'), {+ code: 'PI_IMAGE_INPUT_UNSUPPORTED',+ }),+ );h.coordinator.enqueue(sid, first);await flush();@@ -4574,7 +4783,11 @@ describe('AgentInputCoordinator steer transaction', () => {await flush();h.coordinator.stop(sid);- gate.reject(new Error('Codex steer cancelled before acceptance; delivery uncertain (request already dispatched)'));+ gate.reject(+ new Error(+ 'Codex steer cancelled before acceptance; delivery uncertain (request already dispatched)',+ ),+ );await expect(steerPromise).resolves.toBe(false);await flush();@@ -4600,7 +4813,11 @@ describe('AgentInputCoordinator steer transaction', () => {// clearSession 是用户显式重置(generation bump):结果不确定也不塞回去。h.coordinator.clearSession(sid);- gate.reject(new Error('Codex steer cancelled before acceptance; delivery uncertain (request already dispatched)'));+ gate.reject(+ new Error(+ 'Codex steer cancelled before acceptance; delivery uncertain (request already dispatched)',+ ),+ );await expect(steerPromise).resolves.toBe(false);await flush();@@ -4638,7 +4855,9 @@ describe('AgentInputCoordinator steer transaction', () => {h.coordinator.onTurnEvent(sid, 'done');await flush();expect(h.sendToAgent).toHaveBeenCalledTimes(1);- expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['composer-1']);+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual([+ 'composer-1',+ ]);});it('replays the terminal error recovery when a late steer ack lands after the turn failed', async () => {@@ -4809,9 +5028,7 @@ describe('AgentInputCoordinator steer transaction', () => {const sid = 'steer-persist-fails';const first = makeItem('q-1', 'first');const second = makeItem('q-2', 'second');- mocks.createMessage- .mockResolvedValueOnce({})- .mockRejectedValueOnce(new Error('db down'));+ mocks.createMessage.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error('db down'));h.coordinator.enqueue(sid, first);await flush();@@ -4841,9 +5058,7 @@ describe('AgentInputCoordinator steer transaction', () => {const sid = 'steer-persist-fails-then-terminal-error';const first = makeItem('q-1', 'first');const second = makeItem('q-2', 'second');- mocks.createMessage- .mockResolvedValueOnce({})- .mockRejectedValueOnce(new Error('db down'));+ mocks.createMessage.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error('db down'));h.coordinator.enqueue(sid, first);await flush();@@ -4861,6 +5076,73 @@ describe('AgentInputCoordinator steer transaction', () => {expect(projection.errorRetryText).toBeNull();});+ it('deduplicates an accepted steer after persistence and terminal failure', async () => {+ const h = createHarness();+ h.setAgentKind('codex');+ const sid = 'steer-accepted-persist-failure-dedup';+ const first = makeItem('q-1', 'first');+ const second = makeItem('q-2', 'second');+ mocks.createMessage.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error('db down'));++ h.coordinator.enqueue(sid, first);+ await flush();++ await expect(h.coordinator.steer(sid, second, { removeFromQueue: true })).resolves.toBe(false);+ await flush();+ expect(h.steerToAgent).toHaveBeenCalledTimes(1);++ // The accepted vendor injection has no durable row, and the terminal event+ // releases activeTurn. The bounded accepted-clientId window must still stop+ // an ACK-loss resend from injecting the same content a second time.+ h.coordinator.onTurnEvent(sid, 'error', 'terminal after persist failure');+ await flush();+ expect(h.coordinator.hasKnownClientId(sid, second.clientId)).toBe(true);++ await expect(h.coordinator.steer(sid, second, { removeFromQueue: true })).resolves.toBe(true);+ await flush();++ expect(h.steerToAgent).toHaveBeenCalledTimes(1);+ expect(mocks.createMessage).toHaveBeenCalledTimes(2);+ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual([]);+ });++ it('keeps an accepted steer serialized until its user row is durable', async () => {+ const h = createHarness();+ h.setAgentKind('codex');+ const sid = 'steer-accepted-persisting-serialized';+ const first = makeItem('q-1', 'first');+ const second = makeItem('q-2', 'second');+ const third = makeItem('q-3', 'third');+ const persistStarted = deferred<void>();+ const persistSucceeded = deferred<void>();+ mocks.createMessage.mockResolvedValueOnce({}).mockImplementationOnce(async () => {+ persistStarted.resolve();+ await persistSucceeded.promise;+ return {};+ });++ h.coordinator.enqueue(sid, first);+ await flush();+ h.coordinator.enqueue(sid, second);+ h.coordinator.enqueue(sid, third);+ await flush();++ const steerPromise = h.coordinator.steer(sid, second, { removeFromQueue: true });+ await persistStarted.promise;++ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual(['q-2']);+ await expect(h.coordinator.steer(sid, second, { removeFromQueue: true })).resolves.toBe(true);+ await expect(h.coordinator.steer(sid, third, { removeFromQueue: true })).resolves.toBe(false);+ expect(h.steerToAgent).toHaveBeenCalledTimes(1);++ persistSucceeded.resolve();+ await expect(steerPromise).resolves.toBe(true);+ await flush();++ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual([]);+ expect(mocks.createMessage).toHaveBeenCalledTimes(2);+ });+it('keeps active-turn retry when terminal error arrives before successful steer persistence settles', async () => {const h = createHarness();h.setAgentKind('codex');@@ -4869,13 +5151,11 @@ describe('AgentInputCoordinator steer transaction', () => {const second = makeItem('q-2', 'second');const persistStarted = deferred<void>();const persistSucceeded = deferred<void>();- mocks.createMessage- .mockResolvedValueOnce({})- .mockImplementationOnce(async () => {- persistStarted.resolve();- await persistSucceeded.promise;- return {};- });+ mocks.createMessage.mockResolvedValueOnce({}).mockImplementationOnce(async () => {+ persistStarted.resolve();+ await persistSucceeded.promise;+ return {};+ });h.coordinator.enqueue(sid, first);await flush();@@ -4953,13 +5233,11 @@ describe('AgentInputCoordinator steer transaction', () => {const second = makeItem('q-2', 'second');const persistStarted = deferred<void>();const persistSucceeded = deferred<void>();- mocks.createMessage- .mockResolvedValueOnce({})- .mockImplementationOnce(async () => {- persistStarted.resolve();- await persistSucceeded.promise;- return {};- });+ mocks.createMessage.mockResolvedValueOnce({}).mockImplementationOnce(async () => {+ persistStarted.resolve();+ await persistSucceeded.promise;+ return {};+ });h.coordinator.enqueue(sid, first);await flush();@@ -4996,13 +5274,11 @@ describe('AgentInputCoordinator steer transaction', () => {const second = makeItem('q-2', 'second');const persistStarted = deferred<void>();const persistFailed = deferred<void>();- mocks.createMessage- .mockResolvedValueOnce({})- .mockImplementationOnce(async () => {- persistStarted.resolve();- await persistFailed.promise;- throw new Error('db down');- });+ mocks.createMessage.mockResolvedValueOnce({}).mockImplementationOnce(async () => {+ persistStarted.resolve();+ await persistFailed.promise;+ throw new Error('db down');+ });h.coordinator.enqueue(sid, first);await flush();@@ -5061,7 +5337,9 @@ describe('AgentInputCoordinator steer transaction', () => {await flush();expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);- h.steerToAgent.mockRejectedValueOnce(new Error('[NO_ACTIVE_TURN] Session steer-zombie has no active turn'));+ h.steerToAgent.mockRejectedValueOnce(+ new Error('[NO_ACTIVE_TURN] Session steer-zombie has no active turn'),+ );// host 校准: 复核后清掉 stale busy tracker (镜像 register.ts 的接线行为)。h.reconcileTurnIdle.mockImplementationOnce(() => {h.setRunning(false);@@ -5126,7 +5404,9 @@ describe('AgentInputCoordinator steer transaction', () => {expect(h.resolveSessionReferences).not.toHaveBeenCalled();expect(h.sendToAgent).toHaveBeenCalledTimes(2);- expect(JSON.stringify(h.sendToAgent.mock.calls[1]?.[1])).toContain('authoritative remote history');+ expect(JSON.stringify(h.sendToAgent.mock.calls[1]?.[1])).toContain(+ 'authoritative remote history',+ );});it('serializes steer attempts while a steer request is already in flight', async () => {@@ -5210,14 +5490,17 @@ describe('AgentInputCoordinator steer transaction', () => {createOpts: { ...makeItem('tmp2', 'tmp2').createOpts, agentKind: 'codex' },});h.setAgentKind('codex');- h.steerToAgent.mockImplementationOnce((_sessionId, _message, sendOpts) =>- new Promise<void>((_resolve, reject) => {- if (sendOpts.signal?.aborted) {- reject(new Error('cancelled'));- return;- }- sendOpts.signal?.addEventListener('abort', () => reject(new Error('cancelled')), { once: true });- }),+ h.steerToAgent.mockImplementationOnce(+ (_sessionId, _message, sendOpts) =>+ new Promise<void>((_resolve, reject) => {+ if (sendOpts.signal?.aborted) {+ reject(new Error('cancelled'));+ return;+ }+ sendOpts.signal?.addEventListener('abort', () => reject(new Error('cancelled')), {+ once: true,+ });+ }),);h.coordinator.enqueue(sid, first);@@ -5374,10 +5657,17 @@ describe('AgentInputCoordinator queue mutations', () => {const sid = 'edit-content';const first = makeItem('q-1', 'first');const second = makeItem('q-2', 'old', {- files: [{- id: 'file-old', name: 'old.png', path: '/tmp/old.png', ext: '.png',- size: 10, category: 'image', mimeType: 'image/png',- }],+ files: [+ {+ id: 'file-old',+ name: 'old.png',+ path: '/tmp/old.png',+ ext: '.png',+ size: 10,+ category: 'image',+ mimeType: 'image/png',+ },+ ],});h.coordinator.enqueue(sid, first);@@ -5392,22 +5682,39 @@ describe('AgentInputCoordinator queue mutations', () => {});h.coordinator.enqueue(sid, withMentions);await flush();- h.coordinator.updateContent(sid, withMentions.clientId, makeItem(withMentions.clientId, 'edited on phone'));- const mentionKept = latestProjection(h.projections).pendingQueue- .find((entry) => entry.clientId === withMentions.clientId);+ h.coordinator.updateContent(+ sid,+ withMentions.clientId,+ makeItem(withMentions.clientId, 'edited on phone'),+ );+ const mentionKept = latestProjection(h.projections).pendingQueue.find(+ (entry) => entry.clientId === withMentions.clientId,+ );expect(mentionKept?.mentions).toEqual([{ type: 'file', name: 'README.md', path: 'README.md' }]);// 显式数组才是权威替换:空数组 = 清空。- h.coordinator.updateContent(sid, withMentions.clientId, makeItem(withMentions.clientId, 'cleared', { mentions: [] }));- const mentionCleared = latestProjection(h.projections).pendingQueue- .find((entry) => entry.clientId === withMentions.clientId);+ h.coordinator.updateContent(+ sid,+ withMentions.clientId,+ makeItem(withMentions.clientId, 'cleared', { mentions: [] }),+ );+ const mentionCleared = latestProjection(h.projections).pendingQueue.find(+ (entry) => entry.clientId === withMentions.clientId,+ );expect(mentionCleared?.mentions).toBeUndefined();const replacement = makeItem(second.clientId, 'edited', {persistedContent: JSON.stringify({ text: 'edited', images: [], files: [] }),- files: [{- id: 'file-new', name: 'new.png', path: '/tmp/new.png', ext: '.png',- size: 20, category: 'image', mimeType: 'image/png',- }],+ files: [+ {+ id: 'file-new',+ name: 'new.png',+ path: '/tmp/new.png',+ ext: '.png',+ size: 20,+ category: 'image',+ mimeType: 'image/png',+ },+ ],chatMessage: {clientId: second.clientId,role: 'user',@@ -5581,11 +5888,9 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()const h = createHarness();const sid = 'continue-in-flight-projection';- h.coordinator.enqueue(- sid,- makeItem('q-continue', CONTINUE_AFTER_APP_EXIT_PROMPT),- { resumeRestorePausedQueue: true },- );+ h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_APP_EXIT_PROMPT), {+ resumeRestorePausedQueue: true,+ });await flush();let projection = latestProjection(h.projections);@@ -5604,11 +5909,9 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()const h = createHarness();const sid = 'continue-owner-survives-steer';- h.coordinator.enqueue(- sid,- makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),- { resumeRestorePausedQueue: true },- );+ h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT), {+ resumeRestorePausedQueue: true,+ });await flush();let projection = latestProjection(h.projections);@@ -5634,11 +5937,9 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()const steerGate = deferred<void>();h.steerToAgent.mockImplementationOnce(() => steerGate.promise);- h.coordinator.enqueue(- sid,- makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),- { resumeRestorePausedQueue: true },- );+ h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT), {+ resumeRestorePausedQueue: true,+ });await flush();const steerPromise = h.coordinator.steer(sid, makeItem('q-steer', 'additional context'));@@ -5662,11 +5963,9 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()const steerGate = deferred<void>();h.steerToAgent.mockImplementationOnce(() => steerGate.promise);- h.coordinator.enqueue(- sid,- makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),- { resumeRestorePausedQueue: true },- );+ h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT), {+ resumeRestorePausedQueue: true,+ });await flush();h.setTurnGeneration(null as never);@@ -5687,11 +5986,9 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()const steerGate = deferred<void>();h.steerToAgent.mockImplementationOnce(() => steerGate.promise);- h.coordinator.enqueue(- sid,- makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),- { resumeRestorePausedQueue: true },- );+ h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT), {+ resumeRestorePausedQueue: true,+ });await flush();const steerPromise = h.coordinator.steer(sid, makeItem('q-steer', 'additional context'));@@ -5711,11 +6008,9 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()h.setAgentKind('codex');const sid = 'continue-owner-cleared-on-stop';- h.coordinator.enqueue(- sid,- makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),- { resumeRestorePausedQueue: true },- );+ h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT), {+ resumeRestorePausedQueue: true,+ });await flush();expect(latestProjection(h.projections).continuationTurnClientId).toBe('q-continue');@@ -5740,11 +6035,9 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()return sendSuccess();});- h.coordinator.enqueue(- sid,- makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),- { resumeRestorePausedQueue: true },- );+ h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT), {+ resumeRestorePausedQueue: true,+ });await sendStarted.promise;h.coordinator.stop(sid);@@ -5766,11 +6059,9 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()const sid = 'continue-cancelled-while-queued';h.setRunning(true);- h.coordinator.enqueue(- sid,- makeItem('q-continue', CONTINUE_AFTER_APP_EXIT_PROMPT),- { resumeRestorePausedQueue: true },- );+ h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_APP_EXIT_PROMPT), {+ resumeRestorePausedQueue: true,+ });await flush();let projection = latestProjection(h.projections);@@ -5795,11 +6086,9 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()text: 'Continue with the reviewed constraints.',}));- h.coordinator.enqueue(- sid,- makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT),- { resumeRestorePausedQueue: true },- );+ h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT), {+ resumeRestorePausedQueue: true,+ });await flush();expect(h.sendToAgent).toHaveBeenCalledWith(@@ -5920,7 +6209,10 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()await h.coordinator.ensureQueueRestored(sid);await flush();expect(attempts).toBe(2);- expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['r-1', 'q-1']);+ expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual([+ 'r-1',+ 'q-1',+ ]);expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual(['r-1', 'q-1']);});@@ -6026,15 +6318,17 @@ describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)'const raw = `> <!-- cindy-composer-quote -->\n> selected\n\ninspect ${href}`;const item = makeItem('semantic-turn', raw, {persistedContent: JSON.stringify({ text: raw, quotesEncoded: true }),- agentReferences: [{- kind: 'message',- start: raw.indexOf(href),- end: raw.indexOf(href) + href.length,- href,- sessionId: 'session-a',- messageClientId: 'message-a',- text: 'Target message body',- }],+ agentReferences: [+ {+ kind: 'message',+ start: raw.indexOf(href),+ end: raw.indexOf(href) + href.length,+ href,+ sessionId: 'session-a',+ messageClientId: 'message-a',+ text: 'Target message body',+ },+ ],chatMessage: {clientId: 'semantic-turn',role: 'user',@@ -6107,7 +6401,9 @@ describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)'it('bypassGhostHooks:强行放行的重发不再询问钩子', async () => {const h = createHarness();- const screen = vi.fn(async () => ({ action: 'block', ghostId: 'g1', ghostName: '哨兵', reason: 'x' }) as const);+ const screen = vi.fn(+ async () => ({ action: 'block', ghostId: 'g1', ghostName: '哨兵', reason: 'x' }) as const,+ );h.setScreenUserMessage(screen);h.coordinator.enqueue('s1', makeItem('c1', '剧透话', { bypassGhostHooks: true }));await flush();@@ -6127,12 +6423,15 @@ describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)'it('rewrite:改写版落库 + 送 agent,回调 onUserMessageRewritten 带原文', async () => {const h = createHarness();- h.setScreenUserMessage(async () => ({- action: 'rewrite',- ghostId: 'g1',- ghostName: '哨兵',- text: '优化后的问题',- }) as const);+ h.setScreenUserMessage(+ async () =>+ ({+ action: 'rewrite',+ ghostId: 'g1',+ ghostName: '哨兵',+ text: '优化后的问题',+ }) as const,+ );h.coordinator.enqueue('s1', makeItem('c1', '润色 原始问题'));await flush();// 送 agent 的消息是改写版(buildMakerUserMessage 读 head.text)@@ -6141,8 +6440,9 @@ describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)'// 落库内容也是改写版(persistUserMessage.content = head.persistedContent)expect(mocks.createMessage.mock.calls.some(- (c) => (c[1] as { clientId?: string; content?: string }).clientId === 'c1'- && (c[1] as { content?: string }).content === '优化后的问题',+ (c) =>+ (c[1] as { clientId?: string; content?: string }).clientId === 'c1' &&+ (c[1] as { content?: string }).content === '优化后的问题',),).toBe(true);// 回调带原文供留痕@@ -6156,12 +6456,15 @@ describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)'it('rewrite:persistedContent 是 JSON 信封(带附件/引用)时只换 text 字段,引用不丢', async () => {const h = createHarness();- h.setScreenUserMessage(async () => ({- action: 'rewrite',- ghostId: 'g1',- ghostName: '哨兵',- text: '优化后的问题',- }) as const);+ h.setScreenUserMessage(+ async () =>+ ({+ action: 'rewrite',+ ghostId: 'g1',+ ghostName: '哨兵',+ text: '优化后的问题',+ }) as const,+ );// stringifyUserContent 形态的信封:text 之外还有图片引用与引用块。const envelope = JSON.stringify({text: '润色 原始问题',@@ -6182,23 +6485,29 @@ describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)'it('rewrite:marker 被移除时同步清除真实 quotesEncoded 标志', async () => {const h = createHarness();- h.setScreenUserMessage(async () => ({- action: 'rewrite',- ghostId: 'g1',- ghostName: '哨兵',- text: '> ordinary markdown after rewrite',- }) as const);+ h.setScreenUserMessage(+ async () =>+ ({+ action: 'rewrite',+ ghostId: 'g1',+ ghostName: '哨兵',+ text: '> ordinary markdown after rewrite',+ }) as const,+ );const original = '> <!-- cindy-composer-quote -->\n> product quote\n\n润色 原始问题';const envelope = JSON.stringify({ text: original, quotesEncoded: true });- h.coordinator.enqueue('s1', makeItem('c1', original, {- persistedContent: envelope,- chatMessage: {- clientId: 'c1',- role: 'user',- content: original,- quotesEncoded: true,- },- }));+ h.coordinator.enqueue(+ 's1',+ makeItem('c1', original, {+ persistedContent: envelope,+ chatMessage: {+ clientId: 'c1',+ role: 'user',+ content: original,+ quotesEncoded: true,+ },+ }),+ );await flush();@@ -6217,12 +6526,15 @@ describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)'const h = createHarness();const href = 'cindy://session/session-a?message=message-a';const original = `inspect ${href}`;- h.setScreenUserMessage(async () => ({- action: 'rewrite',- ghostId: 'g1',- ghostName: '哨兵',- text: `rewritten ${href}`,- }) as const);+ h.setScreenUserMessage(+ async () =>+ ({+ action: 'rewrite',+ ghostId: 'g1',+ ghostName: '哨兵',+ text: `rewritten ${href}`,+ }) as const,+ );const reference = {kind: 'message' as const,start: original.indexOf(href),@@ -6232,13 +6544,16 @@ describe('AgentInputCoordinator 意识拦截钩(订阅槽①,will-user-message)'messageClientId: 'message-a',text: 'Target message body',};- h.coordinator.enqueue('s1', makeItem('c1', original, {- persistedContent: JSON.stringify({- text: original,+ h.coordinator.enqueue(+ 's1',+ makeItem('c1', original, {+ persistedContent: JSON.stringify({+ text: original,+ agentReferences: [reference],+ }),agentReferences: [reference],}),- agentReferences: [reference],- }));+ );await flush();@@ -6353,9 +6668,7 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()// 去重视角也看不到它 → 顺延重试 / 下一轮 cron 能重新入队,不被僵尸挡住expect(bySchedule(true)).toBe(false);expect(bySchedule(false)).toBe(false);- expect(- h.coordinator.hasQueuedItemWhere(sid, (item) => item.clientId === 'c1'),- ).toBe(false);+ expect(h.coordinator.hasQueuedItemWhere(sid, (item) => item.clientId === 'c1')).toBe(false);});it('onAccepted 抛错取消 scheduler 项:放掉 activeTurn 并唤醒队列(不把会话钉死)', async () => {@@ -6379,15 +6692,19 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()expect(latestProjection(h.projections).recovery).toBeNull();// activeTurn 是内部态(不进 projection),但它正是 isDispatchBoundaryBusy 的判据expect(- (h.coordinator as unknown as { getState: (id: string) => { activeTurn: unknown } })- .getState(sid).activeTurn,+ (h.coordinator as unknown as { getState: (id: string) => { activeTurn: unknown } }).getState(+ sid,+ ).activeTurn,).toBeNull();// 派发边界确实放开了:紧接着入队的消息能被真正派发出去- h.sendToAgent.mockImplementationOnce(async () => ({- kind: 'session-dispatch',- dispatched: true,- }) as never);+ h.sendToAgent.mockImplementationOnce(+ async () =>+ ({+ kind: 'session-dispatch',+ dispatched: true,+ }) as never,+ );h.coordinator.enqueue(sid, makeItem('c2', 'next one'));await flush();expect(h.sendToAgent).toHaveBeenCalledTimes(2);@@ -6420,10 +6737,13 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()// 队列真的被唤醒了(recovery 不留就没人点 clearError,必须自己唤)。注意唤醒是// **等失败收尾的配对 done 到达之后**:第二十一轮起这条路会打配对标记,标记期间派发// 边界算忙 —— 旧 turn 的尾巴还在飞时就起新活,正是那一轮要防的错误归因。- h.sendToAgent.mockImplementationOnce(async () => ({- kind: 'session-dispatch',- dispatched: true,- }) as never);+ h.sendToAgent.mockImplementationOnce(+ async () =>+ ({+ kind: 'session-dispatch',+ dispatched: true,+ }) as never,+ );h.coordinator.enqueue(sid, makeItem('c2', 'next one'));await flush();h.coordinator.onTurnEvent(sid, 'done');@@ -6490,10 +6810,13 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()h.coordinator.onTurnEvent(sid, 'error', 'upstream went silent');await flush();- h.sendToAgent.mockImplementationOnce(async () => ({- kind: 'session-dispatch',- dispatched: true,- }) as never);+ h.sendToAgent.mockImplementationOnce(+ async () =>+ ({+ kind: 'session-dispatch',+ dispatched: true,+ }) as never,+ );h.coordinator.enqueue(sid, makeItem('c2', 'next one'));await flush();// 配对标记仍在 → 新消息不该被派发@@ -6512,9 +6835,10 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()const sid = 'sched-error-during-persist';let releasePersist!: () => void;mocks.createMessage.mockImplementationOnce(- () => new Promise<Record<string, never>>((resolve) => {- releasePersist = () => resolve({});- }),+ () =>+ new Promise<Record<string, never>>((resolve) => {+ releasePersist = () => resolve({});+ }),);h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {await persistQueuedUserMessage(sessionId, sendOpts);@@ -6542,9 +6866,10 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()const sid = 'user-error-during-persist';let releasePersist!: () => void;mocks.createMessage.mockImplementationOnce(- () => new Promise<Record<string, never>>((resolve) => {- releasePersist = () => resolve({});- }),+ () =>+ new Promise<Record<string, never>>((resolve) => {+ releasePersist = () => resolve({});+ }),);h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {await persistQueuedUserMessage(sessionId, sendOpts);@@ -6569,7 +6894,9 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()let releaseSend!: () => void;h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {await persistQueuedUserMessage(sessionId, sendOpts);- await new Promise<void>((resolve) => { releaseSend = resolve; });+ await new Promise<void>((resolve) => {+ releaseSend = resolve;+ });return { kind: 'session-dispatch', dispatched: true } as never;});h.coordinator.enqueue(sid, makeItem('c1', 'hb', { origin: schedOrigin }));@@ -6578,7 +6905,11 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()const state = (h.coordinator as unknown as {getState: (id: string) => {- activeTurn: { persisted: boolean; sendStarted: boolean; dispatchLifecycle?: string } | null;+ activeTurn: {+ persisted: boolean;+ sendStarted: boolean;+ dispatchLifecycle?: string;+ } | null;};}).getState(sid);@@ -6601,7 +6932,9 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()let releaseSend!: () => void;h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {await persistQueuedUserMessage(sessionId, sendOpts);- await new Promise<void>((resolve) => { releaseSend = resolve; });+ await new Promise<void>((resolve) => {+ releaseSend = resolve;+ });return { kind: 'session-dispatch', dispatched: true } as never;});h.coordinator.enqueue(sid, makeItem('c1', 'typed by hand'));@@ -6735,11 +7068,9 @@ describe('AgentInputCoordinator scheduler 排队心跳(review 反馈回归)', ()expect(projection.queuePaused).toBe(true);// 去重视角也看不到被丢弃的 scheduler 项 —— 后续 fire 不会被僵尸挡住。expect(- h.coordinator.hasQueuedItemWhere(- sid,- (item) => item.origin?.kind === 'scheduler',- { includeRecovery: true },- ),+ h.coordinator.hasQueuedItemWhere(sid, (item) => item.origin?.kind === 'scheduler', {+ includeRecovery: true,+ }),).toBe(false);});@@ -6789,7 +7120,11 @@ describe('AgentInputCoordinator replaceQueuedMessage(Orca lead 排队消息修h.coordinator.enqueue(sid, makeItem('q-3', 'third'));await flush();- const replaced = h.coordinator.replaceQueuedMessage(sid, 'q-2', makeItem('q-2', 'second-edited'));+ const replaced = h.coordinator.replaceQueuedMessage(+ sid,+ 'q-2',+ makeItem('q-2', 'second-edited'),+ );expect(replaced).toBe(true);const projection = latestProjection(h.projections);@@ -6895,11 +7230,7 @@ describe('AgentInputCoordinator 中断自动续跑', () => {runId: 'run-1',},});- await failAfterDispatch(- h,- sid,- item,- );+ await failAfterDispatch(h, sid, item);expect(latestProjection(h.projections).recovery?.kind).toBe('active-turn');expect(h.onResumableTurnError).toHaveBeenCalledWith(@@ -7486,7 +7817,9 @@ describe('AgentInputCoordinator 中断自动续跑', () => {await flush();expect(h.coordinator.isAutoResumePending(sid)).toBe(false);- expect(h.onUserEnqueue, 'host 必须先释放退避簿记与 Agent Island filter').toHaveBeenCalledWith(sid);+ expect(h.onUserEnqueue, 'host 必须先释放退避簿记与 Agent Island filter').toHaveBeenCalledWith(+ sid,+ );});it('recovery 已被用户清掉时 autoRetryLastError 返回 false(调用方据此回滚额度)', async () => {@@ -7570,10 +7903,7 @@ describe('AgentInputCoordinator 中断自动续跑', () => {await expect(retry).resolves.toBe('superseded');await flush();- expect(- h.sendToAgent.mock.calls.length,- '不许往已经终止的会话补发续跑',- ).toBe(sendCallsBefore);+ expect(h.sendToAgent.mock.calls.length, '不许往已经终止的会话补发续跑').toBe(sendCallsBefore);});it('延后结算:候选期不发布 error(一帧都不闪),接管后只有活动行', async () => {@@ -7695,10 +8025,9 @@ describe('AgentInputCoordinator 中断自动续跑', () => {h.coordinator.autoRetryLastError(sid, TAKEOVER_INFO.sessionTotal),).resolves.toBe('superseded');await flush();- expect(- h.sendToAgent.mock.calls.length,- '不许在用户消息之前插一条自动续跑',- ).toBe(sendCallsBefore);+ expect(h.sendToAgent.mock.calls.length, '不许在用户消息之前插一条自动续跑').toBe(+ sendCallsBefore,+ );});it('延后结算:非候选错误照旧立刻呈现(确定性失败不受本机制影响)', async () => {@@ -7715,7 +8044,9 @@ describe('AgentInputCoordinator 中断自动续跑', () => {h.coordinator.enqueue(sid, makeItem('q-first', 'original long task'));await flush();- h.coordinator.onTurnEvent(sid, 'error', 'Invalid API key', { sdkError: 'authentication_failed' });+ h.coordinator.onTurnEvent(sid, 'error', 'Invalid API key', {+ sdkError: 'authentication_failed',+ });await flush();expect(latestProjection(h.projections).error, '认证失效必须立刻报,不许被按住').toBe('Invalid API key',diff --git a/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.tsindex f12afedc59..1a66908270 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts@@ -23,6 +23,7 @@ vi.mock('../../logger.js', () => ({}));vi.mock('../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: vi.fn(),}));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex e72048bf18..f465d2659b 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -439,6 +439,94 @@ describe('maker SEND transaction', () => {expect(cleanupBeforeAcceptance).toHaveBeenCalledTimes(1);});+ it('preserves local media when onAccepted persisted the row before a late abort returns accepted=false', async () => {+ const cleanupBeforeAcceptance = vi.fn(async () => {});+ const cleanupAfterAcceptance = vi.fn();+ const materializeDirectSendOssAttachments = vi.fn(async () => ({+ message: { type: 'user', content: 'materialized' },+ sendOpts: undefined,+ cleanupBeforeAcceptance,+ cleanupAfterAcceptance,+ }));+ const session = createSession({+ send: vi.fn(async (_message, opts) => {+ await opts?.onAccepted?.();+ return {+ accepted: false,+ reason: 'cancelled-before-dispatch',+ } satisfies SessionSendResult;+ }),+ });+ const { deps } = createDeps({+ getSession: vi.fn(() => session),+ materializeDirectSendOssAttachments,+ });+ const transaction = createMakerSendTransaction(deps);++ await expect(+ transaction.sendToAgentAccepted(+ 'session-1',+ { type: 'user', content: 'hello' },+ undefined,+ {+ persistUserMessage: {+ clientId: 'client-1',+ content: 'hello',+ },+ },+ ),+ ).resolves.toMatchObject({ accepted: false });++ expect(deps.createDbMessage).toHaveBeenCalledTimes(1);+ expect(cleanupBeforeAcceptance).not.toHaveBeenCalled();+ expect(cleanupAfterAcceptance).toHaveBeenCalledTimes(1);+ });++ it('rewinds a persisted user row when clear wins during onPersisted before dispatch', async () => {+ let clearBoundaryCurrent = true;+ let observedGeneration: number | undefined;+ const rewindPersistedUserMessageAfterClear = vi.fn(async () => {});+ const onPersisted = vi.fn(async () => {+ clearBoundaryCurrent = false;+ throw new Error('[SEND_CANCELLED_BEFORE_DISPATCH] clear won before dispatch');+ });+ const session = createSession({+ send: vi.fn(async (_message, opts) => {+ await opts?.onAccepted?.();+ return { accepted: true } satisfies SessionSendResult;+ }),+ });+ const { deps } = createDeps({+ getSession: vi.fn(() => session),+ isClearBoundaryCurrent: vi.fn((_sessionId, _expectedBoundary, expectedGeneration) => {+ observedGeneration = expectedGeneration;+ return clearBoundaryCurrent;+ }),+ rewindPersistedUserMessageAfterClear,+ });+ const transaction = createMakerSendTransaction(deps);++ await expect(+ transaction.sendToAgentAccepted('session-1', 'hello', undefined, {+ persistUserMessage: {+ clientId: 'client-clear-race',+ content: 'hello',+ expectedClearBoundaryMs: null,+ expectedInputGeneration: 7,+ onPersisted,+ },+ }),+ ).rejects.toThrow('clear won before dispatch');++ expect(deps.createDbMessage).toHaveBeenCalledTimes(1);+ expect(onPersisted).toHaveBeenCalledTimes(1);+ expect(observedGeneration).toBe(7);+ expect(rewindPersistedUserMessageAfterClear).toHaveBeenCalledWith(+ 'session-1',+ 'client-clear-race',+ );+ });+it('cleans direct OSS materializations when vendor send throws before dispatch', async () => {const cleanupBeforeAcceptance = vi.fn(async () => {});const materializeDirectSendOssAttachments = vi.fn(async () => ({@@ -466,11 +554,40 @@ describe('maker SEND transaction', () => {it('keeps local OSS materializations after accepted vendor dispatch', async () => {const cleanupAfterAcceptance = vi.fn();const cleanupBeforeAcceptance = vi.fn(async () => {});+ const cleanupLocalMaterialization = vi.fn(async () => {});+ const materializeDirectSendOssAttachments = vi.fn(async () => ({+ message: { type: 'user', content: 'materialized' },+ sendOpts: undefined,+ cleanupAfterAcceptance,+ cleanupBeforeAcceptance,+ cleanupLocalMaterialization,+ }));+ const { deps } = createDeps({ materializeDirectSendOssAttachments });+ const transaction = createMakerSendTransaction(deps);++ await expect(+ transaction.sendToAgentAccepted('session-1', 'hello', undefined, {+ persistUserMessage: {+ clientId: 'client-1',+ content: 'hello',+ },+ }),+ ).resolves.toMatchObject({ accepted: true });+ expect(cleanupAfterAcceptance).toHaveBeenCalledTimes(1);+ expect(cleanupBeforeAcceptance).not.toHaveBeenCalled();+ expect(cleanupLocalMaterialization).not.toHaveBeenCalled();+ });++ it('cleans local OSS materializations after accepted direct sends without persistence', async () => {+ const cleanupAfterAcceptance = vi.fn();+ const cleanupBeforeAcceptance = vi.fn(async () => {});+ const cleanupLocalMaterialization = vi.fn(async () => {});const materializeDirectSendOssAttachments = vi.fn(async () => ({message: { type: 'user', content: 'materialized' },sendOpts: undefined,cleanupAfterAcceptance,cleanupBeforeAcceptance,+ cleanupLocalMaterialization,}));const { deps } = createDeps({ materializeDirectSendOssAttachments });const transaction = createMakerSendTransaction(deps);@@ -478,8 +595,10 @@ describe('maker SEND transaction', () => {await expect(transaction.sendToAgentAccepted('session-1', 'hello')).resolves.toMatchObject({accepted: true,});+expect(cleanupAfterAcceptance).toHaveBeenCalledTimes(1);expect(cleanupBeforeAcceptance).not.toHaveBeenCalled();+ expect(cleanupLocalMaterialization).toHaveBeenCalledTimes(1);});it('does not materialize direct OSS attachments when workdir preflight rejects', async () => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/queuedAttachmentOwnership.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/queuedAttachmentOwnership.test.tsnew file mode 100644index 0000000000..97faa99db5--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/queuedAttachmentOwnership.test.ts@@ -0,0 +1,190 @@+import { describe, expect, it, vi } from 'vitest';++import { QueuedAttachmentOwnershipRegistry } from '../queuedAttachmentOwnership';++describe('QueuedAttachmentOwnershipRegistry', () => {+ it('defers discard during persistence and transfers ownership to the durable row', async () => {+ const cleanup = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const ownerId = registry.register('session-1', 'client-1', cleanup);+ registry.activateCurrentOwner('session-1', 'client-1', ownerId!);++ registry.markPersistenceStarted('session-1', 'client-1');+ await registry.discardClient('session-1', 'client-1');+ expect(cleanup).not.toHaveBeenCalled();++ registry.releaseClient('session-1', 'client-1');+ expect(cleanup).not.toHaveBeenCalled();+ });++ it('runs a deferred discard when persistence fails', async () => {+ const cleanup = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const ownerId = registry.register('session-1', 'client-1', cleanup);+ registry.activateCurrentOwner('session-1', 'client-1', ownerId!);++ registry.markPersistenceStarted('session-1', 'client-1');+ await registry.discardClient('session-1', 'client-1');+ await registry.markPersistenceFailed('session-1', 'client-1', {+ retainForRetry: true,+ });++ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it('keeps a retryable owner after persistence fails without a discard', async () => {+ const cleanup = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const ownerId = registry.register('session-1', 'client-1', cleanup);+ registry.activateCurrentOwner('session-1', 'client-1', ownerId!);++ registry.markPersistenceStarted('session-1', 'client-1');+ await registry.markPersistenceFailed('session-1', 'client-1', {+ retainForRetry: true,+ });+ expect(cleanup).not.toHaveBeenCalled();++ await registry.discardClient('session-1', 'client-1');+ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it('cleans a non-retryable owner when persistence fails', async () => {+ const cleanup = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const ownerId = registry.register('session-1', 'client-1', cleanup);+ registry.activateCurrentOwner('session-1', 'client-1', ownerId!);++ registry.markPersistenceStarted('session-1', 'client-1');+ await registry.markPersistenceFailed('session-1', 'client-1', {+ retainForRetry: false,+ });++ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it('holds remote cleanup until the queue crosses a durable boundary', async () => {+ const localCleanup = vi.fn(async () => {});+ const remoteCleanup = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const ownerId = registry.register('session-1', 'client-1', localCleanup, {+ cleanupAfterDurable: remoteCleanup,+ });+ registry.activateCurrentOwner('session-1', 'client-1', ownerId!);++ expect(ownerId).toBeTruthy();+ expect(remoteCleanup).not.toHaveBeenCalled();+ await registry.markDurable('session-1', 'client-1', ownerId!);++ expect(remoteCleanup).toHaveBeenCalledTimes(1);+ expect(localCleanup).not.toHaveBeenCalled();+ await registry.markDurable('session-1', 'client-1', ownerId!);+ expect(remoteCleanup).toHaveBeenCalledTimes(1);++ registry.releaseClient('session-1', 'client-1');+ expect(localCleanup).not.toHaveBeenCalled();+ });++ it('cleans both local and remote ownership on explicit discard', async () => {+ const localCleanup = vi.fn(async () => {});+ const remoteCleanup = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ registry.register('session-1', 'client-1', localCleanup, {+ cleanupAfterDurable: remoteCleanup,+ });++ await registry.discardClient('session-1', 'client-1');++ expect(localCleanup).toHaveBeenCalledTimes(1);+ expect(remoteCleanup).toHaveBeenCalledTimes(1);+ });++ it('retains both ownership callbacks for a retryable persistence failure', async () => {+ const localCleanup = vi.fn(async () => {});+ const remoteCleanup = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const ownerId = registry.register('session-1', 'client-1', localCleanup, {+ cleanupAfterDurable: remoteCleanup,+ });+ registry.activateCurrentOwner('session-1', 'client-1', ownerId!);++ registry.markPersistenceStarted('session-1', 'client-1');+ await registry.markPersistenceFailed('session-1', 'client-1', {+ retainForRetry: true,+ });+ expect(localCleanup).not.toHaveBeenCalled();+ expect(remoteCleanup).not.toHaveBeenCalled();++ await registry.discardClient('session-1', 'client-1');+ expect(localCleanup).toHaveBeenCalledTimes(1);+ expect(remoteCleanup).toHaveBeenCalledTimes(1);+ });++ it('cleans superseded owners while preserving the accepted replacement', async () => {+ const oldLocal = vi.fn(async () => {});+ const oldRemote = vi.fn(async () => {});+ const newLocal = vi.fn(async () => {});+ const newRemote = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const oldOwnerId = registry.register('session-1', 'client-1', oldLocal, {+ cleanupAfterDurable: oldRemote,+ });+ registry.activateCurrentOwner('session-1', 'client-1', oldOwnerId!);+ const newOwnerId = registry.register('session-1', 'client-1', newLocal, {+ cleanupAfterDurable: newRemote,+ });+ registry.activateCurrentOwner('session-1', 'client-1', newOwnerId!);++ registry.markPersistenceStarted('session-1', 'client-1');+ await registry.markPersistenceFailed('session-1', 'client-1', { retainForRetry: true });++ expect(oldLocal).toHaveBeenCalledTimes(1);+ expect(oldRemote).toHaveBeenCalledTimes(1);+ expect(newLocal).not.toHaveBeenCalled();+ expect(newRemote).not.toHaveBeenCalled();++ await registry.discardClient('session-1', 'client-1');+ expect(newLocal).toHaveBeenCalledTimes(1);+ expect(newRemote).toHaveBeenCalledTimes(1);+ });++ it('settles the persisted replacement atomically and cleans the old owner', async () => {+ const oldLocal = vi.fn(async () => {});+ const oldRemote = vi.fn(async () => {});+ const newLocal = vi.fn(async () => {});+ const newRemote = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const oldOwnerId = registry.register('session-1', 'client-1', oldLocal, {+ cleanupAfterDurable: oldRemote,+ });+ registry.activateCurrentOwner('session-1', 'client-1', oldOwnerId!);+ const newOwnerId = registry.register('session-1', 'client-1', newLocal, {+ cleanupAfterDurable: newRemote,+ });+ registry.activateCurrentOwner('session-1', 'client-1', newOwnerId!);++ await registry.settleDurable('session-1', 'client-1');++ expect(oldLocal).toHaveBeenCalledTimes(1);+ expect(oldRemote).toHaveBeenCalledTimes(1);+ expect(newLocal).not.toHaveBeenCalled();+ expect(newRemote).toHaveBeenCalledTimes(1);+ expect(registry.getCurrentOwnerId('session-1', 'client-1')).toBeNull();+ });++ it('does not clean a duplicate materialisation that was never accepted', async () => {+ const acceptedCleanup = vi.fn(async () => {});+ const duplicateCleanup = vi.fn(async () => {});+ const registry = new QueuedAttachmentOwnershipRegistry();+ const acceptedOwnerId = registry.register('session-1', 'client-1', acceptedCleanup);+ registry.activateCurrentOwner('session-1', 'client-1', acceptedOwnerId!);+ registry.register('session-1', 'client-1', duplicateCleanup);++ registry.markPersistenceStarted('session-1', 'client-1');+ await registry.markPersistenceFailed('session-1', 'client-1', { retainForRetry: true });++ expect(duplicateCleanup).toHaveBeenCalledTimes(1);+ expect(acceptedCleanup).not.toHaveBeenCalled();+ await registry.discardClient('session-1', 'client-1');+ expect(acceptedCleanup).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.tsindex 522326d16f..9c29d6f1f5 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts@@ -67,7 +67,10 @@ describe('codex remote drift uses the bridge-clamped memory flag (R2 P2)', () =>// codexRemoteDriftOpts (内部走 remoteMakerMemoryEnabledForBridge)。expect(source).toContain('function remoteMakerMemoryEnabledForBridge()');expect(source).toContain('makerMemoryEnabled: remoteMakerMemoryEnabledForBridge()');- const driftCalls = source.match(/hasPendingRemoteMcpDrift\(live\.remoteHostId, codexRemoteDriftOpts\(\)\)/g) ?? [];+ const driftCalls =+ source.match(+ /hasPendingRemoteMcpDrift\(\s*live\.remoteHostId\s*,\s*codexRemoteDriftOpts\(\)\s*,?\s*\)/g,+ ) ?? [];expect(driftCalls.length).toBe(2);// drift 调用点不得残留裸 manager 现值。expect(source).not.toContain('makerMemoryEnabled: maker.makerMemory?.isEnabled() ?? false');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduleIntervalJsonBoundary.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduleIntervalJsonBoundary.test.tsindex 7bf8eb8004..de4bc1fbf9 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduleIntervalJsonBoundary.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduleIntervalJsonBoundary.test.ts@@ -24,6 +24,7 @@ vi.mock('electron', () => ({}));vi.mock('../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: vi.fn(),}));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/scheduleReadiness.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/scheduleReadiness.test.tsindex 5b2d356c72..7d6e46b464 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/scheduleReadiness.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/scheduleReadiness.test.ts@@ -44,6 +44,7 @@ vi.mock('electron', () => ({}));vi.mock('../../device-link/broadcast-tap.js', () => ({+ getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: h.tapWindowBroadcast,}));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionSendHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionSendHandler.test.tsindex 21ce1c9a7d..c4a41779ca 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionSendHandler.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionSendHandler.test.ts@@ -40,6 +40,48 @@ describe('maker session SEND IPC handler', () => {expect(sendToAgentAccepted).toHaveBeenCalledWith('session-1', message, createOpts, sendOpts);});+ it('runs the clear-boundary fence before a legacy direct send', async () => {+ const harness = new IpcHarness();+ const sendToAgentAccepted = vi.fn().mockResolvedValue({ accepted: true });+ const assertRemoteInputControlBoundary = vi.fn().mockReturnValue({+ expectedClearBoundaryMs: 456,+ expectedInputGeneration: 9,+ });+ const sendOpts = { expectedClearBoundaryMs: 123 };++ registerMakerSessionSendHandler(harness, {+ sendToAgentAccepted,+ assertRemoteInputControlBoundary,+ });++ await harness.invoke(MAKER_INVOKE.SEND, 'session-1', 'hello', undefined, sendOpts);++ expect(assertRemoteInputControlBoundary).toHaveBeenCalledWith('session-1', sendOpts);+ expect(sendToAgentAccepted).toHaveBeenCalledWith(+ 'session-1',+ 'hello',+ undefined,+ { expectedClearBoundaryMs: 456, expectedInputGeneration: 9 },+ );+ });++ it('keeps a validated clear token when the optional boundary hook is absent', async () => {+ const harness = new IpcHarness();+ const sendToAgentAccepted = vi.fn().mockResolvedValue({ accepted: true });+ const sendOpts = { expectedClearBoundaryMs: 123, messageUuid: 'msg-1' };++ registerMakerSessionSendHandler(harness, { sendToAgentAccepted });++ await harness.invoke(MAKER_INVOKE.SEND, 'session-1', 'hello', undefined, sendOpts);++ expect(sendToAgentAccepted).toHaveBeenCalledWith(+ 'session-1',+ 'hello',+ undefined,+ sendOpts,+ );+ });+it('keeps empty string sessionId on the send transaction path for compatibility', async () => {const harness = new IpcHarness();const result = { accepted: false, reason: 'NOT_FOUND' };diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex 9edaf80fbf..2dd0ad6a4e 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -46,15 +46,13 @@ import {buildMakerUserMessage,getAgentInputAttachmentBlockType,getAgentFacingText,+ normalizeAgentInputClearBoundaryMs,projectionRetryText,sanitizeQueuedMessageForPersistence,updateQueuedMessageContent,updateQueuedMessageText,} from '../../shared/agentInputQueue.js';-import {- CONTINUE_AFTER_ERROR_PROMPT,- syntheticTriggerKind,-} from '../../shared/interruptedTurn.js';+import { CONTINUE_AFTER_ERROR_PROMPT, syntheticTriggerKind } from '../../shared/interruptedTurn.js';import { attachSessionReferenceMetadata } from '../../shared/sessionReferenceMetadata.js';const log = createLogger('maker-input-coordinator');@@ -156,10 +154,12 @@ function stripQueuedMessageImages(item: AgentInputQueuedMessage): AgentInputQueu}function hasRetryableQueuedContent(item: AgentInputQueuedMessage): boolean {- return getAgentFacingText(item).trim().length > 0- || (item.files?.length ?? 0) > 0- || (item.mentions?.length ?? 0) > 0- || (item.sessionRefs?.length ?? 0) > 0;+ return (+ getAgentFacingText(item).trim().length > 0 ||+ (item.files?.length ?? 0) > 0 ||+ (item.mentions?.length ?? 0) > 0 ||+ (item.sessionRefs?.length ?? 0) > 0+ );}export interface AgentInputSendOpts {@@ -183,11 +183,17 @@ export interface AgentInputSendOpts {* 最终 wire 消息。**由 main 构造,不是 wire 输入。***/fromMobileClient?: boolean;+ /** Main-owned clear token captured when this input became active. */+ expectedClearBoundaryMs?: number | null;+ /** Main-owned input generation captured before async preparation. */+ expectedInputGeneration?: number;persistUserMessage?: {clientId: string;content: string;sdkSessionId?: string;delivery: AgentInputDelivery;+ expectedClearBoundaryMs?: number | null;+ expectedInputGeneration?: number;/*** 本条是自动补发的续跑指令(见 AgentInputQueuedMessage.autoResume)。host 把它合进* 落库 agentMeta.autoResume:renderer 据此隐藏气泡,充值判据据此排除自动消息。@@ -202,6 +208,7 @@ export interface AgentInputSendOpts {shouldBroadcast?: () => boolean;onPersisting?: () => void;onPersisted?: () => void | Promise<void>;+ onPersistFailed?: () => void;};}@@ -253,6 +260,14 @@ export interface AgentInputCoordinatorDeps {hasPendingInteraction: (sessionId: string) => boolean;getAgentKind: (sessionId: string) => AgentInputCreateOpts['agentKind'] | null;getSdkSessionId: (sessionId: string) => Promise<string | undefined>;+ /**+ * Durable user-row writer shared with direct maker sends. The fallback keeps+ * the coordinator usable in narrow unit harnesses, while the registered host+ * injects its FIFO writer so steer and drain persistence share one ordering.+ */+ createUserMessage?: typeof createDbMessage;+ /** Hide a user row that was written after `/clear` won the persistence race. */+ rewindPersistedUserMessageAfterClear?: (sessionId: string, clientId: string) => Promise<void>;/*** interrupted-turn-resume:判断某条已派发 user 消息之后 agent 是否已产出内容* (assistant / tool_use / thinking 持久化行)。retryLastError 用它决定语义:@@ -345,7 +360,10 @@ export interface AgentInputCoordinatorDeps {info: { ghostId: string; ghostName: string; text: string; originalText: string },) => void;/** Awaited after the user message is persisted but before vendor dispatch starts. */- beforeDispatchUserTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void | Promise<void>;+ beforeDispatchUserTurn?: (+ sessionId: string,+ item: AgentInputQueuedMessage,+ ) => void | Promise<void>;/*** Called when a user row crossed the persistence boundary but never reached* vendor dispatch. `cancelled` is an explicit user lifecycle boundary;@@ -356,9 +374,30 @@ export interface AgentInputCoordinatorDeps {item: AgentInputQueuedMessage,disposition: 'cancelled' | 'failed',) => void;+ /** Called immediately before the durable user-row write begins. */+ onUserMessagePersisting?: (sessionId: string, item: AgentInputQueuedMessage) => void;+ /** Called after the durable user row exists; ownership of staged attachments may be released. */+ onUserMessagePersisted?: (sessionId: string, item: AgentInputQueuedMessage) => void;+ /**+ * Called when the user-row write failed. A queued turn remains retryable;+ * an accepted steer does not, because replay could duplicate model input.+ */+ onUserMessagePersistenceFailed?: (+ sessionId: string,+ item: AgentInputQueuedMessage,+ opts: { retainForRetry: boolean },+ ) => void;+ /**+ * The delivery pipeline rejected this item for a technical/policy reason+ * before vendor dispatch. Unlike Stop/remove/clear, this is a real failed+ * attempt rather than explicit user cancellation.+ *//** Technical or policy rejection before vendor dispatch. */onRejectedUserTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void;- onAcceptedQueuedMessage?: (sessionId: string, item: AgentInputQueuedMessage) => void | Promise<void>;+ onAcceptedQueuedMessage?: (+ sessionId: string,+ item: AgentInputQueuedMessage,+ ) => void | Promise<void>;/*** Awaited only after vendor dispatch is irreversible (`accepted=true`).* Hosts use this for side effects that must not run on cancelled-before-dispatch@@ -420,7 +459,10 @@ export interface AgentInputCoordinatorDeps {* 快照(items 为空 = 删行),实现方自行 fire-and-forget + 保序,绝不阻塞派发;* loadQueueSnapshot:ensureQueueRestored 懒恢复时读回。两者要么都注入要么都不注入。*/- persistQueueSnapshot?: (sessionId: string, items: AgentInputQueuedMessage[]) => void | Promise<void>;+ persistQueueSnapshot?: (+ sessionId: string,+ items: AgentInputQueuedMessage[],+ ) => void | Promise<void>;loadQueueSnapshot?: (sessionId: string) => Promise<AgentInputQueuedMessage[]>;getPersistedClientIds?: (sessionId: string, clientIds: string[]) => Promise<Set<string>>;}@@ -431,6 +473,7 @@ interface ActiveTurn {messageUuid: string;createdAt: string;generation: number;+ clearBoundaryMs: number | null;persisted: boolean;persisting: boolean;sendStarted: boolean;@@ -447,7 +490,8 @@ interface PendingCompactRequest {waitForClientIds: string[];}-type ActiveTurnDispatchLifecycle = 'preparing' | 'awaiting-dispatch-hooks' | 'sending' | 'dispatched';+type ActiveTurnDispatchLifecycle =+ 'preparing' | 'awaiting-dispatch-hooks' | 'sending' | 'dispatched';type ActiveTurnTerminalEvent =| { type: 'done' }@@ -471,7 +515,10 @@ type ActiveTurnTerminalEvent =supersededByUser?: boolean;};-type AgentInputSendFailure = Extract<AgentInputSendResult, { accepted: false } | { dispatched: false }>;+type AgentInputSendFailure = Extract<+ AgentInputSendResult,+ { accepted: false } | { dispatched: false }+>;interface SessionInputState {pendingQueue: AgentInputQueuedMessage[];@@ -546,6 +593,8 @@ interface SessionInputState {*/recentEnqueuedClientIds: string[];generation: number;+ /** Latest authoritative `/clear` token for device-link optimistic input preconditions. */+ clearBoundaryMs: number | null;}interface PendingAutoResumeRecovery {@@ -558,7 +607,10 @@ interface PendingAutoResumeRecovery {attemptToken: number;}-function createInitialInputState(generation = 0): SessionInputState {+function createInitialInputState(+ generation = 0,+ clearBoundaryMs: number | null = null,+): SessionInputState {return {pendingQueue: [],pendingCompacts: [],@@ -592,16 +644,14 @@ function createInitialInputState(generation = 0): SessionInputState {credentialSwitchRetryGeneration: null,recentEnqueuedClientIds: [],generation,+ clearBoundaryMs,};}-/*** 首次进入 main 队列边界时冻结原始合成指令意图。IPC payload 属不可信输入,* 因此即使 renderer 带了同名字段也必须从当下原始 text 重新计算。*/-function captureOriginalSyntheticTrigger(- item: AgentInputQueuedMessage,-): AgentInputQueuedMessage {+function captureOriginalSyntheticTrigger(item: AgentInputQueuedMessage): AgentInputQueuedMessage {return {...item,originalSyntheticTrigger: syntheticTriggerKind(item.text) ?? undefined,@@ -609,16 +659,28 @@ function captureOriginalSyntheticTrigger(}/**- * 老崩溃快照没有 originalSyntheticTrigger;从仍保留的原始 text 补齐。新版- * 快照则保留首次入队时冻结的值,因为正文可能已经被 Ghost rewrite。+ * Stamp the acceptance boundary with the controlled host's clock. Remote+ * renderer timestamps are presentation data and may come from a device with a+ * different wall clock; they must never decide whether a crash-restored item+ * predates a host-side /clear.*/-function normalizeRestoredSyntheticTrigger(+function stampHostAcceptedAt(item: AgentInputQueuedMessage,+ clearBoundaryMs: number | null,): AgentInputQueuedMessage {- if (- item.originalSyntheticTrigger === 'continue' ||- item.originalSyntheticTrigger === 'generic'- ) {+ // The restore fence is inclusive (`<=`). If a clear and acceptance share a+ // millisecond, the acceptance must still belong to the new epoch; otherwise+ // a crash in that millisecond would silently drop the user's message.+ const minimumPostClearAt = clearBoundaryMs === null ? 0 : clearBoundaryMs + 1;+ return { ...item, hostAcceptedAtMs: Math.max(Date.now(), minimumPostClearAt) };+}++/**+ * 老崩溃快照没有 originalSyntheticTrigger;从仍保留的原始 text 补齐。新版+ * 快照则保留首次入队时冻结的值,因为正文可能已经被 Ghost rewrite。+ */+function normalizeRestoredSyntheticTrigger(item: AgentInputQueuedMessage): AgentInputQueuedMessage {+ if (item.originalSyntheticTrigger === 'continue' || item.originalSyntheticTrigger === 'generic') {return item;}return captureOriginalSyntheticTrigger(item);@@ -652,8 +714,10 @@ function isSessionRunningError(err: unknown): boolean {const code = (err as { code?: unknown }).code;if (code === 'SESSION_RUNNING') return true;const message = (err as { message?: unknown }).message;- return typeof message === 'string'- && (message.startsWith('SESSION_RUNNING:') || message.startsWith('[SESSION_RUNNING]'));+ return (+ typeof message === 'string' &&+ (message.startsWith('SESSION_RUNNING:') || message.startsWith('[SESSION_RUNNING]'))+ );}function isSessionRunningSendFailure(result: AgentInputSendFailure): boolean {@@ -719,11 +783,9 @@ function isUiContinuationItem(item: AgentInputQueuedMessage): boolean {function isActiveTurnBeforeVendorDispatch(active: ActiveTurn): boolean {return (!isActiveTurnDispatched(active) &&- (- !active.sendStarted ||+ (!active.sendStarted ||active.persisting ||- active.dispatchLifecycle === 'awaiting-dispatch-hooks'- )+ active.dispatchLifecycle === 'awaiting-dispatch-hooks'));}@@ -758,6 +820,16 @@ function sendFailureLogFields(result: AgentInputSendFailure): Record<string, unkexport class AgentInputCoordinator {private readonly states = new Map<string, SessionInputState>();private readonly steerAbortControllers = new Map<string, Map<string, AbortController>>();+ /**+ * One clear/stop-scoped cancellation boundary per session generation. The+ * vendor adapters can spend time converting attachments after the final+ * synchronous fence; aborting this signal keeps that late work from reaching+ * the provider after the input epoch has been superseded.+ */+ private readonly inputBoundaryAbortControllers = new Map<+ string,+ { generation: number; controller: AbortController }+ >();/*** 队列快照恢复簿记(issue #761)。故意放在 SessionInputState **外面**:* clearSession 会整体重建 state,若 restored 标记跟着 state 走,清空后的@@ -798,6 +870,62 @@ export class AgentInputCoordinator {return this.toProjection(sessionId, this.getState(sessionId));}+ /**+ * Capture/check the session input generation around IPC-side async+ * preparation. clearSession replaces the state and increments this value;+ * a handler that started before that boundary must return the current+ * projection instead of committing stale input into the new queue.+ */+ getGeneration(sessionId: string): number {+ return this.getState(sessionId).generation;+ }++ /** Main-only signal for a content-bearing input transaction. */+ getInputAbortSignal(sessionId: string, generation = this.getGeneration(sessionId)): AbortSignal {+ if (!this.isGenerationCurrent(sessionId, generation)) {+ const stale = new AbortController();+ stale.abort();+ return stale.signal;+ }+ const current = this.inputBoundaryAbortControllers.get(sessionId);+ if (current && current.generation === generation && !current.controller.signal.aborted) {+ return current.controller.signal;+ }+ const controller = new AbortController();+ this.inputBoundaryAbortControllers.set(sessionId, { generation, controller });+ return controller.signal;+ }++ private abortInputBoundary(sessionId: string): void {+ const current = this.inputBoundaryAbortControllers.get(sessionId);+ if (!current) return;+ current.controller.abort();+ this.inputBoundaryAbortControllers.delete(sessionId);+ }++ isGenerationCurrent(sessionId: string, generation: number): boolean {+ return this.getState(sessionId).generation === generation;+ }++ getClearBoundaryMs(sessionId: string): number | null {+ return this.getState(sessionId).clearBoundaryMs;+ }++ /**+ * Rehydrate the authoritative clear token after a host restart. The+ * coordinator state is intentionally in-memory, while `sessions.cleared_at`+ * survives restart; remote preconditions must compare against the latter+ * before accepting the first post-restart input.+ */+ observeClearBoundary(sessionId: string, clearedAt: unknown): void {+ const boundary = normalizeAgentInputClearBoundaryMs(clearedAt);+ if (typeof boundary !== 'number') return;+ const state = this.getState(sessionId);+ if (state.clearBoundaryMs === null || boundary > state.clearBoundaryMs) {+ state.clearBoundaryMs = boundary;+ }+ }+/*** 懒恢复崩溃前持久化的排队输入(issue #761)。IPC 入口(getProjection /* enqueue / steer / compact)在处理前调用;并发调用共享同一 promise,@@ -856,6 +984,20 @@ export class AgentInputCoordinator {sessionId,items.map((i) => i.clientId),);+ const currentState = this.getState(sessionId);+ if (currentState !== preState || currentState.generation !== preGeneration) {+ // Clear/stop may win while the durable de-duplication query is in+ // flight. Do not merge the stale snapshot into the new generation;+ // close the restore window and let the current in-memory state own+ // the next persisted snapshot.+ this.restoredQueueSessions.add(sessionId);+ this.queueRestorePromises.delete(sessionId);+ for (const item of items) {+ this.deps.onDiscardedQueuedMessage?.(sessionId, item);+ }+ this.maybePersistQueueSnapshot(sessionId);+ return;+ }for (const cid of persisted) existingIds.add(cid);} catch (err) {log.warn('getPersistedClientIds failed during restore; will retry on next entry', {@@ -865,19 +1007,55 @@ export class AgentInputCoordinator {throw err;}}+ // A clear boundary survives process restart while the queue snapshot is+ // only an optimization. Compare it with the host-owned acceptance receipt;+ // chatMessage.createdAt belongs to the controller and can be skewed by+ // hours across devices. An old/invalid receipt is fail-closed once a+ // boundary is known so it cannot resurrect pre-clear content after a+ // weak-network restart.+ const clearBoundaryMs = state.clearBoundaryMs;+ const staleClearItems: AgentInputQueuedMessage[] = [];+ const boundaryFilteredItems = items.filter((item) => {+ if (clearBoundaryMs === null) return true;+ const acceptedAtMs = item.hostAcceptedAtMs;+ if (+ typeof acceptedAtMs !== 'number' ||+ !Number.isFinite(acceptedAtMs) ||+ acceptedAtMs <= clearBoundaryMs+ ) {+ staleClearItems.push(item);+ return false;+ }+ return true;+ });+ if (staleClearItems.length > 0) {+ for (const item of staleClearItems) {+ this.deps.onDiscardedQueuedMessage?.(sessionId, item);+ }+ log.info('dropped pre-clear queue item(s) from crash snapshot', {+ sessionId,+ boundaryMs: clearBoundaryMs,+ dropped: staleClearItems.length,+ });+ }// 标记恢复完成:所有 async 工作已结束,此后 getDrainableHead 放行、// maybePersistQueueSnapshot 开闸。this.restoredQueueSessions.add(sessionId);- // 用读回内容预热变更检测缓存:内存态与 DB 一致时(最常见:空快照 + 空队列)- // 收口点直接跳过,避免每次打开会话都发一次冗余覆盖写/删除。- this.lastQueueSnapshotJson.set(sessionId, JSON.stringify(items));+ // 用读回内容预热变更检测缓存:没有丢弃/去重项时(最常见:空快照 + 空队列)+ // 收口点直接跳过,避免每次打开会话都发一次冗余覆盖写/删除。只要有丢弃项就+ // 留空,让 maybePersistQueueSnapshot 把清理后的快照写回盘面。+ if (staleClearItems.length === 0) {+ this.lastQueueSnapshotJson.set(sessionId, JSON.stringify(items));+ } else {+ this.lastQueueSnapshotJson.delete(sessionId);+ }// scheduler 撞忙排队项不跨重启恢复(persist 侧已不再写入,这里兜老快照):// 静默会话的恢复队列处于 queuePausedByRestore 暂停态,自动化项等不来"用户// 显式输入"的放行,会永远滞留;同任务去重又会把它当在途,后续每轮 fire 都// 判 duplicate 顺延 —— 无人值守自动化整体停摆(PR #972 review P1)。直接// 丢弃并走 onDiscarded 释放回调注册表;下一轮 cron fire 按当下状态重新走// 排队/直发,不丢任务只丢陈旧副本。- const restorable = items.filter((item) => !existingIds.has(item.clientId));+ const restorable = boundaryFilteredItems.filter((item) => !existingIds.has(item.clientId));const staleSchedulerItems = restorable.filter((item) => item.origin?.kind === 'scheduler');const restored = restorable.filter((item) => item.origin?.kind !== 'scheduler');if (staleSchedulerItems.length > 0) {@@ -972,6 +1150,23 @@ export class AgentInputCoordinator {return recovery?.kind === 'active-turn' ? predicate(recovery.item) : false;}+ /** Includes the recent idempotency window used by remote weak-link retries. */+ hasKnownClientId(sessionId: string, clientId: string): boolean {+ if (!clientId) return false;+ const state = this.getState(sessionId);+ return (+ state.pendingQueue.some((item) => item.clientId === clientId) ||+ state.activeTurn?.item?.clientId === clientId ||+ state.steeringQueueClientIds.includes(clientId) ||+ state.recentEnqueuedClientIds.includes(clientId) ||+ (state.recovery?.kind === 'active-turn' && state.recovery.item.clientId === clientId)+ );+ }++ hasPendingQueueItem(sessionId: string, clientId: string): boolean {+ return this.getState(sessionId).pendingQueue.some((item) => item.clientId === clientId);+ }+/*** 崩溃恢复快照是否已成功读回(无快照配置视为已恢复)。ensureQueueRestored* 读快照失败时**内部吞错**并保持未恢复态(下次入口重试),调用方无法从@@ -1044,17 +1239,25 @@ export class AgentInputCoordinator {private isDuplicateEnqueueClientId(state: SessionInputState, clientId: string): boolean {if (!clientId) return false;return (- state.pendingQueue.some((q) => q.clientId === clientId)- || state.activeTurn?.item?.clientId === clientId- || state.steeringQueueClientIds.includes(clientId)- || state.recentEnqueuedClientIds.includes(clientId)+ state.pendingQueue.some((q) => q.clientId === clientId) ||+ state.activeTurn?.item?.clientId === clientId ||+ state.steeringQueueClientIds.includes(clientId) ||+ state.recentEnqueuedClientIds.includes(clientId));}private rememberEnqueuedClientId(state: SessionInputState, clientId: string): void {if (!clientId) return;+ // Treat the bounded list as an MRU window. A queued item may be accepted+ // later as a same-turn steer; refreshing it here keeps the post-acceptance+ // weak-link retry window intact without growing a second dedupe mechanism.+ state.recentEnqueuedClientIds = state.recentEnqueuedClientIds.filter(+ (knownClientId) => knownClientId !== clientId,+ );state.recentEnqueuedClientIds.push(clientId);- if (state.recentEnqueuedClientIds.length > AgentInputCoordinator.RECENT_ENQUEUED_CLIENT_IDS_LIMIT) {+ if (+ state.recentEnqueuedClientIds.length > AgentInputCoordinator.RECENT_ENQUEUED_CLIENT_IDS_LIMIT+ ) {state.recentEnqueuedClientIds.shift();}}@@ -1062,7 +1265,12 @@ export class AgentInputCoordinator {enqueue(sessionId: string,item: AgentInputQueuedMessage,- opts?: { wasFirst?: boolean; sendAtMs?: number; resumeRestorePausedQueue?: boolean },+ opts?: {+ wasFirst?: boolean;+ sendAtMs?: number;+ resumeRestorePausedQueue?: boolean;+ onDuplicate?: () => void;+ },): AgentInputProjection {const state = this.getState(sessionId);item = captureOriginalSyntheticTrigger(item);@@ -1077,8 +1285,10 @@ export class AgentInputCoordinator {sessionId,clientId: item.clientId,});+ opts?.onDuplicate?.();return this.getProjection(sessionId);}+ item = stampHostAcceptedAt(item, state.clearBoundaryMs);this.rememberEnqueuedClientId(state, item.clientId);// 真的有一条**新**消息进队了 = 这个会话被别的内容推进(见 deps.onUserEnqueue)。// 必须放在幂等去重**之后**: 被去重丢弃的重传(弱网 / 移动端补发)压根没推进任何@@ -1172,7 +1382,11 @@ export class AgentInputCoordinator {return this.getProjection(sessionId);}- async compact(sessionId: string, createOpts: AgentInputCreateOpts, opts?: { userName?: string }): Promise<AgentInputProjection> {+ async compact(+ sessionId: string,+ createOpts: AgentInputCreateOpts,+ opts?: { userName?: string },+ ): Promise<AgentInputProjection> {const state = this.getState(sessionId);// 手动 /compact 是用户接管,与 composer 新消息同语义。先撤掉尚未跨过// vendor dispatch 的隐藏 scheduler 续跑,再让 host 终止对应 run waiter;@@ -1233,6 +1447,7 @@ export class AgentInputCoordinator {messageUuid: crypto.randomUUID(),createdAt: new Date().toISOString(),generation: state.generation,+ clearBoundaryMs: state.clearBoundaryMs,persisted: false,persisting: false,sendStarted: false,@@ -1255,12 +1470,20 @@ export class AgentInputCoordinator {messageUuid: active.messageUuid,userName: request.userName,throwOnStartFailure: true,+ expectedClearBoundaryMs: active.clearBoundaryMs,+ expectedInputGeneration: active.generation,},);if (!this.isActiveTurnCurrent(sessionId, active)) return this.getProjection(sessionId);if (!isSendDispatched(result)) {if (isSessionRunningSendFailure(result)) {- return this.deferCompactAfterSessionRunning(sessionId, active, request, reason, sendFailureMessage(result));+ return this.deferCompactAfterSessionRunning(+ sessionId,+ active,+ request,+ reason,+ sendFailureMessage(result),+ );}const latest = this.getState(sessionId);latest.activeTurn = null;@@ -1287,7 +1510,13 @@ export class AgentInputCoordinator {} catch (err) {if (!this.isActiveTurnCurrent(sessionId, active)) return this.getProjection(sessionId);if (isSessionRunningError(err)) {- return this.deferCompactAfterSessionRunning(sessionId, active, request, reason, errorMessage(err));+ return this.deferCompactAfterSessionRunning(+ sessionId,+ active,+ request,+ reason,+ errorMessage(err),+ );}const latest = this.getState(sessionId);latest.activeTurn = null;@@ -1306,11 +1535,22 @@ export class AgentInputCoordinator {}}- async steer(sessionId: string, item: AgentInputQueuedMessage, opts?: { removeFromQueue?: boolean; touchUserSend?: boolean }): Promise<boolean> {+ async steer(+ sessionId: string,+ item: AgentInputQueuedMessage,+ opts?: { removeFromQueue?: boolean; touchUserSend?: boolean },+ ): Promise<boolean> {const state = this.getState(sessionId);+ // Capture the clear boundary before any screening/reference/steer await. The+ // live state may advance when `/clear` wins the race; this turn must retain+ // the token from the moment it entered the steer transaction.+ const steerClearBoundaryMs = state.clearBoundaryMs;+ let itemAlreadyOwnedByHost = false;+ let steersStoredQueueItem = false;if (opts?.removeFromQueue) {const storedItem = state.pendingQueue.find((queued) => queued.clientId === item.clientId);if (storedItem) {+ steersStoredQueueItem = true;// Renderer projections intentionally omit trusted reference bodies. The main-owned// queue row is authoritative for identity/text. A restored device-link row can retain// only the fail-closed marker, though; in that case the validated inbound snapshot is@@ -1338,8 +1578,28 @@ export class AgentInputCoordinator {item = canRestoreSnapshot? { ...storedItem, trustedSessionReferenceContexts: incomingContexts }: storedItem;+ itemAlreadyOwnedByHost =+ typeof item.hostAcceptedAtMs === 'number' && Number.isFinite(item.hostAcceptedAtMs);}}+ if (state.steeringQueueClientIds.includes(item.clientId)) {+ log.info('steer ignored: duplicate in-flight clientId (control-side resend)', {+ sessionId,+ clientId: item.clientId,+ });+ return true;+ }+ if (!steersStoredQueueItem && this.isDuplicateEnqueueClientId(state, item.clientId)) {+ log.info('steer ignored: duplicate clientId (control-side resend)', {+ sessionId,+ clientId: item.clientId,+ });+ return true;+ }+ // A row already owned by the host keeps its original receipt. A direct+ // composer steer has no host-owned row yet, so stamp it before any async+ // screening/dispatch work begins.+ if (!itemAlreadyOwnedByHost) item = stampHostAcceptedAt(item, steerClearBoundaryMs);if (state.steeringQueueClientIds.length > 0 ||state.queueAbortPending ||@@ -1384,6 +1644,7 @@ export class AgentInputCoordinator {state.steeringQueueClientIds.push(item.clientId);}const steerAbort = new AbortController();+ const inputBoundarySignal = this.getInputAbortSignal(sessionId, steerGeneration);this.registerSteerAbortController(sessionId, item.clientId, steerAbort);this.emit(sessionId);@@ -1404,7 +1665,9 @@ export class AgentInputCoordinator {// 拦截即终态:不注入、不落库,气泡由 onUserMessageBlocked 广播降级;// 返回 true(已处置),renderer 不再回滚重试。this.clearSteerAbortController(sessionId, item.clientId);- cur.steeringQueueClientIds = cur.steeringQueueClientIds.filter((id) => id !== item.clientId);+ cur.steeringQueueClientIds = cur.steeringQueueClientIds.filter(+ (id) => id !== item.clientId,+ );if (opts?.removeFromQueue) {cur.pendingQueue = cur.pendingQueue.filter((q) => q.clientId !== item.clientId);this.removePendingCompactWaitClientId(cur, item.clientId);@@ -1441,23 +1704,26 @@ export class AgentInputCoordinator {try {const referenceContexts = await this.resolveReferenceContexts(item);- item.persistedContent = attachSessionReferenceMetadata(item.persistedContent, referenceContexts);- await this.deps.steerToAgent(- sessionId,- buildMakerUserMessage(item, referenceContexts),- {- messageUuid,- userName: item.userName,- signal: steerAbort.signal,- // 同 drain:steer 投递也在入队时的 async context 之外。- ...(item.fromMobileClient ? { fromMobileClient: true } : {}),- },+ item.persistedContent = attachSessionReferenceMetadata(+ item.persistedContent,+ referenceContexts,);+ await this.deps.steerToAgent(sessionId, buildMakerUserMessage(item, referenceContexts), {+ messageUuid,+ userName: item.userName,+ signal: AbortSignal.any([inputBoundarySignal, steerAbort.signal]),+ expectedClearBoundaryMs: steerClearBoundaryMs,+ expectedInputGeneration: steerGeneration,+ // 同 drain:steer 投递也在入队时的 async context 之外。+ ...(item.fromMobileClient ? { fromMobileClient: true } : {}),+ });} catch (err) {this.clearSteerAbortController(sessionId, item.clientId);const latest = this.getState(sessionId);const markerStillPresent = latest.steeringQueueClientIds.includes(item.clientId);- latest.steeringQueueClientIds = latest.steeringQueueClientIds.filter((id) => id !== item.clientId);+ latest.steeringQueueClientIds = latest.steeringQueueClientIds.filter(+ (id) => id !== item.clientId,+ );if (isNoActiveTurnError(err)) {// maker-core 权威判定无活跃 turn — 先让 host 校准可能 stale 的 busy@@ -1525,10 +1791,7 @@ export class AgentInputCoordinator {// 不确定投递的保护性暂停必须由用户显式处置,不许新输入静默放行。latest.queuePausedByRestore = false;}- } else if (- isSteerDeliveryUncertainError(err) &&- latest.generation === steerGeneration- ) {+ } else if (isSteerDeliveryUncertainError(err) && latest.generation === steerGeneration) {// Stop/close 赢在 ack 返回前(marker 已被 stop 清):RPC 已发出,结果同样// 不确定,消息必须有落点(尤其 composer 入口无队列行的场景,review #939// 第四轮)。物化进暂停队列交用户处置。generation 守卫:clearSession 是@@ -1550,14 +1813,20 @@ export class AgentInputCoordinator {const accepted = this.getState(sessionId);if (!accepted.steeringQueueClientIds.includes(item.clientId)) {- log.warn('steer accepted by agent but marker already cancelled (stop/close raced); dropping', {- sessionId,- clientId: item.clientId,- });+ log.warn(+ 'steer accepted by agent but marker already cancelled (stop/close raced); dropping',+ {+ sessionId,+ clientId: item.clientId,+ },+ );this.emit(sessionId);return false;}- accepted.steeringQueueClientIds = accepted.steeringQueueClientIds.filter((id) => id !== item.clientId);+ // steerToAgent has crossed the irreversible delivery boundary. Keep the+ // clientId known even if the subsequent user-row persistence or terminal+ // event fails, otherwise an ACK-loss retry can inject the same text twice.+ this.rememberEnqueuedClientId(accepted, item.clientId);if (opts?.removeFromQueue) {accepted.pendingQueue = accepted.pendingQueue.filter((q) => q.clientId !== item.clientId);this.removePendingCompactWaitClientId(accepted, item.clientId);@@ -1582,23 +1851,39 @@ export class AgentInputCoordinator {delivery: 'steer',messageUuid,createdAt,- generation: accepted.generation,+ generation: steerGeneration,+ clearBoundaryMs: steerClearBoundaryMs,persisted: false,persisting: true,sendStarted: true,dispatchLifecycle: 'dispatched',pendingTerminalEvent: null,- continuationOwnerClientId:- isUiContinuationItem(item)- ? item.clientId- : sameVendorTurn- ? steerContinuationOwnerClientId- : null,+ continuationOwnerClientId: isUiContinuationItem(item)+ ? item.clientId+ : sameVendorTurn+ ? steerContinuationOwnerClientId+ : null,};this.emit(sessionId);const persisted = await this.persistAcceptedUserMessage(sessionId, accepted.activeTurn);- if (persisted !== 'persisted') return false;+ const settled = this.getState(sessionId);+ let releasedSteerMarker = false;+ if (settled.generation === steerGeneration) {+ const remainingSteeringClientIds = settled.steeringQueueClientIds.filter(+ (id) => id !== item.clientId,+ );+ releasedSteerMarker =+ remainingSteeringClientIds.length !== settled.steeringQueueClientIds.length;+ if (releasedSteerMarker) {+ settled.steeringQueueClientIds = remainingSteeringClientIds;+ this.emit(sessionId);+ }+ }+ if (persisted !== 'persisted') {+ if (releasedSteerMarker) this.scheduleDrain(sessionId, 'steer-persistence-settled');+ return false;+ }if (opts?.touchUserSend) this.touchUserSend(sessionId);// 已投递收口(review #939 第二轮 P1):steer ack 可能与 turn 终态乱序——// maker-core 对"server 已接受注入但本地 turn 已终结"按已投递成功返回@@ -1639,11 +1924,15 @@ export class AgentInputCoordinator {return true;}- stop(sessionId: string, opts?: { keepQueue?: boolean; pauseQueue?: boolean }): AgentInputProjection {+ stop(+ sessionId: string,+ opts?: { keepQueue?: boolean; pauseQueue?: boolean },+ ): AgentInputProjection {const state = this.getState(sessionId);const preserveQueue = opts?.keepQueue === true;this.supersedePendingAutoResumeRecoveries(sessionId);this.cancelPreparedAutoResume(sessionId, state);+ this.abortInputBoundary(sessionId);this.abortSteerTransactions(sessionId);this.clearAbortReconcileRetry(state);// Stop 是用户显式收手:凭证切换等待随之取消(保留队列时队首仍在,恢复后会重新进入等待)。@@ -1664,7 +1953,9 @@ export class AgentInputCoordinator {}// 整批丢弃的排队消息同样从未派发:从弱网重发幂等窗口遗忘,允许再次入队。const droppedIds = new Set(droppedQueue.map((q) => q.clientId));- state.recentEnqueuedClientIds = state.recentEnqueuedClientIds.filter((id) => !droppedIds.has(id));+ state.recentEnqueuedClientIds = state.recentEnqueuedClientIds.filter(+ (id) => !droppedIds.has(id),+ );state.pendingCompacts = [];state.queueInteractionLocks = state.queueInteractionLocks.filter((lockId) =>state.interactionLocksPreservedOnStop.includes(lockId),@@ -1696,7 +1987,8 @@ export class AgentInputCoordinator {state.queueExpanded = false;this.emit(sessionId);- this.deps.abortSession(sessionId)+ this.deps+ .abortSession(sessionId).catch((err) => {log.warn('abortSession failed', { sessionId, error: errorMessage(err) });})@@ -1760,10 +2052,7 @@ export class AgentInputCoordinator {* - `superseded`:目标已消失(用户自己接手 / 清了会话)——他已经在处理,别再弹横幅。* - `no-progress`:保留给无法构造安全重试项的异常路径(例如 image-only fallback)。*/- async autoRetryLastError(- sessionId: string,- attemptToken: number,- ): Promise<AutoRetryOutcome> {+ async autoRetryLastError(sessionId: string, attemptToken: number): Promise<AutoRetryOutcome> {const { outcome } = await this.performRetryLastError(sessionId, {auto: true,attemptToken,@@ -1810,7 +2099,7 @@ export class AgentInputCoordinator {let continueItem: AgentInputQueuedMessage | null = null;let progressKnown = false;const previousAutoResumeInfo = opts?.auto ? state.autoResumePending : null;- const attemptToken = opts?.auto ? opts.attemptToken ?? null : null;+ const attemptToken = opts?.auto ? (opts.attemptToken ?? null) : null;const continueText = CONTINUE_AFTER_ERROR_PROMPT;if (recovery.kind === 'active-turn' && this.deps.hasAssistantProgressAfter) {let hasProgress = false;@@ -1848,7 +2137,7 @@ export class AgentInputCoordinator {autoResume: opts?.auto ? true : undefined,// 人工 Retry 是新的真人介入周期,不能继承上一轮隐藏自动消息的标记;自动路径// 则把展示信息随消息落库,成为「已重新连接」活动行的 param 位与展开详情。- autoResumeInfo: opts?.auto ? previousAutoResumeInfo ?? undefined : undefined,+ autoResumeInfo: opts?.auto ? (previousAutoResumeInfo ?? undefined) : undefined,// 附件 / mention 属于原始消息,已在失败 turn 里送达过模型,续跑指令不重带。files: undefined,mentions: undefined,@@ -1872,10 +2161,7 @@ export class AgentInputCoordinator {// queue-head recovery 表示消息从未跨过 accepted 边界,自动重发仍然可能重复一条// 尚未确认是否落库的输入;这条路径继续交给用户。active-turn recovery 则已经落库,// 零产出克隆重发是安全的,连续失败次数由 host 守卫负责止损。- if (- opts?.auto &&- (recovery.kind !== 'active-turn' || (!continueItem && !progressKnown))- ) {+ if (opts?.auto && (recovery.kind !== 'active-turn' || (!continueItem && !progressKnown))) {log.debug('auto retry skipped — progress state is not safe to resend', {sessionId,recoveryKind: recovery.kind,@@ -1887,9 +2173,9 @@ export class AgentInputCoordinator {const previousStickyError = state.stickyError;let retryItem = recovery.kind === 'active-turn' ? recovery.item : null;if (- !continueItem- && retryItem- && isUnsupportedResponsesImageErrorPayload(state.error ?? state.stickyError)+ !continueItem &&+ retryItem &&+ isUnsupportedResponsesImageErrorPayload(state.error ?? state.stickyError)) {retryItem = stripQueuedMessageImages(retryItem);if (!hasRetryableQueuedContent(retryItem)) {@@ -1914,7 +2200,7 @@ export class AgentInputCoordinator {...(retryItem ?? recovery.item),clientId,autoResume: opts?.auto ? true : undefined,- autoResumeInfo: opts?.auto ? previousAutoResumeInfo ?? undefined : undefined,+ autoResumeInfo: opts?.auto ? (previousAutoResumeInfo ?? undefined) : undefined,// 自动 clone 自身会被 renderer 隐藏,不能再软删原始可见 user 行;人工 Retry// 才用可见克隆取代旧行。显式覆盖也避免继承上一轮的隐藏标记。supersedesUserClientId: opts?.auto ? undefined : recovery.item.clientId,@@ -2031,9 +2317,7 @@ export class AgentInputCoordinator {// sessionRefs. When a trusted snapshot is required, treating undefined// as "no refs" is fail-closed; otherwise updateQueuedMessageText would// re-parse remote text and resolve links in the target device's DB.- const refsForUpdate = requireTrustedSnapshot && sessionRefs === undefined- ? []- : sessionRefs;+ const refsForUpdate = requireTrustedSnapshot && sessionRefs === undefined ? [] : sessionRefs;const updated = updateQueuedMessageText(entry, newText, refsForUpdate);if (requireTrustedSnapshot && updated.sessionRefs && updated.sessionRefs.length > 0) {updated.sessionReferencesRequireTrustedSnapshot = true;@@ -2061,16 +2345,35 @@ export class AgentInputCoordinator {clientId: string,next: AgentInputQueuedMessage,): AgentInputProjection {+ return this.updateContentWithResult(sessionId, clientId, next).projection;+ }++ /**+ * Content replacement variant that exposes whether a pending row was+ * actually replaced. The IPC attachment lifecycle needs this distinction:+ * an update can legitimately become a no-op when the row was dispatched,+ * removed, or rejected by a concurrent steer, and newly materialised local+ * media must then be cleaned instead of being treated as durable.+ */+ updateContentWithResult(+ sessionId: string,+ clientId: string,+ next: AgentInputQueuedMessage,+ ): { projection: AgentInputProjection; updated: boolean } {if (!next.text.trim() && !(next.files && next.files.length > 0)) {- return this.getProjection(sessionId);+ return { projection: this.getProjection(sessionId), updated: false };}const state = this.getState(sessionId);- if (state.steeringQueueClientIds.includes(clientId)) return this.getProjection(sessionId);- state.pendingQueue = state.pendingQueue.map((entry) =>- entry.clientId === clientId ? updateQueuedMessageContent(entry, next) : entry,- );+ if (state.steeringQueueClientIds.includes(clientId)) {+ return { projection: this.getProjection(sessionId), updated: false };+ }+ const index = state.pendingQueue.findIndex((entry) => entry.clientId === clientId);+ if (index < 0) return { projection: this.getProjection(sessionId), updated: false };+ const nextQueue = [...state.pendingQueue];+ nextQueue[index] = updateQueuedMessageContent(state.pendingQueue[index], next);+ state.pendingQueue = nextQueue;this.emit(sessionId);- return this.getProjection(sessionId);+ return { projection: this.getProjection(sessionId), updated: true };}/**@@ -2083,7 +2386,11 @@ export class AgentInputCoordinator {* (身份不变,防止入队去重窗口与崩溃快照错位)。返回是否完成替换 ——* false = 条目已不在 pendingQueue(已派发 / 已移除)、正在 steering 或身份不符。*/- replaceQueuedMessage(sessionId: string, clientId: string, next: AgentInputQueuedMessage): boolean {+ replaceQueuedMessage(+ sessionId: string,+ clientId: string,+ next: AgentInputQueuedMessage,+ ): boolean {if (next.clientId !== clientId || next.chatMessage.clientId !== clientId) return false;const state = this.getState(sessionId);if (state.steeringQueueClientIds.includes(clientId)) return false;@@ -2190,10 +2497,16 @@ export class AgentInputCoordinator {this.deps.noteSessionClearBoundary?.(sessionId, clearedAt);const prev = this.getState(sessionId);this.supersedePendingAutoResumeRecoveries(sessionId);+ const observedClearBoundaryMs = normalizeAgentInputClearBoundaryMs(clearedAt) ?? Date.now();+ const clearBoundaryMs =+ prev.clearBoundaryMs === null+ ? observedClearBoundaryMs+ : Math.max(prev.clearBoundaryMs, observedClearBoundaryMs);this.clearAbortReconcileRetry(prev);this.clearSessionRunningRetry(prev);this.clearCredentialSwitchWait(prev);this.clearPendingExternalTerminalDone(prev);+ this.abortInputBoundary(sessionId);this.abortSteerTransactions(sessionId);for (const item of prev.pendingQueue) {this.deps.onDiscardedQueuedMessage?.(sessionId, item);@@ -2202,7 +2515,7 @@ export class AgentInputCoordinator {// 显式清上下文:强制开启持久化闸门,让 emit 写出空快照(删行),// 即使此前该会话从未触发恢复(否则旧快照残留,下次打开会诈尸)。this.restoredQueueSessions.add(sessionId);- this.states.set(sessionId, createInitialInputState(prev.generation + 1));+ this.states.set(sessionId, createInitialInputState(prev.generation + 1, clearBoundaryMs));this.emit(sessionId);return this.getProjection(sessionId);}@@ -2243,11 +2556,7 @@ export class AgentInputCoordinator {state.activeTurn = null;state.stickyError = null;const schedulerItem = active.item && isSchedulerOriginItem(active.item);- const resumableCandidate = this.isResumableTurnErrorCandidate(- sessionId,- message,- signals,- );+ const resumableCandidate = this.isResumableTurnErrorCandidate(sessionId, message, signals);const outcome = this.setActiveTurnRecovery(state, active.item, {allowSchedulerAutoResume: Boolean(schedulerItem && resumableCandidate),});@@ -2419,6 +2728,7 @@ export class AgentInputCoordinator {this.clearAbortReconcileRetry(state);this.clearSessionRunningRetry(state);this.clearPendingExternalTerminalDone(state);+ this.abortInputBoundary(sessionId);this.abortSteerTransactions(sessionId);const active = state.activeTurn;if (active && !isActiveTurnDispatched(active)) {@@ -2467,7 +2777,8 @@ export class AgentInputCoordinator {private computeQueueSnapshotItems(state: SessionInputState): AgentInputQueuedMessage[] {const active = state.activeTurn;const activeItem =- active?.item && !active.persisted &&+ active?.item &&+ !active.persisted &&!state.pendingQueue.some((q) => q.clientId === active.item?.clientId)? [active.item]: [];@@ -2502,12 +2813,18 @@ export class AgentInputCoordinator {private toProjection(sessionId: string, state: SessionInputState): AgentInputProjection {const pendingQueue = state.pendingQueue.map((item) => this.toProjectedItem(item));- const recovery: AgentInputRecovery = state.recovery?.kind === 'active-turn'- ? { ...state.recovery, item: this.toProjectedItem(state.recovery.item) }- : state.recovery;+ const recovery: AgentInputRecovery =+ state.recovery?.kind === 'active-turn'+ ? { ...state.recovery, item: this.toProjectedItem(state.recovery.item) }+ : state.recovery;return {sessionId,pendingQueue,+ // Modern projections always carry the explicit null token for a session+ // that has never been cleared. Only an older controlled Desktop can+ // omit the field at the wire boundary; keeping null here lets a remote+ // sender safely fence clear/send races from the very first message.+ clearBoundaryMs: state.clearBoundaryMs,continuationInFlightClientId:state.activeTurn?.item && isUiContinuationItem(state.activeTurn.item)? state.activeTurn.item.clientId@@ -2535,6 +2852,7 @@ export class AgentInputCoordinator {/** Renderer projection may carry routing hints, but never quoted history bodies. */private toProjectedItem(item: AgentInputQueuedMessage): AgentInputQueuedMessage {const projected = { ...item };+ delete projected.hostAcceptedAtMs;delete projected.trustedSessionReferenceContexts;delete projected.sessionReferencesRequireTrustedSnapshot;return projected;@@ -2579,9 +2897,13 @@ export class AgentInputCoordinator {return state.activeTurn !== null || this.deps.isTurnRunning(sessionId);}- private getDrainableHead(sessionId: string, state: SessionInputState): AgentInputQueuedMessage | null {+ private getDrainableHead(+ sessionId: string,+ state: SessionInputState,+ ): AgentInputQueuedMessage | null {if (this.queueRestorePromises.has(sessionId)) return null;- if (this.restoreAttempted.has(sessionId) && !this.restoredQueueSessions.has(sessionId)) return null;+ if (this.restoreAttempted.has(sessionId) && !this.restoredQueueSessions.has(sessionId))+ return null;if (state.pendingQueue.length === 0) return null;if (state.queuePaused) return null;if (state.queueAbortPending) return null;@@ -2597,9 +2919,13 @@ export class AgentInputCoordinator {return head;}- private getDrainableCompact(sessionId: string, state: SessionInputState): PendingCompactRequest | null {+ private getDrainableCompact(+ sessionId: string,+ state: SessionInputState,+ ): PendingCompactRequest | null {if (this.queueRestorePromises.has(sessionId)) return null;- if (this.restoreAttempted.has(sessionId) && !this.restoredQueueSessions.has(sessionId)) return null;+ if (this.restoreAttempted.has(sessionId) && !this.restoredQueueSessions.has(sessionId))+ return null;const first = state.pendingCompacts[0];if (!first) return null;if (first.waitForClientIds.length > 0) return null;@@ -2621,7 +2947,8 @@ export class AgentInputCoordinator {const drainWakeupGeneration = state.drainWakeupGeneration;queueMicrotask(() => {const latest = this.getState(sessionId);- if (latest !== scheduledState || latest.drainWakeupGeneration !== drainWakeupGeneration) return;+ if (latest !== scheduledState || latest.drainWakeupGeneration !== drainWakeupGeneration)+ return;latest.drainScheduled = false;void this.drain(sessionId, reason);});@@ -2659,13 +2986,13 @@ export class AgentInputCoordinator {messageUuid: crypto.randomUUID(),createdAt: new Date().toISOString(),generation: state.generation,+ clearBoundaryMs: state.clearBoundaryMs,persisted: false,persisting: false,sendStarted: false,dispatchLifecycle: 'preparing',pendingTerminalEvent: null,- continuationOwnerClientId:- isUiContinuationItem(head) ? head.clientId : null,+ continuationOwnerClientId: isUiContinuationItem(head) ? head.clientId : null,};state.activeTurn = active;this.emit(sessionId);@@ -2699,7 +3026,8 @@ export class AgentInputCoordinator {const rewritten = updateQueuedMessageText(head, verdict.text);Object.assign(head, rewritten);if (!rewritten.sessionRefs) delete head.sessionRefs;- if (!rewritten.trustedSessionReferenceContexts) delete head.trustedSessionReferenceContexts;+ if (!rewritten.trustedSessionReferenceContexts)+ delete head.trustedSessionReferenceContexts;if (!rewritten.sessionReferencesRequireTrustedSnapshot) {delete head.sessionReferencesRequireTrustedSnapshot;}@@ -2721,7 +3049,10 @@ export class AgentInputCoordinator {// post-dispatch acknowledgements must remain older than that marker.const preVendorDispatchAt = Math.max(0, Date.now() - 1);const referenceContexts = await this.resolveReferenceContexts(head);- head.persistedContent = attachSessionReferenceMetadata(head.persistedContent, referenceContexts);+ head.persistedContent = attachSessionReferenceMetadata(+ head.persistedContent,+ referenceContexts,+ );const result = await this.deps.sendToAgent(sessionId,buildMakerUserMessage(head, referenceContexts),@@ -2733,6 +3064,9 @@ export class AgentInputCoordinator {...(head.autoResume && typeof head.autoResumeInfo?.sessionTotal === 'number'? { turnAttemptToken: head.autoResumeInfo.sessionTotal }: {}),+ signal: this.getInputAbortSignal(sessionId, active.generation),+ expectedClearBoundaryMs: active.clearBoundaryMs,+ expectedInputGeneration: active.generation,...(head.origin?.kind === 'scheduler' ? { origin: head.origin } : {}),// 手机来源透传到 send 事务:drain 已脱离入队时的 async context。...(head.fromMobileClient ? { fromMobileClient: true } : {}),@@ -2741,6 +3075,8 @@ export class AgentInputCoordinator {content: head.persistedContent,sdkSessionId,delivery: active.delivery,+ expectedClearBoundaryMs: active.clearBoundaryMs,+ expectedInputGeneration: active.generation,// 自动续跑标记必须一路透到落库:renderer 靠 agentMeta.autoResume 隐藏气泡,// host 靠它跳过额度充值(见 AgentInputQueuedMessage.autoResume)。...(head.autoResume ? { autoResume: true } : {}),@@ -2748,11 +3084,17 @@ export class AgentInputCoordinator {...(head.origin ? { origin: head.origin } : {}),shouldBroadcast: () => this.isTurnGenerationCurrent(sessionId, active),onPersisting: () => {+ this.notifyUserMessagePersisting(sessionId, head);if (this.isTurnGenerationCurrent(sessionId, active)) {active.persisting = true;}},onPersisted: async () => {+ // The DB row already owns any staged attachment references. This+ // callback intentionally runs before generation checks: a clear+ // or Stop may win the pre-vendor race after persistence, but it+ // must not delete media that the durable row now references.+ this.notifyUserMessagePersisted(sessionId, head);if (this.isTurnGenerationCurrent(sessionId, active)) {active.persisted = true;active.persisting = false;@@ -2764,17 +3106,26 @@ export class AgentInputCoordinator {}await this.deps.beforeDispatchUserTurn?.(sessionId, head);if (!this.isActiveTurnCurrent(sessionId, active)) {- throw new Error('[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch');+ throw new Error(+ '[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch',+ );}// host 把排队 orca 消息的 accepted 副作用挂在这个 hook 上(置 running /// autoBridgePending), 必须 await 完才能放行 vendor turn —— fire-and-forget// 会让快 worker 在状态可见前结束 turn, 桥接被 turn-end handler 误跳过。await this.deps.onAcceptedQueuedMessage?.(sessionId, head);if (!this.isActiveTurnCurrent(sessionId, active)) {- throw new Error('[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch');+ throw new Error(+ '[SEND_CANCELLED_BEFORE_DISPATCH] User turn was cancelled before vendor dispatch',+ );}active.dispatchLifecycle = 'sending';},+ onPersistFailed: () => {+ this.notifyUserMessagePersistenceFailed(sessionId, head, {+ retainForRetry: true,+ });+ },},},);@@ -2838,7 +3189,13 @@ export class AgentInputCoordinator {const latest = this.getState(sessionId);if (!active.persisted) {if (isSessionRunningError(err)) {- this.deferQueueHeadAfterSessionRunning(sessionId, active, head, reason, errorMessage(err));+ this.deferQueueHeadAfterSessionRunning(+ sessionId,+ active,+ head,+ reason,+ errorMessage(err),+ );return;}if (head.autoResume) {@@ -2868,8 +3225,7 @@ export class AgentInputCoordinator {latest.stickyError = null;// 同 handleSendNotDispatched:调度来源的 prompt 不留可被人手动 Retry 的 recovery// (review #944 第九轮 P1;判据内建在 setActiveTurnRecovery)。- const schedulerOrigin =- this.setActiveTurnRecovery(latest, head) === 'dropped-scheduler';+ const schedulerOrigin = this.setActiveTurnRecovery(latest, head) === 'dropped-scheduler';if (schedulerOrigin) {// 摘掉 recovery 就**必须**一并放掉 activeTurn。isDispatchBoundaryBusy 只要// activeTurn 非空就判忙,而这条 active-turn recovery 原本是唯一能清掉它的入口@@ -2965,7 +3321,11 @@ export class AgentInputCoordinator {item,cancelledByUserBoundary ? 'cancelled' : 'failed',);- if (latest.queueAbortPending && result.kind === 'session-dispatch' && result.reason === 'cancelled-before-dispatch') {+ if (+ latest.queueAbortPending &&+ result.kind === 'session-dispatch' &&+ result.reason === 'cancelled-before-dispatch'+ ) {latest.queueAbortPending = false;}log.warn(@@ -3031,7 +3391,9 @@ export class AgentInputCoordinator {const latest = this.getState(sessionId);if (!this.isActiveTurnCurrent(sessionId, active)) return;latest.activeTurn = null;- if (this.abandonAutoResumeAfterTransientFailure(sessionId, latest, item, 'credential-switch-busy')) {+ if (+ this.abandonAutoResumeAfterTransientFailure(sessionId, latest, item, 'credential-switch-busy')+ ) {return;}this.prependQueueHeadIfMissing(latest, item);@@ -3061,7 +3423,10 @@ export class AgentInputCoordinator {if (sessionId === settledSessionId) continue;const wait = state.credentialSwitchWait;if (!wait) continue;- if (wait.blockedBySessionIds.length > 0 && !wait.blockedBySessionIds.includes(settledSessionId)) {+ if (+ wait.blockedBySessionIds.length > 0 &&+ !wait.blockedBySessionIds.includes(settledSessionId)+ ) {continue;}this.scheduleDrain(sessionId, 'credential-switch-blocker-settled');@@ -3232,7 +3597,11 @@ export class AgentInputCoordinator {this.scheduleSessionRunningRetry(sessionId, reason);}- private scheduleExternalTurnRetryIfNeeded(sessionId: string, state: SessionInputState, reason: string): void {+ private scheduleExternalTurnRetryIfNeeded(+ sessionId: string,+ state: SessionInputState,+ reason: string,+ ): void {const compact = state.pendingCompacts[0];const head = state.pendingQueue[0];const hasRunnableCompact = Boolean(compact && compact.waitForClientIds.length === 0);@@ -3266,7 +3635,10 @@ export class AgentInputCoordinator {}/** closed 事件可能早于 sendToAgent 返回;这里先挂起 terminal event,等真实 send outcome 决定 drain 还是 recovery。 */- private recordActiveTurnClosedBeforeSendOutcome(state: SessionInputState, active: ActiveTurn): void {+ private recordActiveTurnClosedBeforeSendOutcome(+ state: SessionInputState,+ active: ActiveTurn,+ ): void {recordPendingTerminalEvent(active, { type: 'done' });state.error = null;state.stickyError = null;@@ -3336,9 +3708,14 @@ export class AgentInputCoordinator {// Stop 可能赢在 getSdkSessionId 或 beforeDispatchUserTurn 等 pre-vendor// await 窗口;此时 maker-core reservation 还没创建,只能由 coordinator// 自己失效这一轮 drain。- private cancelPreSendActiveTurn(sessionId: string, state: SessionInputState, preserveQueue: boolean): void {+ private cancelPreSendActiveTurn(+ sessionId: string,+ state: SessionInputState,+ preserveQueue: boolean,+ ): void {const active = state.activeTurn;if (!active || !isActiveTurnBeforeVendorDispatch(active)) return;+ this.abortInputBoundary(sessionId);state.generation += 1;state.activeTurn = null;const item = active.item;@@ -3379,11 +3756,7 @@ export class AgentInputCoordinator {* 自动续跑项在 pre-vendor 边界被丢弃时恢复原错误入口。* 返回 false 表示它已经被用户动作取代、会话已清空,或已跨过 dispatch 边界。*/- restoreAutoResumeRecovery(- sessionId: string,- clientId: string,- attemptToken: number,- ): boolean {+ restoreAutoResumeRecovery(sessionId: string, clientId: string, attemptToken: number): boolean {const pending = this.pendingAutoResumeRecoveries.get(clientId);if (!pending) return false;const state = this.states.get(sessionId);@@ -3404,10 +3777,7 @@ export class AgentInputCoordinator {return true;}- private discardAutoResumeBeforeDispatch(- sessionId: string,- item: AgentInputQueuedMessage,- ): void {+ private discardAutoResumeBeforeDispatch(sessionId: string, item: AgentInputQueuedMessage): void {// This item has already left pendingQueue but never crossed vendor dispatch. Reuse the// existing host cleanup boundary; register owns the single recovery/finalize operation.this.autoResumeDispatchAttempts.delete(item.clientId);@@ -3415,10 +3785,7 @@ export class AgentInputCoordinator {}/** 自动续跑项已真正进入 vendor,之后不再需要 pre-vendor 回滚信息。 */- private commitAutoResumeDispatch(- sessionId: string,- item: AgentInputQueuedMessage,- ): void {+ private commitAutoResumeDispatch(sessionId: string, item: AgentInputQueuedMessage): void {this.pendingAutoResumeRecoveries.delete(item.clientId);this.autoResumeDispatchAttempts.delete(item.clientId);const attemptToken = item.autoResumeInfo?.sessionTotal;@@ -3475,10 +3842,7 @@ export class AgentInputCoordinator {* 持久化前走 discard 回调,持久化后走 undispatched 回调,两条既有 host 边界都会结算* suppressed error 与 guard pending 状态。*/- private cancelPreparedAutoResume(- sessionId: string,- state: SessionInputState,- ): boolean {+ private cancelPreparedAutoResume(sessionId: string, state: SessionInputState): boolean {const queuedClientIds = state.pendingQueue.filter((item) => item.autoResume).map((item) => item.clientId);@@ -3487,11 +3851,7 @@ export class AgentInputCoordinator {const active = state.activeTurn;const item = active?.item;- if (- !active ||- !item?.autoResume ||- !isActiveTurnBeforeVendorDispatch(active)- ) {+ if (!active || !item?.autoResume || !isActiveTurnBeforeVendorDispatch(active)) {return queuedClientIds.length > 0;}const persisted = active.persisted;@@ -3508,7 +3868,11 @@ export class AgentInputCoordinator {return true;}- private fallbackPreparedAsTurn(sessionId: string, item: AgentInputQueuedMessage, removeFromQueue: boolean): void {+ private fallbackPreparedAsTurn(+ sessionId: string,+ item: AgentInputQueuedMessage,+ removeFromQueue: boolean,+ ): void {const state = this.getState(sessionId);// 插话回落成普通派发 = 也是一条新用户输入。普通 composer / 队列项可能在// scheduler 自动续跑退避期间走到这里,必须先同步作废那一轮的 waiter,避免@@ -3522,7 +3886,9 @@ export class AgentInputCoordinator {this.abandonActiveTurnRecoveryForUserAction(state);this.clearErrorUnlessQueueHeadBlocked(state, item.clientId);state.queuePaused = false;- state.steeringQueueClientIds = state.steeringQueueClientIds.filter((id) => id !== item.clientId);+ state.steeringQueueClientIds = state.steeringQueueClientIds.filter(+ (id) => id !== item.clientId,+ );state.queueEditLocks = state.queueEditLocks.filter((id) => id !== item.clientId);this.movePreparedItemToQueueFront(state, item, removeFromQueue);this.emit(sessionId);@@ -3702,7 +4068,11 @@ export class AgentInputCoordinator {state.abortReconcileRetryTimer = null;}- private registerSteerAbortController(sessionId: string, clientId: string, controller: AbortController): void {+ private registerSteerAbortController(+ sessionId: string,+ clientId: string,+ controller: AbortController,+ ): void {let byClientId = this.steerAbortControllers.get(sessionId);if (!byClientId) {byClientId = new Map<string, AbortController>();@@ -3734,7 +4104,10 @@ export class AgentInputCoordinator {});}- private clearErrorUnlessQueueHeadBlocked(state: SessionInputState, explicitClientId?: string): void {+ private clearErrorUnlessQueueHeadBlocked(+ state: SessionInputState,+ explicitClientId?: string,+ ): void {if (state.recovery?.kind === 'queue-head' && state.recovery.clientId !== explicitClientId) {return;}@@ -3843,11 +4216,9 @@ export class AgentInputCoordinator {): AutoResumeInfo | null {if (!this.deps.onResumableTurnError) return null;try {- return this.deps.onResumableTurnError(- sessionId,- { ...(signals ?? {}), message },- item,- ) ?? null;+ return (+ this.deps.onResumableTurnError(sessionId, { ...(signals ?? {}), message }, item) ?? null+ );} catch (err) {log.warn('onResumableTurnError failed', { sessionId, error: errorMessage(err) });return null;@@ -3976,16 +4347,9 @@ export class AgentInputCoordinator {}}- abandonAutoResume(- sessionId: string,- message?: string,- attemptToken?: number,- ): void {+ abandonAutoResume(sessionId: string, message?: string, attemptToken?: number): void {const state = this.getState(sessionId);- if (- attemptToken !== undefined &&- state.autoResumeAttemptToken !== attemptToken- ) {+ if (attemptToken !== undefined && state.autoResumeAttemptToken !== attemptToken) {return;}const hadPendingTakeover = state.autoResumePending !== null;@@ -4015,6 +4379,46 @@ export class AgentInputCoordinator {}}+ private notifyUserMessagePersisted(sessionId: string, item: AgentInputQueuedMessage): void {+ try {+ this.deps.onUserMessagePersisted?.(sessionId, item);+ } catch (err) {+ log.warn('onUserMessagePersisted failed', {+ sessionId,+ clientId: item.clientId,+ error: errorMessage(err),+ });+ }+ }++ private notifyUserMessagePersisting(sessionId: string, item: AgentInputQueuedMessage): void {+ try {+ this.deps.onUserMessagePersisting?.(sessionId, item);+ } catch (err) {+ log.warn('onUserMessagePersisting failed', {+ sessionId,+ clientId: item.clientId,+ error: errorMessage(err),+ });+ }+ }++ private notifyUserMessagePersistenceFailed(+ sessionId: string,+ item: AgentInputQueuedMessage,+ opts: { retainForRetry: boolean },+ ): void {+ try {+ this.deps.onUserMessagePersistenceFailed?.(sessionId, item, opts);+ } catch (err) {+ log.warn('onUserMessagePersistenceFailed failed', {+ sessionId,+ clientId: item.clientId,+ error: errorMessage(err),+ });+ }+ }+private notifyRejectedUserTurn(sessionId: string, item: AgentInputQueuedMessage): void {try {this.deps.onRejectedUserTurn?.(sessionId, item);@@ -4036,27 +4440,59 @@ export class AgentInputCoordinator {return state.generation === active.generation && state.activeTurn === active;}- private async persistAcceptedUserMessage(sessionId: string, active: ActiveTurn): Promise<PersistAcceptedUserMessageResult> {+ private async persistAcceptedUserMessage(+ sessionId: string,+ active: ActiveTurn,+ ): Promise<PersistAcceptedUserMessageResult> {const item = active.item;if (!item) return 'failed';if (!this.isTurnGenerationCurrent(sessionId, active)) return 'stale';const sdkSessionId = await this.deps.getSdkSessionId(sessionId).catch(() => undefined);const transcriptParentUuid = this.deps.getLastAssistantTranscriptUuid?.(sessionId);if (!this.isTurnGenerationCurrent(sessionId, active)) return 'stale';+ this.notifyUserMessagePersisting(sessionId, item);try {- await createDbMessage(sessionId, {- clientId: item.clientId,- role: 'user',- content: item.persistedContent,- agentMeta: {- uuid: active.messageUuid,- sdkSessionId,- delivery: active.delivery,- ...(transcriptParentUuid ? { transcriptParentUuid } : {}),- } as never,- }, {- shouldBroadcast: () => this.isTurnGenerationCurrent(sessionId, active),- });+ const createUserMessage = this.deps.createUserMessage ?? createDbMessage;+ await createUserMessage(+ sessionId,+ {+ clientId: item.clientId,+ role: 'user',+ content: item.persistedContent,+ agentMeta: {+ uuid: active.messageUuid,+ sdkSessionId,+ delivery: active.delivery,+ ...(transcriptParentUuid ? { transcriptParentUuid } : {}),+ } as never,+ },+ {+ shouldBroadcast: () => this.isTurnGenerationCurrent(sessionId, active),+ expectedClearBoundaryMs: active.clearBoundaryMs,+ },+ );+ // Persistence is the ownership boundary for staged media. Do this+ // before the generation check so a clear racing the DB write cannot+ // clean up a file that the row now references.+ this.notifyUserMessagePersisted(sessionId, item);+ const current = this.getState(sessionId);+ if (+ current.clearBoundaryMs !== active.clearBoundaryMs ||+ current.generation !== active.generation+ ) {+ try {+ await this.deps.rewindPersistedUserMessageAfterClear?.(sessionId, item.clientId);+ } catch (err) {+ // The clear generation still prevents stale in-memory state from+ // proceeding. Keep the cleanup best-effort so a transient rewind+ // failure cannot turn an accepted vendor input into a duplicate retry.+ log.warn('rewind stale user row after clear failed', {+ sessionId,+ clientId: item.clientId,+ error: errorMessage(err),+ });+ }+ }if (!this.isTurnGenerationCurrent(sessionId, active)) return 'stale';active.persisted = true;active.persisting = false;@@ -4064,6 +4500,9 @@ export class AgentInputCoordinator {this.maybePersistQueueSnapshot(sessionId);this.settlePendingTerminalEventAfterPersist(sessionId, active);} catch (err) {+ this.notifyUserMessagePersistenceFailed(sessionId, item, {+ retainForRetry: false,+ });if (!this.isTurnGenerationCurrent(sessionId, active)) return 'stale';const state = this.getState(sessionId);state.error = `Failed to persist user message: ${errorMessage(err)}`;@@ -4071,7 +4510,9 @@ export class AgentInputCoordinator {state.recovery = null;active.persisting = false;const terminalEvent = active.pendingTerminalEvent;- const releasedTerminalBoundary = Boolean(terminalEvent && this.isActiveTurnCurrent(sessionId, active));+ const releasedTerminalBoundary = Boolean(+ terminalEvent && this.isActiveTurnCurrent(sessionId, active),+ );if (releasedTerminalBoundary) {// 这条 error 永远走不到接管决策了(steer 消息落库失败,recovery 也已清)。它的 error 行// 在 host 侧被「可能接管」压住了,必须补落,否则那次中断在历史里彻底消失(I2)。@@ -4081,7 +4522,8 @@ export class AgentInputCoordinator {state.activeTurn = null;}this.emit(sessionId);- if (releasedTerminalBoundary) this.scheduleDrain(sessionId, 'failed-persist-after-deferred-terminal');+ if (releasedTerminalBoundary)+ this.scheduleDrain(sessionId, 'failed-persist-after-deferred-terminal');log.error('persist accepted user message failed', {sessionId,clientId: item.clientId,@@ -4163,10 +4605,7 @@ export class AgentInputCoordinator {state.recovery = null;this.markPendingExternalTerminalDone(sessionId, state);this.emit(sessionId);- this.scheduleDrainAfterExternalTurnSettles(- sessionId,- 'scheduler-prompt-terminal-error',- );+ this.scheduleDrainAfterExternalTurnSettles(sessionId, 'scheduler-prompt-terminal-error');return;}}diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex 9050e07a74..ca6ee1aefb 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -28,8 +28,7 @@ import type { MakerSessionCreateOpts } from './sessionRequest.js';type CreateOpts = MakerSessionCreateOpts;type IpcUserMessage =- | string- | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> };+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> };type MakerSendOptions = {messageUuid?: string;@@ -66,6 +65,11 @@ type MakerSendOptions = {shouldBroadcast?: unknown;onPersisting?: unknown;onPersisted?: unknown;+ onPersistFailed?: unknown;+ /** Main-owned clear token captured before the accepted persistence await. */+ expectedClearBoundaryMs?: unknown;+ /** Main-owned input generation captured before async preparation. */+ expectedInputGeneration?: unknown;/*** 自动续跑标记(coordinator drain 透传,见 AgentInputQueuedMessage.autoResume)。* 合进落库 user 消息的 agentMeta.autoResume:renderer 据此隐藏气泡并渲染@@ -77,6 +81,10 @@ type MakerSendOptions = {/** 队列自动来源(只写入 agentMeta,不传给 maker-core 的 turn origin)。 */origin?: unknown;};+ /** Main-owned clear token used by the final vendor fence. */+ expectedClearBoundaryMs?: unknown;+ /** Main-owned input generation used by the final vendor fence. */+ expectedInputGeneration?: unknown;};export interface MakerSendTransactionSession {@@ -126,12 +134,12 @@ export interface MakerSendTransactionDeps {didInjectOrcaInstructions: boolean;didInjectProjectContext: boolean;}>;- markOrcaRoleIfNeeded(sessionId: string, role: 'lead' | 'worker' | null | undefined): Promise<void>;- broadcastSessionCreated(sessionId: string): void;- prepareSendUserMessage(+ markOrcaRoleIfNeeded(sessionId: string,- message: unknown,- ): Promise<IpcUserMessage>;+ role: 'lead' | 'worker' | null | undefined,+ ): Promise<void>;+ broadcastSessionCreated(sessionId: string): void;+ prepareSendUserMessage(sessionId: string, message: unknown): Promise<IpcUserMessage>;/*** Direct device-link sends may carry OSS attachment references that need to* become local paths before normalization. Keep this after the transaction's@@ -146,6 +154,7 @@ export interface MakerSendTransactionDeps {sendOpts: unknown;cleanupAfterAcceptance?: () => void;cleanupBeforeAcceptance?: () => void | Promise<void>;+ cleanupLocalMaterialization?: () => void | Promise<void>;}>;createDbMessage(sessionId: string,@@ -156,15 +165,24 @@ export interface MakerSendTransactionDeps {agentMeta: Record<string, unknown>;createdAt?: number;},- opts?: { shouldBroadcast?: () => boolean },+ opts?: {+ shouldBroadcast?: () => boolean;+ expectedClearBoundaryMs?: number | null;+ },): Promise<unknown>;- /** 把 Pi 原生 user entry id 补到已落库的 Cindy user 行,供会话树恢复附件。 */- linkPiUserEntry?(+ /** Hide a user row that lost a clear race after accepted persistence. */+ rewindPersistedUserMessageAfterClear?: (sessionId: string, clientId: string) => Promise<void>;+ /** Check the clear token captured at the start of this send. */+ isClearBoundaryCurrent?: (sessionId: string,- clientId: string,- piEntryId: string,- ): Promise<boolean | void>;+ expected: number | null,+ expectedGeneration?: number,+ ) => boolean;+ /** 把 Pi 原生 user entry id 补到已落库的 Cindy user 行,供会话树恢复附件。 */+ linkPiUserEntry?(sessionId: string, clientId: string, piEntryId: string): Promise<boolean | void>;beforeDispatchDirectUserTurn?: (sessionId: string) => void | Promise<void>;+ /** Synchronous final fence immediately before Session.send enters vendor code. */+ assertBeforeVendorDispatch?: (sessionId: string, sendOpts: unknown) => void;onUndispatchedDirectUserTurn?: (sessionId: string) => void;ackInterruptedTurnDispatched?: (sessionId: string, endedAt: number) => void | Promise<void>;previewUserPrompt?(@@ -236,6 +254,9 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {shouldBroadcast?: () => boolean;onPersisting?: () => void;onPersisted?: () => void | Promise<void>;+ onPersistFailed?: () => void;+ expectedClearBoundaryMs?: number | null;+ expectedInputGeneration?: number;} | null {const persist = sendOpts.persistUserMessage;if (!persist || typeof persist.clientId !== 'string') return null;@@ -250,7 +271,9 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {...(persist.origin && typeof persist.origin === 'object' && !Array.isArray(persist.origin)? { origin: persist.origin as Record<string, unknown> }: {}),- ...(persist.delivery === 'turn' || persist.delivery === 'steer' ? { delivery: persist.delivery } : {}),+ ...(persist.delivery === 'turn' || persist.delivery === 'steer'+ ? { delivery: persist.delivery }+ : {}),...(typeof persist.shouldBroadcast === 'function'? { shouldBroadcast: persist.shouldBroadcast as () => boolean }: {}),@@ -260,9 +283,34 @@ function readPersistUserMessageOption(sendOpts: MakerSendOptions): {...(typeof persist.onPersisted === 'function'? { onPersisted: persist.onPersisted as () => void | Promise<void> }: {}),+ ...(typeof persist.onPersistFailed === 'function'+ ? { onPersistFailed: persist.onPersistFailed as () => void }+ : {}),+ ...(persist.expectedClearBoundaryMs === null ||+ (typeof persist.expectedClearBoundaryMs === 'number' &&+ Number.isFinite(persist.expectedClearBoundaryMs) &&+ persist.expectedClearBoundaryMs >= 0)+ ? { expectedClearBoundaryMs: persist.expectedClearBoundaryMs as number | null }+ : {}),+ ...(typeof persist.expectedInputGeneration === 'number' &&+ Number.isSafeInteger(persist.expectedInputGeneration) &&+ persist.expectedInputGeneration >= 0+ ? { expectedInputGeneration: persist.expectedInputGeneration }+ : {}),};}+function normalizeExpectedClearBoundary(value: unknown): number | null | undefined {+ if (value === null) return null;+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value;+ return undefined;+}++function normalizeExpectedInputGeneration(value: unknown): number | undefined {+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) return undefined;+ return value;+}+function containsManagedAttachment(value: unknown): boolean {if (typeof value === 'string') {const trimmed = value.trim();@@ -277,14 +325,18 @@ function containsManagedAttachment(value: unknown): boolean {return value.some((item) => {if (typeof item !== 'object' || item === null) return false;const block = item as Record<string, unknown>;- return block.type === 'image' || block.type === 'file' || containsManagedAttachment(block.content);+ return (+ block.type === 'image' || block.type === 'file' || containsManagedAttachment(block.content)+ );});}if (typeof value !== 'object' || value === null) return false;const record = value as Record<string, unknown>;- return (Array.isArray(record.images) && record.images.length > 0)- || (Array.isArray(record.files) && record.files.length > 0)- || containsManagedAttachment(record.content);+ return (+ (Array.isArray(record.images) && record.images.length > 0) ||+ (Array.isArray(record.files) && record.files.length > 0) ||+ containsManagedAttachment(record.content)+ );}/**@@ -300,7 +352,11 @@ function containsManagedAttachment(value: unknown): boolean {* return”的路径,除非同步更新 queue / bubble / DB / dispatch 状态协议。*/export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakerSendTransaction {- async function loadExtraDirsIfNeeded(sessionId: string, opts: CreateOpts, source: 'lazy-create' | 'active-orca-rehydrate'): Promise<void> {+ async function loadExtraDirsIfNeeded(+ sessionId: string,+ opts: CreateOpts,+ source: 'lazy-create' | 'active-orca-rehydrate',+ ): Promise<void> {if (opts.extraDirs !== undefined) return;try {const row = await deps.readSessionExtraDirsFromDb(sessionId);@@ -367,7 +423,10 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makereturn {kind: 'failure',result: toCompatibleMakerSendResult(- createHostSendFailure('WORKDIR_MISSING', `working directory is missing for session ${sessionId}`),+ createHostSendFailure(+ 'WORKDIR_MISSING',+ `working directory is missing for session ${sessionId}`,+ ),),};}@@ -376,7 +435,11 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makeconst session = await deps.withRehydrateCloseSuppressed(sessionId, async () => {await deps.closeSession(sessionId);// close 后重新 bootstrap,避免旧 SDK handle 缺 Orca MCP vendorOptions。- const { session: newSess, didInjectOrcaInstructions, didInjectProjectContext } = await deps.bootstrapSession(createOpts);+ const {+ session: newSess,+ didInjectOrcaInstructions,+ didInjectProjectContext,+ } = await deps.bootstrapSession(createOpts);await deps.markOrcaRoleIfNeeded(newSess.id, createOpts.orcaRole);deps.log.info('send: rehydrate active Orca session with MCP vendorOptions', {sessionId,@@ -418,7 +481,10 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makereturn {kind: 'failure',result: toCompatibleMakerSendResult(- createHostSendFailure('REHYDRATE_FAILED', err instanceof Error ? err.message : 'rehydrate failed'),+ createHostSendFailure(+ 'REHYDRATE_FAILED',+ err instanceof Error ? err.message : 'rehydrate failed',+ ),),};}@@ -433,14 +499,21 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makereturn {kind: 'failure',result: toCompatibleMakerSendResult(- createHostSendFailure('WORKDIR_MISSING', `working directory is missing for session ${sessionId}`),+ createHostSendFailure(+ 'WORKDIR_MISSING',+ `working directory is missing for session ${sessionId}`,+ ),),};}await deps.synthesizeOrcaVendorOptionsFromDb(sessionId, createOpts);await loadExtraDirsIfNeeded(sessionId, createOpts, 'lazy-create');try {- const { session: lazySess, didInjectOrcaInstructions, didInjectProjectContext } = await deps.bootstrapSession(createOpts);+ const {+ session: lazySess,+ didInjectOrcaInstructions,+ didInjectProjectContext,+ } = await deps.bootstrapSession(createOpts);await deps.markOrcaRoleIfNeeded(lazySess.id, createOpts.orcaRole);deps.broadcastSessionCreated(lazySess.id);deps.log.info('send: lazy create-session', {@@ -483,14 +556,22 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makereturn {kind: 'failure',result: toCompatibleMakerSendResult(- createHostSendFailure('LAZY_CREATE_FAILED', err instanceof Error ? err.message : 'lazy create failed'),+ createHostSendFailure(+ 'LAZY_CREATE_FAILED',+ err instanceof Error ? err.message : 'lazy create failed',+ ),),};}}return {- async sendToAgentAccepted(sessionId, message, createOpts, sendOpts): Promise<DesktopMakerSendResult> {+ async sendToAgentAccepted(+ sessionId,+ message,+ createOpts,+ sendOpts,+ ): Promise<DesktopMakerSendResult> {if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');// session-agent-switch:pending 切换在发送时刻生效(用户语义:「消息真正发出// 去时才切」)。必须在 getSession 之前——apply 会 close 旧引擎的 live session,@@ -511,19 +592,32 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makeawait deps.ensureRemoteReadyForSessionStart({ session: sess, createOpts });if (sess) {- const ok = await deps.checkWorkDirExists(sessionId, sess.workDir, sess.agentKind, sess.remoteHostId);+ const ok = await deps.checkWorkDirExists(+ sessionId,+ sess.workDir,+ sess.agentKind,+ sess.remoteHostId,+ );if (!ok) {return toCompatibleMakerSendResult(- createHostSendFailure('WORKDIR_MISSING', `working directory is missing for session ${sessionId}`),+ createHostSendFailure(+ 'WORKDIR_MISSING',+ `working directory is missing for session ${sessionId}`,+ ),);}if (!deps.isOrcaMcpHydrated(sessionId) && createOpts) {- const co = deps.buildCreateOptsWithStderr({ ...(createOpts as CreateOpts), id: sessionId });+ const co = deps.buildCreateOptsWithStderr({+ ...(createOpts as CreateOpts),+ id: sessionId,+ });const shouldHydrateOrcaMcp = await deps.synthesizeOrcaVendorOptionsFromDb(sessionId, co);if (shouldHydrateOrcaMcp) {if (sess.isTurnRunning()) {// 仍交给下方统一 running guard 抛 SESSION_RUNNING,避免重复分支。- deps.log.warn('send: active Orca session needs MCP rehydrate but turn is running', { sessionId });+ deps.log.warn('send: active Orca session needs MCP rehydrate but turn is running', {+ sessionId,+ });} else {const rehydrated = await rehydrateActiveOrcaSession(sessionId, co);if (rehydrated.kind === 'failure') return rehydrated.result;@@ -534,7 +628,8 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make}if (!sess) {- if (!createOpts) throwIpcError('NOT_FOUND', `Session ${sessionId} not found and no createOpts provided`);+ if (!createOpts)+ throwIpcError('NOT_FOUND', `Session ${sessionId} not found and no createOpts provided`);const co = deps.buildCreateOptsWithStderr({ ...(createOpts as CreateOpts), id: sessionId });await deps.reconcileCreateOptsWithDb?.(sessionId, co);const lazy = await lazyCreateSession(sessionId, co);@@ -556,6 +651,13 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makelet outgoingSendOpts = sendOpts;let cleanupAfterAcceptance: (() => void) | undefined;let cleanupBeforeAcceptance: (() => void | Promise<void>) | undefined;+ let cleanupLocalMaterialization: (() => void | Promise<void>) | undefined;+ // `Session.send()` may invoke onAccepted (and therefore persist the+ // durable user row) before a later abort/stop makes it return+ // `accepted:false`. Keep local materialisation alive once that row+ // exists; otherwise the pre-accept cleanup would delete the only media+ // reference still used by the transcript.+ let userMessagePersisted = false;let sendAccepted = false;if (deps.materializeDirectSendOssAttachments) {const materialized = await deps.materializeDirectSendOssAttachments(@@ -564,11 +666,30 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): MakeoutgoingSendOpts,);outgoingMessage = materialized.message;- outgoingSendOpts = materialized.sendOpts;+ // A materializer that has no sendOpts rewrite may omit the field. Keep+ // the caller's persistence/dispatch options in that case; dropping+ // them would silently turn a durable user send into a non-persisted+ // direct vendor call.+ if (materialized.sendOpts !== undefined) outgoingSendOpts = materialized.sendOpts;cleanupAfterAcceptance = materialized.cleanupAfterAcceptance;cleanupBeforeAcceptance = materialized.cleanupBeforeAcceptance;+ cleanupLocalMaterialization = materialized.cleanupLocalMaterialization;}- const cleanupBeforeAcceptanceIfNeeded = async (): Promise<void> => {+ const cleanupRejectedMaterialization = async (): Promise<void> => {+ if (userMessagePersisted) {+ // The local file is now owned by the durable transcript row. The+ // remote OSS object is still ephemeral and can be released even if+ // the vendor later rejects or throws after onAccepted.+ try {+ cleanupAfterAcceptance?.();+ } catch (err) {+ deps.log.warn('send: direct OSS post-persist cleanup failed', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ return;+ }if (!cleanupBeforeAcceptance) return;try {await cleanupBeforeAcceptance();@@ -579,11 +700,26 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make});}};+ const cleanupAcceptedNonPersistedMaterialization = async (): Promise<void> => {+ // Without a durable transcript row, no later lifecycle callback owns the+ // local media refs. Accepted direct sends must release them here; a+ // persisted send intentionally keeps them for transcript replay.+ if (userMessagePersisted || !cleanupLocalMaterialization) return;+ try {+ await cleanupLocalMaterialization();+ } catch (err) {+ // Vendor dispatch is already irreversible; cleanup remains best effort.+ deps.log.warn('send: accepted direct OSS local cleanup failed', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ };let normalized: IpcUserMessage;try {normalized = await deps.prepareSendUserMessage(sessionId, outgoingMessage);} catch (err) {- await cleanupBeforeAcceptanceIfNeeded();+ await cleanupRejectedMaterialization();throw err;}// session-agent-switch:切换后的首条消息把交接前缀拼进 wire payload。@@ -599,14 +735,91 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make// 元信息在前、交接正文在后、由交接自带的标记统一收尾)。// 两个来源:直连 maker:send 走 async context(deps 注入);排队 / 插入路径走// coordinator 从队列项透传的 so.fromMobileClient(drain 时 context 已结束)。- const mobileClientNote = deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true- ? buildMobileClientPromptNote()- : null;+ const mobileClientNote =+ deps.isMobileClientInvoke?.() === true || so.fromMobileClient === true+ ? buildMobileClientPromptNote()+ : null;const outgoing = mobileClientNote? prependNoteToWireUserMessage(withHandoff as HandoffWireMessage, mobileClientNote): withHandoff;const meta = await deps.getSessionMeta(sessionId).catch(() => null);- const persistUserMessage = readPersistUserMessageOption(so);+ let persistUserMessage = readPersistUserMessageOption(so);+ const topLevelClearBoundary = normalizeExpectedClearBoundary(so.expectedClearBoundaryMs);+ const topLevelInputGeneration = normalizeExpectedInputGeneration(so.expectedInputGeneration);+ if (+ persistUserMessage &&+ ((persistUserMessage.expectedClearBoundaryMs === undefined &&+ topLevelClearBoundary !== undefined) ||+ (persistUserMessage.expectedInputGeneration === undefined &&+ topLevelInputGeneration !== undefined))+ ) {+ persistUserMessage = {+ ...persistUserMessage,+ ...(persistUserMessage.expectedClearBoundaryMs === undefined &&+ topLevelClearBoundary !== undefined+ ? { expectedClearBoundaryMs: topLevelClearBoundary }+ : {}),+ ...(persistUserMessage.expectedInputGeneration === undefined &&+ topLevelInputGeneration !== undefined+ ? { expectedInputGeneration: topLevelInputGeneration }+ : {}),+ };+ }+ const finalFenceOverrides: Record<string, unknown> = {};+ if (+ topLevelClearBoundary === undefined &&+ persistUserMessage?.expectedClearBoundaryMs !== undefined+ ) {+ finalFenceOverrides.expectedClearBoundaryMs = persistUserMessage.expectedClearBoundaryMs;+ }+ if (+ topLevelInputGeneration === undefined &&+ persistUserMessage?.expectedInputGeneration !== undefined+ ) {+ finalFenceOverrides.expectedInputGeneration = persistUserMessage.expectedInputGeneration;+ }+ const finalFenceSendOpts =+ Object.keys(finalFenceOverrides).length > 0 &&+ outgoingSendOpts &&+ typeof outgoingSendOpts === 'object'+ ? { ...(outgoingSendOpts as Record<string, unknown>), ...finalFenceOverrides }+ : Object.keys(finalFenceOverrides).length > 0+ ? finalFenceOverrides+ : outgoingSendOpts;+ let staleUserMessageRewound = false;+ const rewindPersistedUserMessageAfterClearIfStale = async (): Promise<void> => {+ const persistedUserMessage = persistUserMessage;+ const expectedClearBoundaryMs = persistedUserMessage?.expectedClearBoundaryMs;+ if (+ !persistedUserMessage ||+ !userMessagePersisted ||+ staleUserMessageRewound ||+ expectedClearBoundaryMs === undefined ||+ !deps.isClearBoundaryCurrent ||+ deps.isClearBoundaryCurrent(+ sessionId,+ expectedClearBoundaryMs,+ persistedUserMessage.expectedInputGeneration,+ )+ ) {+ return;+ }+ staleUserMessageRewound = true;+ try {+ await deps.rewindPersistedUserMessageAfterClear?.(+ sessionId,+ persistedUserMessage.clientId,+ );+ } catch (err) {+ // The send is already stale; cleanup remains best-effort and must not+ // turn a clear race into a duplicate retry prompt.+ deps.log.warn('send: stale user row rewind after clear failed', {+ sessionId,+ clientId: persistedUserMessage.clientId,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ };const directPreDispatchHook = persistUserMessage ? null : deps.beforeDispatchDirectUserTurn;let directPreDispatchHookStarted = false;let userPromptPreviewSessionId: string | null = null;@@ -638,10 +851,10 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make...(typeof (createOpts as { planMode?: unknown } | undefined)?.planMode === 'boolean'? { planMode: (createOpts as { planMode: boolean }).planMode }: {}),- ...(sess.agentKind === 'pi'- && persistUserMessage- && containsManagedAttachment(persistUserMessage.content)- && deps.linkPiUserEntry+ ...(sess.agentKind === 'pi' &&+ persistUserMessage &&+ containsManagedAttachment(persistUserMessage.content) &&+ deps.linkPiUserEntry? {onTranscriptUserEntry: async (piEntryId: string) => {try {@@ -679,36 +892,64 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make});userPromptPreviewSessionId = sessionId;userPromptPreviewClientId = persistUserMessage.clientId;- await deps.createDbMessage(sessionId, {- clientId: persistUserMessage.clientId,- role: 'user',- content: persistUserMessage.content,- agentMeta: {- uuid: so.messageUuid,- sdkSessionId: persistUserMessage.sdkSessionId,- ...(persistUserMessage.delivery ? { delivery: persistUserMessage.delivery } : {}),- // 自动补发的续跑指令:renderer 隐藏气泡 + 渲染「已重新连接」活动行,- // 同时也是 host 跳过额度充值的判据(见 register 的 createDbMessage)。- ...(persistUserMessage.autoResume ? { autoResume: true } : {}),- ...(persistUserMessage.autoResumeInfo- ? { autoResumeInfo: persistUserMessage.autoResumeInfo }- : {}),- ...(persistUserMessage.origin- ? { origin: persistUserMessage.origin }- : {}),- // scheduler 排队消息:与 runner 直发路径落库的 agentMeta.origin- // 对齐,renderer 据此渲染"由自动化任务发送"标签。- ...(so.origin ? { origin: so.origin } : {}),- },- }, persistUserMessage.shouldBroadcast- ? { shouldBroadcast: persistUserMessage.shouldBroadcast }- : undefined);+ try {+ await deps.createDbMessage(+ sessionId,+ {+ clientId: persistUserMessage.clientId,+ role: 'user',+ content: persistUserMessage.content,+ agentMeta: {+ uuid: so.messageUuid,+ sdkSessionId: persistUserMessage.sdkSessionId,+ ...(persistUserMessage.delivery+ ? { delivery: persistUserMessage.delivery }+ : {}),+ // 自动补发的续跑指令:renderer 隐藏气泡 + 渲染「已重新连接」活动行,+ // 同时也是 host 跳过额度充值的判据(见 register 的 createDbMessage)。+ ...(persistUserMessage.autoResume ? { autoResume: true } : {}),+ ...(persistUserMessage.autoResumeInfo+ ? { autoResumeInfo: persistUserMessage.autoResumeInfo }+ : {}),+ ...(persistUserMessage.origin ? { origin: persistUserMessage.origin } : {}),+ // scheduler 排队消息:与 runner 直发路径落库的 agentMeta.origin+ // 对齐,renderer 据此渲染"由自动化任务发送"标签。+ ...(so.origin ? { origin: so.origin } : {}),+ },+ },+ persistUserMessage.shouldBroadcast ||+ persistUserMessage.expectedClearBoundaryMs !== undefined+ ? {+ ...(persistUserMessage.shouldBroadcast+ ? { shouldBroadcast: persistUserMessage.shouldBroadcast }+ : {}),+ ...(persistUserMessage.expectedClearBoundaryMs !== undefined+ ? {+ expectedClearBoundaryMs: persistUserMessage.expectedClearBoundaryMs,+ }+ : {}),+ }+ : undefined,+ );+ } catch (err) {+ persistUserMessage.onPersistFailed?.();+ throw err;+ }+ userMessagePersisted = true;+ await rewindPersistedUserMessageAfterClearIfStale();// onPersisted 里可能挂着排队 orca 消息的 accepted 副作用(置 running /// autoBridgePending), 必须 await 完再放行 turn(同直发路径语义)。await persistUserMessage.onPersisted?.();}: undefined,onDispatching: () => {+ if (persistUserMessage?.shouldBroadcast && !persistUserMessage.shouldBroadcast()) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'REMOTE_OPTIMISTIC_INPUT_SUPERSEDED: input preparation was superseded',+ );+ }+ deps.assertBeforeVendorDispatch?.(sessionId, finalFenceSendOpts);if (userPromptPreviewSessionId) {deps.dispatchUserPromptPreview?.(userPromptPreviewSessionId,@@ -718,8 +959,13 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make},});sendAccepted = sendResult.accepted;- if (sendAccepted) cleanupAfterAcceptance?.();- else await cleanupBeforeAcceptanceIfNeeded();+ if (sendAccepted) {+ cleanupAfterAcceptance?.();+ await cleanupAcceptedNonPersistedMaterialization();+ } else {+ await rewindPersistedUserMessageAfterClearIfStale();+ await cleanupRejectedMaterialization();+ }if (sendResult.accepted && interruptedAckAt !== null) {try {await deps.ackInterruptedTurnDispatched?.(sessionId, interruptedAckAt);@@ -757,7 +1003,10 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make}),);} catch (err) {- if (!sendAccepted) await cleanupBeforeAcceptanceIfNeeded();+ if (!sendAccepted) {+ await rewindPersistedUserMessageAfterClearIfStale();+ await cleanupRejectedMaterialization();+ }if (userPromptPreviewSessionId && userPromptPreviewClientId) {deps.rollbackUserPromptPreview?.(userPromptPreviewSessionId,diff --git a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.tsindex 53596c18cc..8f1c7e62e2 100644--- a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts+++ b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts@@ -60,6 +60,47 @@ export function stampMobileClientOrigin<T extends { fromMobileClient?: boolean }return rest as T;}+/**+ * Main-owned input boundary captured at an IPC entry point. The generation is+ * intentionally carried alongside the wall-clock clear token: two clears can+ * share the same millisecond timestamp, while the generation still proves that+ * a request started before the later clear.+ */+export interface MainOwnedInputBoundaryStamp {+ expectedClearBoundaryMs: number | null;+ expectedInputGeneration: number;+ /** Main-only cancellation scope; never comes from a device-link payload. */+ inputAbortSignal?: AbortSignal;+}++/**+ * Strip fields that are only valid when constructed by main. The clear token+ * itself remains a valid controller precondition: the IPC boundary validates it+ * before `attachMainOwnedInputBoundary` replaces it with the authoritative host+ * stamp. Keeping it when no stamp is available also preserves old test harnesses+ * and non-device-link callers.+ */+export function attachMainOwnedInputBoundary(+ sendOpts: unknown,+ stamp: MainOwnedInputBoundaryStamp | undefined,+): unknown {+ const sanitized = stripMainOnlySendOpts(sendOpts);+ if (!stamp) return sanitized;+ if (!sanitized || typeof sanitized !== 'object' || Array.isArray(sanitized)) {+ return {+ expectedClearBoundaryMs: stamp.expectedClearBoundaryMs,+ expectedInputGeneration: stamp.expectedInputGeneration,+ ...(stamp.inputAbortSignal ? { signal: stamp.inputAbortSignal } : {}),+ };+ }+ return {+ ...(sanitized as Record<string, unknown>),+ expectedClearBoundaryMs: stamp.expectedClearBoundaryMs,+ expectedInputGeneration: stamp.expectedInputGeneration,+ ...(stamp.inputAbortSignal ? { signal: stamp.inputAbortSignal } : {}),+ };+}+/*** 剥掉 sendOpts 里「只允许 main 写」的字段。*@@ -71,7 +112,21 @@ export function stampMobileClientOrigin<T extends { fromMobileClient?: boolean }*/export function stripMainOnlySendOpts(sendOpts: unknown): unknown {if (!sendOpts || typeof sendOpts !== 'object' || Array.isArray(sendOpts)) return sendOpts;- if (!('fromMobileClient' in sendOpts)) return sendOpts;- const { fromMobileClient: _ignored, ...rest } = sendOpts as Record<string, unknown>;+ const opts = sendOpts as Record<string, unknown>;+ if (+ !('fromMobileClient' in opts) &&+ !('expectedInputGeneration' in opts) &&+ !('inputAbortSignal' in opts) &&+ !('signal' in opts)+ ) {+ return sendOpts;+ }+ const {+ fromMobileClient: _ignoredMobile,+ expectedInputGeneration: _ignoredGeneration,+ inputAbortSignal: _ignoredAbortSignal,+ signal: _ignoredSignal,+ ...rest+ } = opts;return rest;}diff --git a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts b/apps/desktop/src/main/maker-ipc/normalizeAttachments.tsindex 46d1f808c8..16455441c4 100644--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts@@ -336,6 +336,7 @@ async function materializeQueuedOssAttachmentsInternal(item: unknown;cleanupAfterAcceptance?: () => void;cleanupBeforeAcceptance?: () => Promise<void>;+ cleanupLocalMaterialization?: () => Promise<void>;}> {if (!item || typeof item !== 'object') return { item };const it = item as { files?: unknown; persistedContent?: unknown };@@ -402,7 +403,10 @@ async function materializeQueuedOssAttachmentsInternal(if (refId) {localCleanupCallbacks.push(async () => {await cindyMediaLedger.removeRefById(refId);- const removed = await cindyMediaLedger.deleteZeroRefBlobRecord(written.hash, Date.now() + 1);+ const removed = await cindyMediaLedger.deleteZeroRefBlobRecord(+ written.hash,+ Date.now() + 1,+ );if (removed) await cindyMediaBlobStore.deleteBlobFile(written.hash, written.ext);});}@@ -523,6 +527,9 @@ async function materializeQueuedOssAttachmentsInternal(? {cleanupAfterAcceptance: cleanupOss,cleanupBeforeAcceptance,+ ...(localCleanupCallbacks.length > 0+ ? { cleanupLocalMaterialization: cleanupLocalMaterializations }+ : {}),}: {}),};@@ -541,6 +548,27 @@ export async function materializeQueuedOssAttachments(return (await materializeQueuedOssAttachmentsInternal(sessionId, item, false)).item;}+/**+ * Deferred variant for content-bearing input handlers.+ *+ * Materialisation may create cindy-media ledger refs or image-cache files before+ * the handler finishes its generation / clear-boundary checks. Callers must+ * keep the returned cleanup callbacks until the input is accepted; a rejected+ * preparation must run `cleanupBeforeAcceptance`, while an accepted input may+ * release the remote OSS object with `cleanupAfterAcceptance`.+ */+export async function materializeQueuedOssAttachmentsDeferred(+ sessionId: string,+ item: unknown,+): Promise<{+ item: unknown;+ cleanupAfterAcceptance?: () => void;+ cleanupBeforeAcceptance?: () => Promise<void>;+ cleanupLocalMaterialization?: () => Promise<void>;+}> {+ return materializeQueuedOssAttachmentsInternal(sessionId, item, true);+}+/*** Direct maker:send carries attachment references in two parallel shapes:* the user-message blocks consumed by the agent and@@ -560,6 +588,7 @@ export async function materializeDirectSendOssAttachments(sendOpts: unknown;cleanupAfterAcceptance?: () => void;cleanupBeforeAcceptance?: () => Promise<void>;+ cleanupLocalMaterialization?: () => Promise<void>;}> {if (!message || typeof message !== 'object' || Array.isArray(message)) {return { message, sendOpts };@@ -577,8 +606,7 @@ export async function materializeDirectSendOssAttachments(raw &&typeof raw === 'object' &&!Array.isArray(raw) &&- (((raw as { type?: unknown }).type === 'image') ||- (raw as { type?: unknown }).type === 'file')+ ((raw as { type?: unknown }).type === 'image' || (raw as { type?: unknown }).type === 'file')) {attachmentIndexes.push(index);const block = raw as Record<string, unknown>;@@ -620,7 +648,12 @@ export async function materializeDirectSendOssAttachments(for (let index = 0; index < attachmentIndexes.length; index += 1) {const original = msg.content[attachmentIndexes[index]];const materialized = materializedFiles[index];- if (!original || typeof original !== 'object' || !materialized || typeof materialized !== 'object') {+ if (+ !original ||+ typeof original !== 'object' ||+ !materialized ||+ typeof materialized !== 'object'+ ) {continue;}const originalPath = (original as { path?: unknown }).path;@@ -667,6 +700,9 @@ export async function materializeDirectSendOssAttachments(...(materialized.cleanupBeforeAcceptance? { cleanupBeforeAcceptance: materialized.cleanupBeforeAcceptance }: {}),+ ...(materialized.cleanupLocalMaterialization+ ? { cleanupLocalMaterialization: materialized.cleanupLocalMaterialization }+ : {}),};}diff --git a/apps/desktop/src/main/maker-ipc/queuedAttachmentOwnership.ts b/apps/desktop/src/main/maker-ipc/queuedAttachmentOwnership.tsnew file mode 100644index 0000000000..2948c76f39--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/queuedAttachmentOwnership.ts@@ -0,0 +1,317 @@+export type QueuedAttachmentCleanup = () => void | Promise<void>;++export type QueuedAttachmentOwnershipOptions = {+ /**+ * Cleanup for the controller-owned source (for example a remote OSS key).+ * It must not run until the accepted queue item has crossed a durable+ * boundary; explicit discard and a post-snapshot non-retryable persistence+ * failure may run it.+ */+ cleanupAfterDurable?: QueuedAttachmentCleanup;+};++type QueuedAttachmentOwnership = {+ cleanup: QueuedAttachmentCleanup;+ cleanupAfterDurable?: QueuedAttachmentCleanup;+ durableBoundaryReached: boolean;+ persistenceInFlight: boolean;+ discardRequested: boolean;+};++type QueuedAttachmentClientOwnership = {+ owners: Map<string, QueuedAttachmentOwnership>;+ /** The owner represented by the coordinator's currently accepted item. */+ currentOwnerId: string | null;+};++export type QueuedAttachmentCleanupError = {+ sessionId: string;+ clientId: string;+ error: unknown;+};++/**+ * Owns local files created while a queued remote attachment is being prepared.+ *+ * A clear/stop can race the SQLite insert. Cleanup is immediate while the item+ * is only queued, but becomes deferred once persistence starts: a successful+ * insert transfers ownership to the durable row, while a failed insert may+ * clean only when the item was discarded or will not be retried.+ */+export class QueuedAttachmentOwnershipRegistry {+ private readonly ownership = new Map<+ string,+ Map<string, QueuedAttachmentClientOwnership>+ >();+ private nextOwnerId = 0;++ constructor(private readonly onCleanupError?: (failure: QueuedAttachmentCleanupError) => void) {}++ register(+ sessionId: string,+ clientId: string,+ cleanup: QueuedAttachmentCleanup | undefined,+ options?: QueuedAttachmentOwnershipOptions,+ ): string | null {+ if (!cleanup && !options?.cleanupAfterDurable) return null;+ let byClient = this.ownership.get(sessionId);+ if (!byClient) {+ byClient = new Map();+ this.ownership.set(sessionId, byClient);+ }+ let clientOwnership = byClient.get(clientId);+ if (!clientOwnership) {+ clientOwnership = { owners: new Map(), currentOwnerId: null };+ byClient.set(clientId, clientOwnership);+ }+ const ownerId = `${clientId}:${++this.nextOwnerId}`;+ clientOwnership.owners.set(ownerId, {+ cleanup: cleanup ?? (() => {}),+ ...(options?.cleanupAfterDurable ? { cleanupAfterDurable: options.cleanupAfterDurable } : {}),+ durableBoundaryReached: false,+ persistenceInFlight: false,+ discardRequested: false,+ });+ return ownerId;+ }++ /**+ * Make an accepted materialisation the owner of the coordinator item.+ * Registration happens before acceptance, so a rejected preparation never+ * becomes the current owner. The previous id is returned for rollback when+ * an async steer is cancelled before acceptance.+ */+ activateCurrentOwner(sessionId: string, clientId: string, ownerId: string): string | null {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership?.owners.has(ownerId)) return null;+ const previousOwnerId = clientOwnership.currentOwnerId;+ clientOwnership.currentOwnerId = ownerId;+ return previousOwnerId;+ }++ restoreCurrentOwner(sessionId: string, clientId: string, ownerId: string | null): void {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership) return;+ clientOwnership.currentOwnerId =+ ownerId && clientOwnership.owners.has(ownerId) ? ownerId : null;+ }++ getCurrentOwnerId(sessionId: string, clientId: string): string | null {+ return this.ownership.get(sessionId)?.get(clientId)?.currentOwnerId ?? null;+ }++ markPersistenceStarted(sessionId: string, clientId: string): void {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership) return;+ const currentOwner = clientOwnership.currentOwnerId+ ? clientOwnership.owners.get(clientOwnership.currentOwnerId)+ : undefined;+ if (currentOwner) {+ currentOwner.persistenceInFlight = true;+ return;+ }+ // Keep the legacy fail-safe for an item accepted by an older caller that+ // did not stamp its owner: retaining all owners is safer than deleting a+ // local materialisation that may be referenced by the durable row.+ for (const owner of clientOwnership.owners.values()) owner.persistenceInFlight = true;+ }++ async markPersistenceFailed(+ sessionId: string,+ clientId: string,+ opts: { retainForRetry: boolean },+ ): Promise<void> {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership) return;+ const ownerIds = [...clientOwnership.owners.keys()];+ // A single-owner legacy caller can be inferred safely. If several owners+ // exist without an activation stamp, retain all of them on a retry rather+ // than guessing which local file the durable row references.+ const currentOwnerId =+ clientOwnership.currentOwnerId ?? (ownerIds.length === 1 ? ownerIds[0] : null);+ const cleanups: QueuedAttachmentCleanup[] = [];+ for (const [ownerId, owner] of clientOwnership.owners) {+ owner.persistenceInFlight = false;+ const isCurrent = ownerId === currentOwnerId;+ // The caller waits for the post-failure queue snapshot before invoking+ // this method. Every non-current replacement is therefore no longer+ // recoverable from the queue and can be cleaned even when its discard+ // callback was still waiting on that same snapshot.+ if (+ opts.retainForRetry &&+ !owner.discardRequested &&+ (isCurrent || clientOwnership.currentOwnerId === null)+ ) {+ continue;+ }+ clientOwnership.owners.delete(ownerId);+ cleanups.push(owner.cleanup);+ if (owner.cleanupAfterDurable && !owner.durableBoundaryReached) {+ cleanups.push(owner.cleanupAfterDurable);+ }+ }+ clientOwnership.currentOwnerId = null;+ this.prune(sessionId, clientId);+ await this.runCleanups(sessionId, clientId, cleanups);+ }++ /**+ * Mark one accepted materialization as crash-recoverable/durable and release+ * only its ephemeral remote source. The local materialization remains owned+ * until the durable messages row exists or the item is explicitly discarded.+ */+ async markDurable(sessionId: string, clientId: string, ownerId?: string): Promise<void> {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership) return;+ const cleanups: QueuedAttachmentCleanup[] = [];+ for (const [candidateId, owner] of clientOwnership.owners) {+ if (ownerId !== undefined && candidateId !== ownerId) continue;+ if (owner.durableBoundaryReached) continue;+ owner.durableBoundaryReached = true;+ if (owner.cleanupAfterDurable) {+ cleanups.push(owner.cleanupAfterDurable);+ owner.cleanupAfterDurable = undefined;+ }+ }+ await this.runCleanups(sessionId, clientId, cleanups);+ }++ /**+ * Settle the stronger messages-row boundary atomically. The accepted+ * owner transfers its local materialisation to the transcript row; every+ * superseded owner is fully discarded so replacement edits cannot leak+ * media. Callers must invoke this only after the row exists.+ */+ async settleDurable(+ sessionId: string,+ clientId: string,+ ownerId?: string,+ ): Promise<void> {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership) return;+ const persistedOwnerId = ownerId ?? clientOwnership.currentOwnerId;+ if (persistedOwnerId && !clientOwnership.owners.has(persistedOwnerId)) {+ // Never clean local materialisation when the caller names an owner that+ // is no longer registered; the row may still reference another owner.+ return;+ }+ const cleanups: QueuedAttachmentCleanup[] = [];+ if (!persistedOwnerId) {+ // Fail-safe for a legacy caller that did not activate an owner: transfer+ // every local copy to the durable row and release only remote sources.+ // This can leak a superseded local copy, but cannot delete the copy the+ // transcript may reference. New call sites always stamp an owner.+ for (const owner of clientOwnership.owners.values()) {+ owner.durableBoundaryReached = true;+ if (owner.cleanupAfterDurable) cleanups.push(owner.cleanupAfterDurable);+ }+ clientOwnership.owners.clear();+ clientOwnership.currentOwnerId = null;+ this.prune(sessionId, clientId);+ await this.runCleanups(sessionId, clientId, cleanups);+ return;+ }+ for (const [candidateId, owner] of clientOwnership.owners) {+ const persistedOwner = candidateId === persistedOwnerId;+ if (persistedOwner) {+ if (owner.cleanupAfterDurable && !owner.durableBoundaryReached) {+ cleanups.push(owner.cleanupAfterDurable);+ }+ } else {+ cleanups.push(owner.cleanup);+ if (owner.cleanupAfterDurable && !owner.durableBoundaryReached) {+ cleanups.push(owner.cleanupAfterDurable);+ }+ }+ clientOwnership.owners.delete(candidateId);+ }+ clientOwnership.currentOwnerId = null;+ this.prune(sessionId, clientId);+ await this.runCleanups(sessionId, clientId, cleanups);+ }++ discardClient(sessionId: string, clientId: string, keepOwnerId?: string): Promise<void> {+ return this.discardWhere(sessionId, clientId, (ownerId) => ownerId !== keepOwnerId);+ }++ discardSpecific(sessionId: string, clientId: string, ownerId: string): Promise<void> {+ return this.discardWhere(sessionId, clientId, (candidate) => candidate === ownerId);+ }++ releaseClient(sessionId: string, clientId: string): void {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership) return;+ // This legacy escape hatch is intentionally limited to owners that have+ // crossed a durable boundary. Dropping a pending/discard-requested owner+ // here would silently lose the only cleanup callback and reintroduce the+ // session-close data-loss race.+ if ([...clientOwnership.owners.values()].some((owner) => !owner.durableBoundaryReached)) {+ return;+ }+ this.ownership.get(sessionId)?.delete(clientId);+ this.prune(sessionId, clientId);+ }++ releaseSpecific(sessionId: string, clientId: string, ownerId: string): void {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership) return;+ const owner = clientOwnership.owners.get(ownerId);+ if (!owner || !owner.durableBoundaryReached) return;+ clientOwnership.owners.delete(ownerId);+ if (clientOwnership.currentOwnerId === ownerId) clientOwnership.currentOwnerId = null;+ this.prune(sessionId, clientId);+ }++ async discardSession(sessionId: string): Promise<void> {+ const clientIds = [...(this.ownership.get(sessionId)?.keys() ?? [])];+ await Promise.all(clientIds.map((clientId) => this.discardClient(sessionId, clientId)));+ }++ private async discardWhere(+ sessionId: string,+ clientId: string,+ predicate: (ownerId: string) => boolean,+ ): Promise<void> {+ const clientOwnership = this.ownership.get(sessionId)?.get(clientId);+ if (!clientOwnership) return;+ const cleanups: QueuedAttachmentCleanup[] = [];+ for (const [ownerId, owner] of clientOwnership.owners) {+ if (!predicate(ownerId)) continue;+ if (owner.persistenceInFlight) {+ owner.discardRequested = true;+ continue;+ }+ clientOwnership.owners.delete(ownerId);+ if (clientOwnership.currentOwnerId === ownerId) clientOwnership.currentOwnerId = null;+ cleanups.push(owner.cleanup);+ if (owner.cleanupAfterDurable && !owner.durableBoundaryReached) {+ cleanups.push(owner.cleanupAfterDurable);+ }+ }+ this.prune(sessionId, clientId);+ await this.runCleanups(sessionId, clientId, cleanups);+ }++ private prune(sessionId: string, clientId: string): void {+ const byClient = this.ownership.get(sessionId);+ const clientOwnership = byClient?.get(clientId);+ if (clientOwnership?.owners.size === 0) byClient?.delete(clientId);+ if (byClient?.size === 0) this.ownership.delete(sessionId);+ }++ private async runCleanups(+ sessionId: string,+ clientId: string,+ cleanups: QueuedAttachmentCleanup[],+ ): Promise<void> {+ await Promise.all(+ cleanups.map(async (cleanup) => {+ try {+ await cleanup();+ } catch (error) {+ this.onCleanupError?.({ sessionId, clientId, error });+ }+ }),+ );+ }+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 57d27bbf3e..9c59e8e65b 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -36,12 +36,14 @@ import {} from '@cindy/device-link';import { and, desc, eq, gte, inArray, isNull, sql } from 'drizzle-orm';import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';-import { getActiveAppSession } from '../appSessionState.js';+import { getActiveAppSession, getActiveDataOwnerPushStamp } from '../appSessionState.js';import type { AgentMeta } from '../../renderer/lib/ccAgent.types';import {deriveAutoTitleSeed,getAgentFacingText,+ normalizeAgentInputClearBoundaryMs,serializeSessionReferencePayload,+ type AgentInputClearBoundaryOpts,type AgentInputCreateOpts,type AgentInputQueuedMessage,type AgentInputSessionRef,@@ -90,12 +92,16 @@ import {RenameSessionsConfirmBridge,type RenameSessionsConfirmInteractionSnapshot,} from '../session-title-rename/index.js';+import { getBrowserAvailability, openBrowserForLogin } from '../mcp-integrations/browser.js';import {- getBrowserAvailability,- openBrowserForLogin,-} from '../mcp-integrations/browser.js';-import { getActiveCodexBridgeInstanceId, getActiveCodexBridgeServerNames, shutdownCodexEnvironment } from '../mcp-integrations/codexEnvironment.js';-import { invalidatePiEnvironment, shutdownPiEnvironment } from '../mcp-integrations/piEnvironment.js';+ getActiveCodexBridgeInstanceId,+ getActiveCodexBridgeServerNames,+ shutdownCodexEnvironment,+} from '../mcp-integrations/codexEnvironment.js';+import {+ invalidatePiEnvironment,+ shutdownPiEnvironment,+} from '../mcp-integrations/piEnvironment.js';import { REMOTE_MEMORY_SERVER_NAME } from '../mcp-integrations/codexHttpBridge.js';import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToken.js';import {@@ -136,15 +142,18 @@ import {supportsAtProjectAgentResources,} from './atAgentCatalog.js';import * as imageCacheStore from '../imageCacheStore.js';-import { collectCindyMediaUrls, commitChatImageUrls } from '../cindy-media/chatAttachments.js';import * as cindyChatAttachments from '../cindy-media/chatAttachments.js';import { materializeGeneratedImage } from '../cindy-media/generatedMedia.js';import { getDbClient } from '../localDb/client/current.js';import {+ awaitAgentInputQueueSnapshotPersistence,loadAgentInputQueueSnapshot,saveAgentInputQueueSnapshot,} from '../localDb/agentInputQueueSnapshots.js';-import { ensureDialogueWorkspaceDir, dialogueWorkspaceRootDir } from '../localDb/dialogueWorkspace.js';+import {+ ensureDialogueWorkspaceDir,+ dialogueWorkspaceRootDir,+} from '../localDb/dialogueWorkspace.js';import {healMissingDialogueWorkdir,matchDialogueWorkspacePath,@@ -154,6 +163,7 @@ import {broadcastMessageDeleted,commitMessageDeletion,createMessage as createDbMessage,+ rewindPersistedUserMessageAfterClear,findParkedEngineSession,getMessageDeletionTarget,listMessagesForAgentHandoff,@@ -170,6 +180,7 @@ import {clearSessionContextInDb,createSessionRemoteHostIdReader,getSessionRowSnapshot,+ getSessionRowSnapshotStrict,persistSessionFields,} from '../localDb/ipc/sessions.js';// sidebar-card-mode: turn-done 后触发任务现状摘要生成@@ -200,10 +211,22 @@ import {import { messages, orcaTeams, orcaWorkers, sessions } from '../localDb/schema.js';import { t } from '../i18n.js';import { createLogger } from '../logger.js';-import { desktopClaudeAuthAdapter, desktopCodexAuthAdapter, readClaudeApiKey } from '../maker-host/auth-adapters.js';+import {+ desktopClaudeAuthAdapter,+ desktopCodexAuthAdapter,+ readClaudeApiKey,+} from '../maker-host/auth-adapters.js';import { prepareSharedProjectSkillLinks } from '../maker-host/shared-global-skills.js';-import { setRemoteCodexLiveTurnChecker, setRemoteSessionStartEnsure, getRemoteCcTurnSettledHandler, getRemoteCcStaleQuery } from '../maker-host/remote-session-start-ensure.js';-import { getCodexProxyAuthInjection, getCodexProxyAuthInjectionState } from '../maker-host/codex-proxy-host.js';+import {+ setRemoteCodexLiveTurnChecker,+ setRemoteSessionStartEnsure,+ getRemoteCcTurnSettledHandler,+ getRemoteCcStaleQuery,+} from '../maker-host/remote-session-start-ensure.js';+import {+ getCodexProxyAuthInjection,+ getCodexProxyAuthInjectionState,+} from '../maker-host/codex-proxy-host.js';import {readCollaborationSettings,readCollaborationSettingsState,@@ -302,13 +325,21 @@ import {saveTurnStartedAtForDeferred,} from '../messagePersistBroadcaster.js';import { ensureCcManagerInstalledOrInstall } from '../remote-ssh/cc-manager-install.js';-import { ensureRemoteCodexMcpBridge, hasPendingRemoteMcpDrift } from '../remote-ssh/codex-remote-mcp.js';+import {+ ensureRemoteCodexMcpBridge,+ hasPendingRemoteMcpDrift,+} from '../remote-ssh/codex-remote-mcp.js';import {hasPendingAgentProxyReconcile,reconcileCodexAgentProxyEnv,setAgentProxyLiveTurnChecker,} from '../remote-ssh/agent-proxy.js';-import { ensureRemoteAgentInstalledOrInstall, ensureRemoteHostReady, getRemoteSshPool, isCcMgrUpgradeInFlight } from '../remote-ssh/index.js';+import {+ ensureRemoteAgentInstalledOrInstall,+ ensureRemoteHostReady,+ getRemoteSshPool,+ isCcMgrUpgradeInFlight,+} from '../remote-ssh/index.js';import {recordSessionContextSnapshot,recordSessionTurnSpend,@@ -324,13 +355,50 @@ import {import { recordModelMismatchOnMessage } from '../modelMismatchBroadcaster.js';import { detectClaudeModelMismatch } from '../../shared/modelMismatch.js';import { triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';-import { getGatewayAccountCurrency, getGatewayModelPricingForModel, getModelPriceQuote } from '../usage/modelPricing.js';-import { broadcastReferenceModelPricing, getCodexProviderSubscriptionValuePrice, getReferenceModelPricing, getSubscriptionDirectValuePrice } from '../usage/referenceModelPricing.js';-import { clearModelPriceOverride, stageProviderModelPriceOverridesClear, readModelPriceOverrideView, setModelPriceOverride } from '../usage/modelPriceOverrideStore.js';-import { computeModelUsageDeltas, detectOutputLag, type ModelUsageCumulative, type ModelUsageDeltaEntry } from '../usage/modelUsageDelta.js';-import { claudeSubscriptionUsageModelKey, codexApiUsageModelKey, codexSubscriptionUsageModelKey, piSubscriptionUsageModelKey } from '../usage/usageHistory.js';-import { billingRouteForExplicitProvider, buildClaudeTurnUsageDetails, computePriceQuoteTurnMoney, estimateClaudeSubscriptionTurnValue, isAnthropicModel, normalizeModelIdForPricing, resolveClaudeTurnCostSinks, type BillingRoute } from '../usage/turnCostCalculator.js';-import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX, isSubscriptionDirectModel } from '../../shared/subscriptionModels.js';+import {+ getGatewayAccountCurrency,+ getGatewayModelPricingForModel,+ getModelPriceQuote,+} from '../usage/modelPricing.js';+import {+ broadcastReferenceModelPricing,+ getCodexProviderSubscriptionValuePrice,+ getReferenceModelPricing,+ getSubscriptionDirectValuePrice,+} from '../usage/referenceModelPricing.js';+import {+ clearModelPriceOverride,+ stageProviderModelPriceOverridesClear,+ readModelPriceOverrideView,+ setModelPriceOverride,+} from '../usage/modelPriceOverrideStore.js';+import {+ computeModelUsageDeltas,+ detectOutputLag,+ type ModelUsageCumulative,+ type ModelUsageDeltaEntry,+} from '../usage/modelUsageDelta.js';+import {+ claudeSubscriptionUsageModelKey,+ codexApiUsageModelKey,+ codexSubscriptionUsageModelKey,+ piSubscriptionUsageModelKey,+} from '../usage/usageHistory.js';+import {+ billingRouteForExplicitProvider,+ buildClaudeTurnUsageDetails,+ computePriceQuoteTurnMoney,+ estimateClaudeSubscriptionTurnValue,+ isAnthropicModel,+ normalizeModelIdForPricing,+ resolveClaudeTurnCostSinks,+ type BillingRoute,+} from '../usage/turnCostCalculator.js';+import {+ CHATGPT_MODEL_PREFIX,+ XAI_MODEL_PREFIX,+ isSubscriptionDirectModel,+} from '../../shared/subscriptionModels.js';import {addRegionalMoney,usdToLedgerCurrency,@@ -350,9 +418,7 @@ import {import { throwIpcError } from '../utils/ipcValidate.js';import { dbToMakerAgentKind, makerToDbAgentKind } from '../../shared/agentKindConversion.js';import { readWorkflowProgressForSession } from '../workflow-progress/reader.js';-import {- AgentInputCoordinator,-} from './agent-input-coordinator.js';+import { AgentInputCoordinator } from './agent-input-coordinator.js';import {estimateReferenceTokens,MAX_REFERENCE_MESSAGES,@@ -362,15 +428,16 @@ import {} from './sessionReferenceResolver.js';import { registerAndroidAutomationHandlers } from './androidHandlers.js';import { MAKER_INVOKE, MAKER_PUSH, MAKER_SEND } from './channels.js';-import type {- CollabDispatchOutcome,-} from './collabSendOutcome.js';+import type { CollabDispatchOutcome } from './collabSendOutcome.js';import { runAcceptedCallback } from './acceptedCallbackRunner.js';import { createElectronIpcHandlerRegistry } from './electronIpcRegistry.js';import { refreshCodexMcpEnvironment } from './codexMcpRefresh.js';import { broadcastSchedulerChanged } from './schedule.js';import { validateExtraDirs } from './extraDirsValidator.js';-import { prepareHandoffWorktree, shouldRecycleHandoffWorktreeOnFailure } from './handoffWorktree.js';+import {+ prepareHandoffWorktree,+ shouldRecycleHandoffWorktreeOnFailure,+} from './handoffWorktree.js';import { validateHandoffWorkingDir } from './handoffWorkingDir.js';import { registerProjectPluginPolicyHandlers } from './projectPluginPolicyHandlers.js';import { registerPrecreatedWorktreeDiscardHandler } from './precreatedWorktreeDiscardHandler.js';@@ -403,8 +470,10 @@ import { registerMakerMessageDeleteHandler } from './messageDeleteHandler.js';import {normalizeUserMessage,materializeDirectSendOssAttachments,+ materializeQueuedOssAttachmentsDeferred,materializeQueuedOssAttachments,} from './normalizeAttachments.js';+import { QueuedAttachmentOwnershipRegistry } from './queuedAttachmentOwnership.js';import { AGENT_ISLAND_DISPLAY_CONFIG } from '../agent-island/displayConfig.js';import {shouldClearAgentIslandSessionForOrcaWorker,@@ -413,7 +482,14 @@ import {import { getAgentIslandService } from '../agent-island/service.js';import { createOrcaLifecycleService, ORCA_WORKER_READY_MESSAGE } from './orcaLifecycleService.js';import { throwOrcaServiceFailure } from './orcaServiceFailure.js';-import { createOrcaTeamService, findFocusTargetWorker, type ListWorkerQueuedMessagesResult, type OrcaTeamService, type OrcaWorkerEffort, type WorkerQueuedMessageControlResult } from './orcaTeamService.js';+import {+ createOrcaTeamService,+ findFocusTargetWorker,+ type ListWorkerQueuedMessagesResult,+ type OrcaTeamService,+ type OrcaWorkerEffort,+ type WorkerQueuedMessageControlResult,+} from './orcaTeamService.js';import {createOrcaWorkerCreationService,normalizeOrcaWorkerLabel,@@ -488,10 +564,7 @@ import {import { getActiveCatalog, setDiscoveredProviderModels } from '../maker-host/active-catalog.js';import { testProviderConnection } from '../maker-host/provider-diagnostics.js';import { fetchProviderModels } from '../maker-host/provider-model-fetch.js';-import {- beginProviderRouteMutation,- isUserProviderSession,-} from '../maker-host/provider-route.js';+import { beginProviderRouteMutation, isUserProviderSession } from '../maker-host/provider-route.js';import {getAnthropicModelDiscoveryFailure,refreshAnthropicModelsFromHttp,@@ -589,9 +662,11 @@ import {isMobileControllerInvoke,} from '../device-link/invoke-context.js';import {+ attachMainOwnedInputBoundary,buildMobileClientPromptNote,- stampMobileClientOrigin,stripMainOnlySendOpts,+ stampMobileClientOrigin,+ type MainOwnedInputBoundaryStamp,} from './mobileClientPromptNote.js';import {assertResolveInteractionOrigin,@@ -606,10 +681,7 @@ import {registerSessionAutoTitleHooks,scheduleSessionAutoTitle,} from './sessionAutoTitle.js';-import {- SILENT_STOP_RESUME_PROMPT,- SilentStopAutoResumeGuard,-} from './silentStopAutoResume.js';+import { SILENT_STOP_RESUME_PROMPT, SilentStopAutoResumeGuard } from './silentStopAutoResume.js';import {publishUiContinuation,publishUiSessionIntervention,@@ -713,11 +785,7 @@ function schedulerAutoResumeRunKey(sessionId: string, runId: string): string {return JSON.stringify([sessionId, runId]);}-function beginSchedulerAutoResume(- sessionId: string,- runId: string,- attemptToken: number,-): void {+function beginSchedulerAutoResume(sessionId: string, runId: string, attemptToken: number): void {pendingSchedulerAutoResumeRunBySession.set(sessionId, { runId, attemptToken });}@@ -922,7 +990,10 @@ export function noteSilentStopSessionReset(sessionId: string): void {* 以便结束被 silentStop done 挂起的 turnFinished promise。* 回调参数 settled=true 表示该 session 的 silent-stop done 已 settle(不再续跑)。*/-type SilentStopSettledCb = (sessionId: string, reason: 'exhausted' | 'skip' | 'send-failed') => void;+type SilentStopSettledCb = (+ sessionId: string,+ reason: 'exhausted' | 'skip' | 'send-failed',+) => void;const silentStopSettledListeners = new Map<string, Set<SilentStopSettledCb>>();export function onSilentStopSettled(sessionId: string, cb: SilentStopSettledCb): () => void {@@ -938,11 +1009,18 @@ export function onSilentStopSettled(sessionId: string, cb: SilentStopSettledCb):};}-function fireSilentStopSettled(sessionId: string, reason: 'exhausted' | 'skip' | 'send-failed'): void {+function fireSilentStopSettled(+ sessionId: string,+ reason: 'exhausted' | 'skip' | 'send-failed',+): void {const set = silentStopSettledListeners.get(sessionId);if (set) {for (const cb of set) {- try { cb(sessionId, reason); } catch { /* swallow */ }+ try {+ cb(sessionId, reason);+ } catch {+ /* swallow */+ }}}}@@ -952,13 +1030,12 @@ const COLLABORATION_SETTING_KEYS = ['workerHardLimit','workerIdleReleaseMinutes',] as const;-type CollaborationSettingKey = typeof COLLABORATION_SETTING_KEYS[number];+type CollaborationSettingKey = (typeof COLLABORATION_SETTING_KEYS)[number];const COLLABORATION_WORKER_LIMIT_MAX = 20;const COLLABORATION_IDLE_RELEASE_MAX_MINUTES = 120;function isCollaborationSettingKey(key: unknown): key is CollaborationSettingKey {- return typeof key === 'string'- && (COLLABORATION_SETTING_KEYS as readonly string[]).includes(key);+ return typeof key === 'string' && (COLLABORATION_SETTING_KEYS as readonly string[]).includes(key);}function requireInteger(value: unknown, key: CollaborationSettingKey): number {@@ -974,7 +1051,10 @@ function validateCollaborationSettingValue(key: CollaborationSettingKey, value:if (key === 'workerIdleReleaseMinutes') {if (next < 0) throwIpcError('INVALID_PARAMS', `${key} must be >= 0`);if (next > COLLABORATION_IDLE_RELEASE_MAX_MINUTES) {- throwIpcError('INVALID_PARAMS', `${key} must be <= ${COLLABORATION_IDLE_RELEASE_MAX_MINUTES}`);+ throwIpcError(+ 'INVALID_PARAMS',+ `${key} must be <= ${COLLABORATION_IDLE_RELEASE_MAX_MINUTES}`,+ );}return next;}@@ -1176,7 +1256,8 @@ type SendToSessionCreateDefaults = {permissionMode?: 'ask' | 'default' | 'acceptEdits' | 'plan' | 'auto' | 'bypassPermissions';};-type SendToSessionInternalResult = | {+type SendToSessionInternalResult =+ | {ok: true;/** 目标 session 的 business id。create 分支回传新建 id;jump 分支回显入参 id。 */targetSessionId: string;@@ -1208,23 +1289,21 @@ type SendToSessionInternalResult = | {/** 暴露给 xdt-helper MCP provider 的协同控制面,必须复用 IPC 同源业务路径。 */interface OrcaCollabService {- sendToSession: (- params: {- /** 省略 → create 新 session;提供 → jump 到该既有 session。 */- targetSessionId?: string;- message: string;- /** 调用方(dispatcher)自身 session id,create 分支据此继承配置;未绑定 session ctx 时为 undefined。 */- dispatcherSessionId?: string;- /** create 分支可选标题;省略则用消息首行兜底。 */- title?: string;- /** create 分支可选:true = 为新 session 预建独立 git worktree 并以其为 workingDir(jump 忽略)。 */- useWorktree?: boolean;- /** create 分支可选:新 session 的工作目录覆盖(绝对路径,须已存在;jump 忽略)。#811 */- workingDir?: string;- /** Host-owned create defaults for non-session callers such as scheduler script tasks. */- createDefaults?: SendToSessionCreateDefaults;- },- ) => Promise<SendToSessionInternalResult>;+ sendToSession: (params: {+ /** 省略 → create 新 session;提供 → jump 到该既有 session。 */+ targetSessionId?: string;+ message: string;+ /** 调用方(dispatcher)自身 session id,create 分支据此继承配置;未绑定 session ctx 时为 undefined。 */+ dispatcherSessionId?: string;+ /** create 分支可选标题;省略则用消息首行兜底。 */+ title?: string;+ /** create 分支可选:true = 为新 session 预建独立 git worktree 并以其为 workingDir(jump 忽略)。 */+ useWorktree?: boolean;+ /** create 分支可选:新 session 的工作目录覆盖(绝对路径,须已存在;jump 忽略)。#811 */+ workingDir?: string;+ /** Host-owned create defaults for non-session callers such as scheduler script tasks. */+ createDefaults?: SendToSessionCreateDefaults;+ }) => Promise<SendToSessionInternalResult>;enableOrca: (leadSessionId: string,opts: EnableOrcaOptions,@@ -1237,9 +1316,9 @@ interface OrcaCollabService {}>;disableOrca: (leadSessionId: string) => Promise<{ ok: true }>;/** start_team 只建立 team,不隐式创建 worker。 */- startTeam: (params: { leadSessionId: string }) => Promise<- { ok: true; teamId: string } | { ok: false; errorCode: string; message: string }- >;+ startTeam: (params: {+ leadSessionId: string;+ }) => Promise<{ ok: true; teamId: string } | { ok: false; errorCode: string; message: string }>;createWorker: (params: {leadSessionId: string;role: string;@@ -1250,14 +1329,14 @@ interface OrcaCollabService {label: string;initialTask?: string;}) => Promise<- {- ok: true;- workerId: string;- workerSessionId: string;- softLimitExceeded?: boolean;- dispatched?: boolean;- dispatchOutcome?: CollabDispatchOutcome;- }+ | {+ ok: true;+ workerId: string;+ workerSessionId: string;+ softLimitExceeded?: boolean;+ dispatched?: boolean;+ dispatchOutcome?: CollabDispatchOutcome;+ }| { ok: false; errorCode: string; message: string }>;createWorkerFromTask: (params: {@@ -1265,109 +1344,149 @@ interface OrcaCollabService {task: string;agentKind: AgentKind;}) => Promise<- {- ok: true;- workerId: string;- workerSessionId: string;- label: string;- softLimitExceeded?: boolean;- dispatched?: boolean;- dispatchOutcome?: CollabDispatchOutcome;- }+ | {+ ok: true;+ workerId: string;+ workerSessionId: string;+ label: string;+ softLimitExceeded?: boolean;+ dispatched?: boolean;+ dispatchOutcome?: CollabDispatchOutcome;+ }| { ok: false; errorCode: string; message: string }>;listWorkers: (params: { leadSessionId: string }) => Promise<- { ok: true; workers: Array<{- workerId: string;- sessionId: string;- role: string;- agent: AgentKind;- model: string;- effort: string | null;- label: string | null;- status: string;- focused: boolean;- idleSince: string | null;- }> }+ | {+ ok: true;+ workers: Array<{+ workerId: string;+ sessionId: string;+ role: string;+ agent: AgentKind;+ model: string;+ effort: string | null;+ label: string | null;+ status: string;+ focused: boolean;+ idleSince: string | null;+ }>;+ }| { ok: false; errorCode: string; message: string }>;getWorkspaceInfo: (params: { leadSessionId: string }) => Promise<- {- ok: true;- workflow: {- workflow_id: string;- lead_session_id: string;- status: string;- } | null;- ui_capacity: number;- worker_count: number;- workers: Array<{+ | {+ ok: true;+ workflow: {+ workflow_id: string;+ lead_session_id: string;+ status: string;+ } | null;+ ui_capacity: number;+ worker_count: number;+ workers: Array<{+ worker_id: string;+ session_id: string;+ status: string;+ session_status: string;+ idle_ms: number | null;+ restored_from_storage: boolean;+ label: string | null;+ role: string;+ agent_kind: AgentKind;+ model: string;+ effort: string | null;+ focused: boolean;+ working_dir: string;+ }>;+ }+ | { ok: false; errorCode: string; message: string }+ >;+ getWorkerStatus: (params: { leadSessionId: string; workerId: string }) => Promise<+ | {+ ok: true;worker_id: string;session_id: string;status: string;session_status: string;idle_ms: number | null;restored_from_storage: boolean;- label: string | null;- role: string;- agent_kind: AgentKind;- model: string;- effort: string | null;- focused: boolean;- working_dir: string;- }>;- }- | { ok: false; errorCode: string; message: string }- >;- getWorkerStatus: (params: { leadSessionId: string; workerId: string }) => Promise<- {- ok: true;- worker_id: string;- session_id: string;- status: string;- session_status: string;- idle_ms: number | null;- restored_from_storage: boolean;- }+ }| { ok: false; errorCode: string; message: string }>;readWorker: (params: { leadSessionId: string; workerId: string }) => Promise<- {- ok: true;- worker_id: string;- session_id: string;- status: string;- session_status: string;- result: string;- }- | { ok: false; errorCode: string; message: string }- >;- switchFocus: (params: { leadSessionId: string; workerIdOrLabel: string }) => Promise<- { ok: true; workerId: string }+ | {+ ok: true;+ worker_id: string;+ session_id: string;+ status: string;+ session_status: string;+ result: string;+ }| { ok: false; errorCode: string; message: string }>;+ switchFocus: (params: {+ leadSessionId: string;+ workerIdOrLabel: string;+ }) => Promise<{ ok: true; workerId: string } | { ok: false; errorCode: string; message: string }>;// sendToWorker 的语义跟 sendToSession 的 create 分支完全不同 — worker 派活// 永远投递到既有 worker session,绝不创建新 session。holder 只暴露 service// 边界的窄契约,避免 sendToSession 的 create 模式漏进 worker 派活语义。- sendToWorker: (params: { callerLeadSessionId: string; targetSessionId: string; message: string }) => Promise<- { ok: true; agentKind: AgentKind; wakeKind: 'resumed' | 'already-active' | 'queued'; targetTitle: string | null; targetLastUserSendAt: string | null; queuedMessageId?: string }+ sendToWorker: (params: {+ callerLeadSessionId: string;+ targetSessionId: string;+ message: string;+ }) => Promise<+ | {+ ok: true;+ agentKind: AgentKind;+ wakeKind: 'resumed' | 'already-active' | 'queued';+ targetTitle: string | null;+ targetLastUserSendAt: string | null;+ queuedMessageId?: string;+ }| { ok: false; errorCode: string; message: string }>;// 排队消息控制:只作用于 lead 自己发出的 orca 排队条目,归属校验与 send/idle/archive 同一套 resolveWorkerRef。- listWorkerQueuedMessages: (params: { callerLeadSessionId: string; workerRef: string }) => Promise<ListWorkerQueuedMessagesResult>;- updateWorkerQueuedMessage: (params: { callerLeadSessionId: string; workerRef: string; queuedMessageId: string; message: string }) => Promise<WorkerQueuedMessageControlResult>;- cancelWorkerQueuedMessage: (params: { callerLeadSessionId: string; workerRef: string; queuedMessageId: string }) => Promise<WorkerQueuedMessageControlResult>;- idleWorker: (params: { callerLeadSessionId: string; workerId: string; expectedStatus?: 'done' }) => Promise<+ listWorkerQueuedMessages: (params: {+ callerLeadSessionId: string;+ workerRef: string;+ }) => Promise<ListWorkerQueuedMessagesResult>;+ updateWorkerQueuedMessage: (params: {+ callerLeadSessionId: string;+ workerRef: string;+ queuedMessageId: string;+ message: string;+ }) => Promise<WorkerQueuedMessageControlResult>;+ cancelWorkerQueuedMessage: (params: {+ callerLeadSessionId: string;+ workerRef: string;+ queuedMessageId: string;+ }) => Promise<WorkerQueuedMessageControlResult>;+ idleWorker: (params: {+ callerLeadSessionId: string;+ workerId: string;+ expectedStatus?: 'done';+ }) => Promise<{ ok: true; workerId?: string } | { ok: false; errorCode: string; message: string }>;- endTeam: (params: { leadSessionId: string }) => Promise<- { ok: true } | { ok: false; errorCode: string; message: string }- >;- archiveWorker: (params: { callerLeadSessionId: string; workerId: string }) => Promise<+ endTeam: (params: {+ leadSessionId: string;+ }) => Promise<{ ok: true } | { ok: false; errorCode: string; message: string }>;+ archiveWorker: (params: {+ callerLeadSessionId: string;+ workerId: string;+ }) => Promise<{ ok: true; workerId?: string } | { ok: false; errorCode: string; message: string }>;- listAvailableModels: (params: { agent?: AgentKind }) => Promise<- { ok: true; codex?: Array<{ id: string; label: string }>; claude_code?: Array<{ id: string; label: string }>; pi?: Array<{ id: string; label: string }> }+ listAvailableModels: (params: {+ agent?: AgentKind;+ }) => Promise<+ | {+ ok: true;+ codex?: Array<{ id: string; label: string }>;+ claude_code?: Array<{ id: string; label: string }>;+ pi?: Array<{ id: string; label: string }>;+ }| { ok: false; errorCode: string; message: string }>;}@@ -1388,7 +1507,10 @@ let orcaCollabServiceHolder: OrcaCollabService | null = null;// session event wiring 是模块级函数;service 在 registerMakerIpc 内构造后注入给事件回调。let orcaTeamServiceForEvents: OrcaTeamService | null = null;-function markWorkerManualInterruptIfKnown(sessionId: string, reason: 'input_stop' | 'abort_session'): boolean {+function markWorkerManualInterruptIfKnown(+ sessionId: string,+ reason: 'input_stop' | 'abort_session',+): boolean {if (!isKnownOrcaWorkerSession(sessionId)) return false;markManualInterrupt(sessionId, reason);return true;@@ -1400,17 +1522,24 @@ export type {OrcaInterAgentMessageSource,};-type DispatchOrcaInterAgentMessage = (params: DispatchOrcaInterAgentMessageParams) => Promise<DispatchOrcaInterAgentMessageResult>;+type DispatchOrcaInterAgentMessage = (+ params: DispatchOrcaInterAgentMessageParams,+) => Promise<DispatchOrcaInterAgentMessageResult>;let dispatchInterAgentMessageHolder: DispatchOrcaInterAgentMessage | null = null;-export async function dispatchInterAgentMessage(params: DispatchOrcaInterAgentMessageParams): Promise<DispatchOrcaInterAgentMessageResult> {+export async function dispatchInterAgentMessage(+ params: DispatchOrcaInterAgentMessageParams,+): Promise<DispatchOrcaInterAgentMessageResult> {const dispatch = dispatchInterAgentMessageHolder;if (!dispatch) {return {ok: false,dispatchOutcome: {- ...createHostSendFailure('SEND_FAILED', 'orca inter-agent dispatch service not initialized'),+ ...createHostSendFailure(+ 'SEND_FAILED',+ 'orca inter-agent dispatch service not initialized',+ ),source: params.meta.source,context: params.meta.context,},@@ -1463,8 +1592,7 @@ function requireAgentKind(value: unknown): AgentKind {}type IpcUserMessage =- | string- | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> };+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> };async function prepareUserMessageForAgent(sessionId: string,@@ -1492,21 +1620,11 @@ async function prepareUserMessageForAgent(});}}- // 媒体总仓晋升:消息里的 cindy-media blob 挂 session-attachment 引用(草稿- // 转正,替代 markFilesCommitted;幂等,重发不刷重复行)。失败只警告——- // 引用缺失的代价是 blob 提前进回收候选,不该阻塞消息发送。- const sentBlobUrls = collectCindyMediaUrls(msg);- if (sentBlobUrls.length > 0) {- try {- await commitChatImageUrls({ sessionId, urls: sentBlobUrls });- } catch (err) {- log.warn(`${logPrefix}: commit cindy-media attachment refs failed`, {- sessionId,- blobCount: sentBlobUrls.length,- error: err instanceof Error ? err.message : String(err),- });- }- }+ // cindy-media 晋升必须跟 durable user message 同步发生(createMessage 的+ // commitMessageMediaRefs)。这里仍可能在消息行落库前被 /clear 或 steer 取消;+ // 若提前挂 session-attachment 粗引用,取消路径没有 owner token 可补偿,清空后+ // 会把无主 blob 永久 pin 在 session 上。排队物化的本地副本由自身 ownership+ // registry 管理;直接发送则交给 durable message writer 在 row 成功后挂账。return normalized as IpcUserMessage;}@@ -1637,18 +1755,13 @@ const ghostSetupInteractionBridge = initGhostSetupInteractionBridge({getAgentIslandService()?.handlePluginSetupInteraction(value.sessionId,value.request.requestId,- activeStep?.title ?? t('newChat.pluginSetup.title').replace('{{name}}', value.request.ghost.name),+ activeStep?.title ??+ t('newChat.pluginSetup.title').replace('{{name}}', value.request.ghost.name),);return;}- if (- channel === MAKER_PUSH.INTERACTION_DISMISSED &&- typeof value.requestId === 'string'- ) {- getAgentIslandService()?.handleInteractionDismissed(- value.sessionId,- value.requestId,- );+ if (channel === MAKER_PUSH.INTERACTION_DISMISSED && typeof value.requestId === 'string') {+ getAgentIslandService()?.handleInteractionDismissed(value.sessionId, value.requestId);}},logger: log,@@ -1693,7 +1806,9 @@ initGhostSetupCoordinator({return { ok: true };},getGhostIdentity: (ghostId) => {- const ghost = getGhostManager().list().find((candidate) => candidate.manifest.id === ghostId);+ const ghost = getGhostManager()+ .list()+ .find((candidate) => candidate.manifest.id === ghostId);return ghost? {id: ghostId,@@ -1741,24 +1856,17 @@ type PendingInteractionSnapshotEntry = {* INTERACTION_REQUEST push 设置,后加入的窗口会错过那条 push,靠这个查询补回。* 纯内存读;O(N) 其中 N = 全局挂起交互数(极小)。*/-function getPendingInteractionsForSession(- sessionId: string,-): PendingInteractionSnapshotEntry[] {+function getPendingInteractionsForSession(sessionId: string): PendingInteractionSnapshotEntry[] {const out: PendingInteractionSnapshotEntry[] = [];for (const entry of pendingInteractionResolvers.values()) {- if (entry.sessionId === sessionId) out.push({ request: entry.request, persistId: entry.persistId });+ if (entry.sessionId === sessionId)+ out.push({ request: entry.request, persistId: entry.persistId });}out.push(...issueConfirmBridge.pendingSnapshots(sessionId).map(({ request }) => ({ request })),- ...renameSessionsConfirmBridge- .pendingSnapshots(sessionId)- .map(({ request }) => ({ request })),- ...ghostGrantConfirmBridge- .pendingSnapshots(sessionId)- .map(({ request }) => ({ request })),- ...ghostSetupInteractionBridge- .pendingSnapshots(sessionId)- .map(({ request }) => ({ request })),+ ...renameSessionsConfirmBridge.pendingSnapshots(sessionId).map(({ request }) => ({ request })),+ ...ghostGrantConfirmBridge.pendingSnapshots(sessionId).map(({ request }) => ({ request })),+ ...ghostSetupInteractionBridge.pendingSnapshots(sessionId).map(({ request }) => ({ request })),);return out;}@@ -1770,16 +1878,15 @@ function getPendingInteractionsForSession(*/function hasPendingAgentInteractionForSession(sessionId: string): boolean {return (- Array.from(pendingInteractionResolvers.values()).some((entry) => entry.sessionId === sessionId) ||- ghostSetupInteractionBridge.pendingSnapshots(sessionId).length > 0+ Array.from(pendingInteractionResolvers.values()).some(+ (entry) => entry.sessionId === sessionId,+ ) || ghostSetupInteractionBridge.pendingSnapshots(sessionId).length > 0);}function isPendingDesktopOnlyConfirmation(requestId: string): boolean {return (- issueConfirmBridge- .pendingSnapshots()- .some(({ request }) => request.requestId === requestId) ||+ issueConfirmBridge.pendingSnapshots().some(({ request }) => request.requestId === requestId) ||renameSessionsConfirmBridge.pendingSnapshots().some(({ request }) => request.requestId === requestId) ||@@ -1819,7 +1926,8 @@ function resolvePendingInteraction(requestId: string, decision: InteractionDecisresolver.resolve(decision);// 广播「已解决」让**所有其它 renderer**(被控端自己的窗口 + 其它控制端 + 多窗口)收敛清面板。// 多端镜像下同一交互面板可能同时开在多处,只有发起方乐观本地清了 —— 不广播则其它方卡住。- const resolvedAs = decision.kind === 'permission' && decision.behavior === 'allow' ? 'allow' : 'deny';+ const resolvedAs =+ decision.kind === 'permission' && decision.behavior === 'allow' ? 'allow' : 'deny';dismissRendererInteraction(resolver, requestId, 'resolved', resolvedAs, decision);// 交互曾是队列 drain 的 busy 门(hasPendingInteraction)。只在「不会带外启动// 后续 turn」的 resolve 上唤醒:plan_review 的批准/反馈会由 agent 带外自动发起@@ -1843,13 +1951,22 @@ function resolvePendingInteraction(requestId: string, decision: InteractionDecisresolver.sessionId,resolver.persistId,resolver.kind,- resolver.request as { requestId?: unknown; questions?: unknown; plan?: unknown; planFilePath?: unknown },+ resolver.request as {+ requestId?: unknown;+ questions?: unknown;+ plan?: unknown;+ planFilePath?: unknown;+ },(decision ?? {}) as Record<string, unknown>,);}// (Option B)ask_user_question 答完 → 即时改写该会话的 goal 目标(仅首轮澄清,controller 内 guard)。// 连同本次问题(含选项)一并交出,让 controller 用确定性标记甄别这是不是"目标澄清问题"。- if (resolver.kind === 'ask_user_question' && decision.kind === 'ask_user_question' && goalAskAnswerObserver) {+ if (+ resolver.kind === 'ask_user_question' &&+ decision.kind === 'ask_user_question' &&+ goalAskAnswerObserver+ ) {try {const questions = (resolver.request as { questions?: AskUserQuestions }).questions ?? [];goalAskAnswerObserver(resolver.sessionId, decision.answers ?? {}, questions);@@ -1869,11 +1986,18 @@ function resolvePendingPermissionFromAgentIsland(return resolvePendingInteraction(requestId, decision);}-function isPermissionInteractionDecision(value: unknown): value is Extract<InteractionDecision, { kind: 'permission' }> {- return Boolean(value && typeof value === 'object' && (value as { kind?: unknown }).kind === 'permission');+function isPermissionInteractionDecision(+ value: unknown,+): value is Extract<InteractionDecision, { kind: 'permission' }> {+ return Boolean(+ value && typeof value === 'object' && (value as { kind?: unknown }).kind === 'permission',+ );}-function defaultDecisionForPending(kind: InteractionRequest['kind'], reason: string): InteractionDecision {+function defaultDecisionForPending(+ kind: InteractionRequest['kind'],+ reason: string,+): InteractionDecision {if (kind === 'ask_user_question') {return { kind: 'ask_user_question', answers: {} };}@@ -1886,8 +2010,9 @@ function defaultDecisionForPending(kind: InteractionRequest['kind'], reason: str}function cleanupPendingAgentInteractionsForSession(sessionId: string, reason: string): void {- const entries = Array.from(pendingInteractionResolvers.entries())- .filter(([, entry]) => entry.sessionId === sessionId);+ const entries = Array.from(pendingInteractionResolvers.entries()).filter(+ ([, entry]) => entry.sessionId === sessionId,+ );for (const [requestId, entry] of entries) {clearPendingInteraction(requestId);handleAgentIslandInteractionDismissed(sessionId, requestId);@@ -1939,10 +2064,19 @@ function cleanupPendingInteractionsForSession(sessionId: string, reason: string)*/export function takePendingInteractionsForSession(sessionId: string,-): Array<{ requestId: string; request: InteractionRequest; resolve: (decision: InteractionDecision) => void }> {- const entries = Array.from(pendingInteractionResolvers.entries())- .filter(([, entry]) => entry.sessionId === sessionId);- const taken: Array<{ requestId: string; request: InteractionRequest; resolve: (decision: InteractionDecision) => void }> = [];+): Array<{+ requestId: string;+ request: InteractionRequest;+ resolve: (decision: InteractionDecision) => void;+}> {+ const entries = Array.from(pendingInteractionResolvers.entries()).filter(+ ([, entry]) => entry.sessionId === sessionId,+ );+ const taken: Array<{+ requestId: string;+ request: InteractionRequest;+ resolve: (decision: InteractionDecision) => void;+ }> = [];for (const [requestId, entry] of entries) {clearPendingInteraction(requestId);taken.push({ requestId, request: entry.request, resolve: entry.resolve });@@ -2323,7 +2457,12 @@ export async function registerPendingCredentialSwitchForSession(// previousRoute 回滚(model/provider/effort/fast 一致成对,第十六、十八轮)。// deferred 场景会话正在跑 turn,live handle 必在;取不到就不带 = 无从回滚。const live = getMaker().getSession(sessionId);- let prevRow: { model: string | null; effort: string | null; fastMode: boolean | null; providerId: string | null } | null = null;+ let prevRow: {+ model: string | null;+ effort: string | null;+ fastMode: boolean | null;+ providerId: string | null;+ } | null = null;try {const [row] = await getDbClient().drizzle.select({@@ -2376,9 +2515,7 @@ export function getPendingCredentialSwitchTarget(sessionId: string,): { model: string; providerId: string | null } | undefined {const pending = pendingCredentialSwitchHolder?.get(sessionId);- return pending- ? { model: pending.model, providerId: pending.providerId }- : undefined;+ return pending ? { model: pending.model, providerId: pending.providerId } : undefined;}// ── Scheduler 撞忙排队桥(scheduler-host runner 消费)────────────────────────@@ -2410,10 +2547,7 @@ export interface SchedulerQueuedPromptRequest {* 或崩溃恢复快照尚未成功读回(retry —— 恢复完成前不能做持久化去重,调用方* 顺延本次 fire 稍后再试,防止恢复后与快照里的同任务项双份派发)。*/-export type SchedulerEnqueueResult =- | { clientId: string }- | { duplicate: true }- | { retry: true };+export type SchedulerEnqueueResult = { clientId: string } | { duplicate: true } | { retry: true };interface SchedulerQueueBridge {isSessionBusy(sessionId: string): boolean;@@ -2497,7 +2631,8 @@ function handleAgentIslandEventAfterBroadcast(agentInputCoordinatorHolder?.isAutoResumePending(session.id) === true ||agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id) === true;const autoResumeOwnsError =- autoResumePendingOrDeferred || autoResumeBookkeeping.shouldSuppressAgentIslandError(session.id);+ autoResumePendingOrDeferred ||+ autoResumeBookkeeping.shouldSuppressAgentIslandError(session.id);const autoResumeOwnsCompletionTail =autoResumePendingOrDeferred ||autoResumeBookkeeping.shouldSuppressAgentIslandCompletionTail(session.id);@@ -2533,10 +2668,13 @@ function surfaceSuppressedAutoResumeErrorInAgentIsland(if (!service) return;const wired = wiredSessionsById.get(sessionId)?.session;const meta = wired ? sessionMetaForIsland(wired) : { sessionId };- service.handleAgentEvent(meta, redactEventForRenderer({- type: 'error',- data: { ...detail, isTerminal: true },- }));+ service.handleAgentEvent(+ meta,+ redactEventForRenderer({+ type: 'error',+ data: { ...detail, isTerminal: true },+ }),+ );} catch (error) {log.warn('Agent Island suppressed auto-resume error restore failed', {sessionId,@@ -2549,14 +2687,18 @@ function isRemoteAuthRetryErrorEvent(session: { agentKind?: unknown; remoteHostId?: unknown },event: AgentEvent,): boolean {- if (!session.remoteHostId || event.type !== 'error' || !isTerminalTurnErrorEvent(event)) return false;+ if (!session.remoteHostId || event.type !== 'error' || !isTerminalTurnErrorEvent(event))+ return false;if (session.agentKind === 'codex') return false;- const data = event.data as { message?: unknown; sdkError?: unknown; errorStatus?: unknown } | undefined;- return data?.sdkError === 'authentication_failed' ||+ const data = event.data as+ { message?: unknown; sdkError?: unknown; errorStatus?: unknown } | undefined;+ return (+ data?.sdkError === 'authentication_failed' ||data?.errorStatus === 401 ||/authentication_error|invalid.*api.key|401/i.test(typeof data?.message === 'string' ? data.message : '',- );+ )+ );}function handleAgentIslandInteractionAfterBroadcast(@@ -2704,7 +2846,11 @@ function commitAgentIslandUserPrompt(sessionId: string, clientId: string | undef}}-function rollbackAgentIslandUserPrompt(sessionId: string, clientId: string | undefined, source: string): void {+function rollbackAgentIslandUserPrompt(+ sessionId: string,+ clientId: string | undefined,+ source: string,+): void {if (!shouldNotifyAgentIslandForSession(sessionId)) return;try {getAgentIslandService()?.rollbackUserPrompt(sessionId, clientId);@@ -2801,7 +2947,9 @@ let goalAskAnswerObserver:| ((sessionId: string, answers: Record<string, string>, questions: AskUserQuestions) => void)| null = null;export function setGoalAskAnswerObserver(- observer: ((sessionId: string, answers: Record<string, string>, questions: AskUserQuestions) => void) | null,+ observer:+ | ((sessionId: string, answers: Record<string, string>, questions: AskUserQuestions) => void)+ | null,): void {goalAskAnswerObserver = observer;}@@ -2816,12 +2964,15 @@ export function setGoalAskAnswerObserver(* turn 通过 beforeProviderStart 登记临时 route,终态只释放自己的 lease,* 不再覆盖或“还原” Desktop listener。重复调用只更新 Desktop fallback。*/-export function installDesktopInteractionListener(- session: { id: string; setInteractionListener: (l: ((req: InteractionRequest) => Promise<InteractionDecision>) | null) => void },-): void {+export function installDesktopInteractionListener(session: {+ id: string;+ setInteractionListener: (+ l: ((req: InteractionRequest) => Promise<InteractionDecision>) | null,+ ) => void;+}): void {installDesktopInteractionHandler(session, async (req: InteractionRequest) => {const agentIslandInteractionEpoch = shouldNotifyAgentIslandForSession(session.id)- ? getAgentIslandService()?.captureInteractionEpoch(session.id) ?? null+ ? (getAgentIslandService()?.captureInteractionEpoch(session.id) ?? null): null;// F1-a Phase 2: interaction(ask_user / plan_review / permission)是 turn 暂停边界,// 且不走 onEvent —— 在这把在飞 assistant 文本落库,等价于 renderer 老逻辑在@@ -2829,10 +2980,8 @@ export function installDesktopInteractionListener(if (agentIslandInteractionEpoch !== null &&shouldNotifyAgentIslandForSession(session.id) &&- getAgentIslandService()?.isInteractionCurrent(- session.id,- agentIslandInteractionEpoch,- ) === false+ getAgentIslandService()?.isInteractionCurrent(session.id, agentIslandInteractionEpoch) ===+ false) {return defaultDecisionForPending(req.kind, 'stale_turn');}@@ -2840,9 +2989,16 @@ export function installDesktopInteractionListener(// F1-a Phase 5: ask_user / plan_review 的消息本身也收口 main 单点落库(单 persistId,// 修 F1 重复),persistId 盖进 payload 让 renderer 用同一 id 建气泡 + answered 回写命中。// permission 不建 chat 消息 → persistId 为 undefined。- const interactionPersistId = onInteractionMessage(session.id, req as unknown as {- kind?: unknown; requestId?: unknown; questions?: unknown; plan?: unknown; planFilePath?: unknown;- });+ const interactionPersistId = onInteractionMessage(+ session.id,+ req as unknown as {+ kind?: unknown;+ requestId?: unknown;+ questions?: unknown;+ plan?: unknown;+ planFilePath?: unknown;+ },+ );broadcastToAllWindows(MAKER_PUSH.INTERACTION_REQUEST, {sessionId: session.id,request: req,@@ -2902,7 +3058,10 @@ export function installDesktopInteractionListener(* (skip / exhausted / send 失败)补发被推迟的 idle + coordinator done 信号,* 让 renderer 正确显示 stopped、scheduler/hook runner 收到 done 并 finish。*/-function settleSilentStopDone(sessionId: string, reason: 'exhausted' | 'skip' | 'send-failed'): void {+function settleSilentStopDone(+ sessionId: string,+ reason: 'exhausted' | 'skip' | 'send-failed',+): void {sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(sessionId);noteClaudeSessionTurnState(sessionId, false);agentInputCoordinatorHolder?.onTurnEvent(sessionId, 'done');@@ -2982,7 +3141,9 @@ async function handleSilentStopTurnEnd(origin: {kind: 'scheduler' as const,scheduleId: turnOrigin.scheduleId,- ...(turnOrigin.scheduleName ? { scheduleName: turnOrigin.scheduleName } : {}),+ ...(turnOrigin.scheduleName+ ? { scheduleName: turnOrigin.scheduleName }+ : {}),...(turnOrigin.runId ? { runId: turnOrigin.runId } : {}),},}@@ -3061,1130 +3222,1026 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidghostSessionTap.dispose();installInteractionLifecycleObserver(session, null);});- registration.disposers.push(session.onEvent((event: AgentEvent) => {- ghostSessionTap.handleEvent(- event as { type: string; data?: unknown; source?: string; turnOrigin?: { kind?: string } },- );- }));+ registration.disposers.push(+ session.onEvent((event: AgentEvent) => {+ ghostSessionTap.handleEvent(+ event as { type: string; data?: unknown; source?: string; turnOrigin?: { kind?: string } },+ );+ }),+ );// 转发事件到所有 window。interaction_dismissed 单独走专用 channel,// 让 renderer chat store 不必扫所有 vendor-raw 找它。- registration.disposers.push(session.onEvent((event: AgentEvent) => {- // 自动续跑的 pending 不能只靠 status(isRunning=true) 清理:Pi/Claude 的- // terminal-only 路径可能首个事件就是 error。Session 已把 host-owned token- // 盖到事件上,首个匹配 token 的事件即视为 provider accepted。- if (typeof event.turnAttemptToken === 'number') {- interruptedTurnAutoResumeGuard.noteAttemptEvent(session.id, event.turnAttemptToken);- }- let attributedEvent = event;- if (event.type === 'error' && isTerminalTurnErrorEvent(event)) {- const reason = !session.remoteHostId && session.agentKind === 'claude-code'- ? consumeClaudeOpusPlanMismatch(session.id)- : null;- if (reason) {- const eventData = event.data && typeof event.data === 'object' && !Array.isArray(event.data)- ? (event.data as Record<string, unknown>)- : {};- attributedEvent = {- ...event,- data: { ...eventData, reason },- };- log.warn('Claude Opus plan error normalized for renderer', {+ registration.disposers.push(+ session.onEvent((event: AgentEvent) => {+ // 自动续跑的 pending 不能只靠 status(isRunning=true) 清理:Pi/Claude 的+ // terminal-only 路径可能首个事件就是 error。Session 已把 host-owned token+ // 盖到事件上,首个匹配 token 的事件即视为 provider accepted。+ if (typeof event.turnAttemptToken === 'number') {+ interruptedTurnAutoResumeGuard.noteAttemptEvent(session.id, event.turnAttemptToken);+ }+ let attributedEvent = event;+ if (event.type === 'error' && isTerminalTurnErrorEvent(event)) {+ const reason =+ !session.remoteHostId && session.agentKind === 'claude-code'+ ? consumeClaudeOpusPlanMismatch(session.id)+ : null;+ if (reason) {+ const eventData =+ event.data && typeof event.data === 'object' && !Array.isArray(event.data)+ ? (event.data as Record<string, unknown>)+ : {};+ attributedEvent = {+ ...event,+ data: { ...eventData, reason },+ };+ log.warn('Claude Opus plan error normalized for renderer', {+ sessionId: session.id,+ model: session.model,+ reason,+ });+ }+ }+ const broadcastEvent = redactEventForRenderer(attributedEvent);+ if (event.type === 'interaction_dismissed') {+ const data = event.data as { requestId?: unknown; reason?: unknown };+ if (typeof data.requestId === 'string') {+ handleAgentIslandInteractionDismissed(session.id, data.requestId);+ const entry = clearPendingInteraction(data.requestId);+ if (entry) {+ entry.resolve(+ defaultDecisionForPending(+ entry.kind,+ typeof data.reason === 'string' ? data.reason : 'dismissed',+ ),+ );+ }+ }+ broadcastToAllWindows(MAKER_PUSH.INTERACTION_DISMISSED, {sessionId: session.id,- model: session.model,- reason,+ ...(event.data as object),});+ return;}- }- const broadcastEvent = redactEventForRenderer(attributedEvent);- if (event.type === 'interaction_dismissed') {- const data = event.data as { requestId?: unknown; reason?: unknown };- if (typeof data.requestId === 'string') {- handleAgentIslandInteractionDismissed(session.id, data.requestId);- const entry = clearPendingInteraction(data.requestId);- if (entry) {- entry.resolve(defaultDecisionForPending(- entry.kind,- typeof data.reason === 'string' ? data.reason : 'dismissed',- ));- }+ if (event.type === 'image' && event.source === 'codex') {+ void broadcastCodexImageAsToolResult(session.id, event);+ return;}- broadcastToAllWindows(MAKER_PUSH.INTERACTION_DISMISSED, { sessionId: session.id, ...(event.data as object) });- return;- }- if (event.type === 'image' && event.source === 'codex') {- void broadcastCodexImageAsToolResult(session.id, event);- return;- }- if (event.type === 'plan_mode_changed') {- // agent 自行切换计划模式(典型: 计划批准后自动退出)。main 是持久化收口点:- // 复用 persistSessionFields 回写 sessions.plan_mode_enabled 并广播- // sessions:patched, 本机窗口与 device-link 控制端镜像同步收敛。- const data = event.data as { enabled?: unknown };- if (typeof data?.enabled === 'boolean') {- void persistSessionFields(session.id, { planModeEnabled: data.enabled }).catch((err) => {- log.warn('persist plan_mode_changed failed', {- sessionId: session.id,- error: err instanceof Error ? err.message : String(err),+ if (event.type === 'plan_mode_changed') {+ // agent 自行切换计划模式(典型: 计划批准后自动退出)。main 是持久化收口点:+ // 复用 persistSessionFields 回写 sessions.plan_mode_enabled 并广播+ // sessions:patched, 本机窗口与 device-link 控制端镜像同步收敛。+ const data = event.data as { enabled?: unknown };+ if (typeof data?.enabled === 'boolean') {+ void persistSessionFields(session.id, { planModeEnabled: data.enabled }).catch((err) => {+ log.warn('persist plan_mode_changed failed', {+ sessionId: session.id,+ error: err instanceof Error ? err.message : String(err),+ });});- });+ }+ return;}- return;- }- // turn 结束的 status event (isRunning=false + status='Done') 携带 endSnapshot。- // contextTokens / contextWindow 的持久化统一在 main 端做,避免多 window 竞写;- // 但不能挡在 EVENT broadcast 前面,否则 final/done 已到 main 后还会被同步 SQLite- // 和 usage 广播拖住。这里先记录待写快照,广播后再执行。- // Claude / Codex 同形 (usageTracker.snapshot() 两边都给 contextTokens / contextWindow),- // 不按 source 分支 —— 之前漏接 codex 导致重启后圆环归零。- let pendingContextSnapshot: { contextTokens: number; contextWindow: number } | null = null;- let pendingCodexAccountUsageSnapshot: unknown | null = null;- let shouldMarkTurnStatusIdleAfterBroadcast = false;- let shouldMarkTurnTerminalIdleAfterBroadcast = false;- if (event.type === 'account_usage' && event.source === 'codex' && !session.remoteHostId) {- pendingCodexAccountUsageSnapshot = event.data;- }- if (event.type === 'status') {- const data = event.data as {- isRunning?: boolean;- status?: string;- contextTokens?: number;- contextWindow?: number;- };- if (data.isRunning === true) {- // replacement 已进入 vendor 后,running 是新 attempt 的权威起点。不要依赖- // sendToAgent 返回后的 onDispatched 回调:provider 可同步发事件并先清 activeTurn。- autoResumeBookkeeping.discardReplacementProvenByProviderEvent(session.id);- // 新 turn 启动: 上一轮未配对的失败记账交接 id 已无归属, 丢弃防错配。- pendingFailedTurnAssistantPersistId.delete(session.id);- // 记录 turn 开始时刻,供 onTurnErrorEvent 判断 error 是否属于 /clear 之前的旧 turn。- noteTurnStarted(session.id);- // silent-stop 守卫:新 turn 开始 → 清 pendingResume + 记录时刻(陈旧判定)。- silentStopAutoResumeGuard.noteTurnStarted(session.id);- interruptedTurnAutoResumeGuard.noteTurnStarted(session.id, {- // A tokenless status(true) can be a delayed tail from the failed turn. It- // must not consume the pending token of the next scheduled auto-resume.- clearPending: typeof event.turnAttemptToken === 'number',- });- const wasInTurn = sessionTurnActivityTracker.isSessionInTurn(session.id);- sessionTurnActivityTracker.setSessionInTurn(session.id, data.isRunning);- if (!wasInTurn) advanceSessionTurnBoundaryGeneration(session.id);- // 后台活动检测:turn 开始 → 该会话的 API 流量回归主线,后台横幅熄灭。- noteClaudeSessionTurnState(session.id, true);- if (!wasInTurn) {- if (!gitSnapshotCoordinator?.hasPendingTurnStart(session.id)) {- void gitSnapshotCoordinator?.onTurnStart(session.id);- }- workerTurnStartSequencer.start(session.id, async () => {- await orcaTeamServiceForEvents?.handleWorkerTurnStarted(session.id);+ // turn 结束的 status event (isRunning=false + status='Done') 携带 endSnapshot。+ // contextTokens / contextWindow 的持久化统一在 main 端做,避免多 window 竞写;+ // 但不能挡在 EVENT broadcast 前面,否则 final/done 已到 main 后还会被同步 SQLite+ // 和 usage 广播拖住。这里先记录待写快照,广播后再执行。+ // Claude / Codex 同形 (usageTracker.snapshot() 两边都给 contextTokens / contextWindow),+ // 不按 source 分支 —— 之前漏接 codex 导致重启后圆环归零。+ let pendingContextSnapshot: { contextTokens: number; contextWindow: number } | null = null;+ let pendingCodexAccountUsageSnapshot: unknown | null = null;+ let shouldMarkTurnStatusIdleAfterBroadcast = false;+ let shouldMarkTurnTerminalIdleAfterBroadcast = false;+ if (event.type === 'account_usage' && event.source === 'codex' && !session.remoteHostId) {+ pendingCodexAccountUsageSnapshot = event.data;+ }+ if (event.type === 'status') {+ const data = event.data as {+ isRunning?: boolean;+ status?: string;+ contextTokens?: number;+ contextWindow?: number;+ };+ if (data.isRunning === true) {+ // replacement 已进入 vendor 后,running 是新 attempt 的权威起点。不要依赖+ // sendToAgent 返回后的 onDispatched 回调:provider 可同步发事件并先清 activeTurn。+ autoResumeBookkeeping.discardReplacementProvenByProviderEvent(session.id);+ // 新 turn 启动: 上一轮未配对的失败记账交接 id 已无归属, 丢弃防错配。+ pendingFailedTurnAssistantPersistId.delete(session.id);+ // 记录 turn 开始时刻,供 onTurnErrorEvent 判断 error 是否属于 /clear 之前的旧 turn。+ noteTurnStarted(session.id);+ // silent-stop 守卫:新 turn 开始 → 清 pendingResume + 记录时刻(陈旧判定)。+ silentStopAutoResumeGuard.noteTurnStarted(session.id);+ interruptedTurnAutoResumeGuard.noteTurnStarted(session.id, {+ // A tokenless status(true) can be a delayed tail from the failed turn. It+ // must not consume the pending token of the next scheduled auto-resume.+ clearPending: typeof event.turnAttemptToken === 'number',});- // interrupted-turn-resume:记录 turn 启动时刻,与正常收尾时刻配对做- // 「疑似中断」纯读判定(设计总述见 localDb/sessionActiveTurn.ts 文件头)。- // SSH remote 会话同样记录:session 行在本地 DB、事件流走本进程,只是- // agent 跑在远端;device-link 被控会话不进本进程 maker-core,天然不经过。- markSessionTurnStarted(session.id);+ const wasInTurn = sessionTurnActivityTracker.isSessionInTurn(session.id);+ sessionTurnActivityTracker.setSessionInTurn(session.id, data.isRunning);+ if (!wasInTurn) advanceSessionTurnBoundaryGeneration(session.id);+ // 后台活动检测:turn 开始 → 该会话的 API 流量回归主线,后台横幅熄灭。+ noteClaudeSessionTurnState(session.id, true);+ if (!wasInTurn) {+ if (!gitSnapshotCoordinator?.hasPendingTurnStart(session.id)) {+ void gitSnapshotCoordinator?.onTurnStart(session.id);+ }+ workerTurnStartSequencer.start(session.id, async () => {+ await orcaTeamServiceForEvents?.handleWorkerTurnStarted(session.id);+ });+ // interrupted-turn-resume:记录 turn 启动时刻,与正常收尾时刻配对做+ // 「疑似中断」纯读判定(设计总述见 localDb/sessionActiveTurn.ts 文件头)。+ // SSH remote 会话同样记录:session 行在本地 DB、事件流走本进程,只是+ // agent 跑在远端;device-link 被控会话不进本进程 maker-core,天然不经过。+ markSessionTurnStarted(session.id);+ }+ if (+ (event.source === 'claude-code' || event.source === 'codex' || event.source === 'pi') &&+ !turnModelPromiseBySession.has(session.id)+ ) {+ turnModelPromiseBySession.set(session.id, readSessionModelForUsage(session.id));+ }+ } else if (data.isRunning === false) {+ shouldMarkTurnStatusIdleAfterBroadcast = true;}if (- (event.source === 'claude-code' || event.source === 'codex' || event.source === 'pi')- && !turnModelPromiseBySession.has(session.id)+ data.isRunning === false &&+ data.status === 'Done' &&+ typeof data.contextTokens === 'number') {- turnModelPromiseBySession.set(session.id, readSessionModelForUsage(session.id));+ pendingContextSnapshot = {+ contextTokens: data.contextTokens,+ contextWindow: data.contextWindow ?? 0,+ };}- } else if (data.isRunning === false) {- shouldMarkTurnStatusIdleAfterBroadcast = true;}- if (data.isRunning === false && data.status === 'Done' && typeof data.contextTokens === 'number') {- pendingContextSnapshot = {- contextTokens: data.contextTokens,- contextWindow: data.contextWindow ?? 0,- };+ if (event.type === 'done') {+ // turn 正常收尾但一路没有实质产出时,上一条重连记录同样不能停在"结果未回填":+ // 成功路径已在产出事件里 settle 成 succeeded(此处 no-op),走到这里就是没产出。+ const doneAttemptToken = event.turnAttemptToken;+ if (typeof doneAttemptToken === 'number') {+ autoResumeBookkeeping.settleOutcome(session.id, doneAttemptToken, 'failed');+ interruptedTurnAutoResumeGuard.noteAttemptSettled(session.id, doneAttemptToken);+ }+ const isSilentStopDone =+ (event.data as { silentStop?: boolean } | null | undefined)?.silentStop === true;+ // silent-stop done:自动续跑会在 1.5s 后启动新 turn(或弹耗尽横幅),+ // 不标 idle/不触发 goal idle/不通知 coordinator done——避免 renderer+ // 在 500ms 完成去抖窗口内显示假完成通知,下一个 turn 开始后又跳回 running。+ if (!isSilentStopDone) {+ // 兜底: 有些 vendor 的 done 不必先发 status:isRunning=false。+ // 但 idle 恢复不能挡在 EVENT broadcast 前,否则隐藏窗口可能在 done+ // 还没进入 renderer 时就重新被 Chromium 节流。+ shouldMarkTurnTerminalIdleAfterBroadcast = true;+ agentInputCoordinatorHolder?.onTurnEvent(session.id, 'done');+ // #9 idle 兜底:turn 收尾后让 goal controller 决定是否补一轮(无 goal/非 active 时 no-op)。+ goalIdleObserver?.(session.id);+ } else {+ // silent-stop 自动续跑:translator 判定本 turn 被上游空内容消息静默收尾时在+ // done.data 附加 silentStop 标记(见 maker-core translator)。延迟一拍再决策,+ // 让本次 turn-end 的落库/收口先走完,也给"用户恰好自己发了消息"留出让位窗口+ //(守卫内部还有 doneAt 陈旧判定,双保险,绝不插队)。+ // 回拨 in-turn 状态:translator 在 done 之前推了 status(isRunning=false),+ // 那条事件已经把 tracker 标成 idle。恢复 in-turn 让 renderer 在 1.5s 决策+ // 窗口内不触发 500ms 完成去抖的假通知。settleSilentStopDone / 新 turn 的+ // noteTurnStarted 会再正确设置最终状态。+ sessionTurnActivityTracker.setSessionInTurn(session.id, true);+ // 后台活动检测:silent-stop 决策窗内逻辑 turn 仍在继续,同步回拨。+ noteClaudeSessionTurnState(session.id, true);+ const silentStopDoneAt = Date.now();+ const silentStopTurnOrigin = event.turnOrigin;+ setTimeout(() => {+ void handleSilentStopTurnEnd(session, silentStopDoneAt, silentStopTurnOrigin);+ }, 1_500);+ }}- }- if (event.type === 'done') {- // turn 正常收尾但一路没有实质产出时,上一条重连记录同样不能停在"结果未回填":- // 成功路径已在产出事件里 settle 成 succeeded(此处 no-op),走到这里就是没产出。- const doneAttemptToken = event.turnAttemptToken;- if (typeof doneAttemptToken === 'number') {- autoResumeBookkeeping.settleOutcome(session.id, doneAttemptToken, 'failed');- interruptedTurnAutoResumeGuard.noteAttemptSettled(session.id, doneAttemptToken);- }- const isSilentStopDone = (event.data as { silentStop?: boolean } | null | undefined)?.silentStop === true;- // silent-stop done:自动续跑会在 1.5s 后启动新 turn(或弹耗尽横幅),- // 不标 idle/不触发 goal idle/不通知 coordinator done——避免 renderer- // 在 500ms 完成去抖窗口内显示假完成通知,下一个 turn 开始后又跳回 running。- if (!isSilentStopDone) {- // 兜底: 有些 vendor 的 done 不必先发 status:isRunning=false。- // 但 idle 恢复不能挡在 EVENT broadcast 前,否则隐藏窗口可能在 done- // 还没进入 renderer 时就重新被 Chromium 节流。+ // 提前声明在终止型 error 块与 done/terminal 边界块两处均需使用的持久化条件标志。+ let isPlannedUpgradeClose = false;+ let isRemoteAuthRetry = false;+ if (isTerminalTurnErrorEvent(event)) {+ // **任何**终态失败都先把上一条重连记录钉成失败 —— 不管这次错误本身是否值得自愈。+ // 只在"命中白名单、准备再接管"时才 settle 的话,非白名单的终态(认证 / 计费 /+ // invalid-request)会让记录悬空,随后一个无关 turn 的首个产出事件就把它标成+ // 「已重新连接」(codex P1)。+ const failedAttemptToken = event.turnAttemptToken;+ if (typeof failedAttemptToken === 'number') {+ autoResumeBookkeeping.settleOutcome(session.id, failedAttemptToken, 'failed');+ interruptedTurnAutoResumeGuard.noteAttemptSettled(session.id, failedAttemptToken);+ }+ // 终止型 error 可能没有后续 status/done(SDK/event loop crash 等),需要在+ // EVENT broadcast 后结束逻辑 turn,并保留 terminal grace 给 renderer 收尾;+ // 可重试 error 保持 running。shouldMarkTurnTerminalIdleAfterBroadcast = true;- agentInputCoordinatorHolder?.onTurnEvent(session.id, 'done');- // #9 idle 兜底:turn 收尾后让 goal controller 决定是否补一轮(无 goal/非 active 时 no-op)。- goalIdleObserver?.(session.id);- } else {- // silent-stop 自动续跑:translator 判定本 turn 被上游空内容消息静默收尾时在- // done.data 附加 silentStop 标记(见 maker-core translator)。延迟一拍再决策,- // 让本次 turn-end 的落库/收口先走完,也给"用户恰好自己发了消息"留出让位窗口- //(守卫内部还有 doneAt 陈旧判定,双保险,绝不插队)。- // 回拨 in-turn 状态:translator 在 done 之前推了 status(isRunning=false),- // 那条事件已经把 tracker 标成 idle。恢复 in-turn 让 renderer 在 1.5s 决策- // 窗口内不触发 500ms 完成去抖的假通知。settleSilentStopDone / 新 turn 的- // noteTurnStarted 会再正确设置最终状态。- sessionTurnActivityTracker.setSessionInTurn(session.id, true);- // 后台活动检测:silent-stop 决策窗内逻辑 turn 仍在继续,同步回拨。- noteClaudeSessionTurnState(session.id, true);- const silentStopDoneAt = Date.now();- const silentStopTurnOrigin = event.turnOrigin;- setTimeout(() => {- void handleSilentStopTurnEnd(session, silentStopDoneAt, silentStopTurnOrigin);- }, 1_500);- }- }- // 提前声明在终止型 error 块与 done/terminal 边界块两处均需使用的持久化条件标志。- let isPlannedUpgradeClose = false;- let isRemoteAuthRetry = false;- if (isTerminalTurnErrorEvent(event)) {- // **任何**终态失败都先把上一条重连记录钉成失败 —— 不管这次错误本身是否值得自愈。- // 只在"命中白名单、准备再接管"时才 settle 的话,非白名单的终态(认证 / 计费 /- // invalid-request)会让记录悬空,随后一个无关 turn 的首个产出事件就把它标成- // 「已重新连接」(codex P1)。- const failedAttemptToken = event.turnAttemptToken;- if (typeof failedAttemptToken === 'number') {- autoResumeBookkeeping.settleOutcome(session.id, failedAttemptToken, 'failed');- interruptedTurnAutoResumeGuard.noteAttemptSettled(session.id, failedAttemptToken);- }- // 终止型 error 可能没有后续 status/done(SDK/event loop crash 等),需要在- // EVENT broadcast 后结束逻辑 turn,并保留 terminal grace 给 renderer 收尾;- // 可重试 error 保持 running。- shouldMarkTurnTerminalIdleAfterBroadcast = true;- if (event.source === 'claude-code' || event.source === 'codex' || event.source === 'pi') {- turnModelPromiseBySession.delete(session.id);+ if (event.source === 'claude-code' || event.source === 'codex' || event.source === 'pi') {+ turnModelPromiseBySession.delete(session.id);+ }+ const errData =+ attributedEvent.type === 'error'+ ? (attributedEvent.data as+ | { message?: unknown; reason?: unknown; sdkError?: unknown; errorStatus?: unknown }+ | undefined)+ : undefined;+ // 计划内 cc-mgr 升级窗口的 daemon 关闭(reason='remote_daemon_closed')是+ // 预期噪音: renderer 事件路径按同语义静默 banner, 这里同样不给 coordinator+ // 记 error —— 否则 paired-done 保留会让升级后的 projection 复现+ // [REMOTE_DAEMON_CLOSED] banner。范围与 renderer 一致**按 session**(仅+ // banner-clicker):同 host 其它会话的中断照真实失败浮现;窗口外的 daemon+ // 死亡同样不受影响(保留 + 通知)。+ isPlannedUpgradeClose =+ errData?.reason === 'remote_daemon_closed' && isCcMgrUpgradeInFlight(session.id);+ // Legacy CC/XD 远程 auth 错误跳过持久化:renderer 会静默 auto-retry(makerChatStore 在 reducer+ // 前拦截、关闭旧会话、重发消息,不显示 ErrorBanner);若 main 已落库,retry 成功后+ // 重开会话会看到虚假错误卡。判定与 renderer 的 isAuthError 保持一致,覆盖+ // sdkError === 'authentication_failed' 以及 message 命中 authentication_error /+ // invalid api key / 401 的情形。本地会话(无 remoteHostId)无 auto-retry,不跳过。+ isRemoteAuthRetry = isRemoteAuthRetryErrorEvent(session, event);+ if (!isPlannedUpgradeClose) {+ agentInputCoordinatorHolder?.onTurnEvent(+ session.id,+ 'error',+ typeof broadcastEvent.data === 'object' &&+ broadcastEvent.data !== null &&+ typeof (broadcastEvent.data as { message?: unknown }).message === 'string'+ ? (broadcastEvent.data as { message: string }).message+ : undefined,+ // 结构化信号:自动续跑的判据靠它们收紧(见 isInterruptedTurnError),不靠文本猜。+ {+ ...(typeof errData?.sdkError === 'string' ? { sdkError: errData.sdkError } : {}),+ ...(typeof errData?.reason === 'string' ? { reason: errData.reason } : {}),+ ...(typeof errData?.errorStatus === 'number'+ ? { errorStatus: errData.errorStatus }+ : {}),+ },+ );+ }}- const errData = attributedEvent.type === 'error'- ? (attributedEvent.data as- | { message?: unknown; reason?: unknown; sdkError?: unknown; errorStatus?: unknown }- | undefined)- : undefined;- // 计划内 cc-mgr 升级窗口的 daemon 关闭(reason='remote_daemon_closed')是- // 预期噪音: renderer 事件路径按同语义静默 banner, 这里同样不给 coordinator- // 记 error —— 否则 paired-done 保留会让升级后的 projection 复现- // [REMOTE_DAEMON_CLOSED] banner。范围与 renderer 一致**按 session**(仅- // banner-clicker):同 host 其它会话的中断照真实失败浮现;窗口外的 daemon- // 死亡同样不受影响(保留 + 通知)。- isPlannedUpgradeClose =- errData?.reason === 'remote_daemon_closed' &&- isCcMgrUpgradeInFlight(session.id);- // Legacy CC/XD 远程 auth 错误跳过持久化:renderer 会静默 auto-retry(makerChatStore 在 reducer- // 前拦截、关闭旧会话、重发消息,不显示 ErrorBanner);若 main 已落库,retry 成功后- // 重开会话会看到虚假错误卡。判定与 renderer 的 isAuthError 保持一致,覆盖- // sdkError === 'authentication_failed' 以及 message 命中 authentication_error /- // invalid api key / 401 的情形。本地会话(无 remoteHostId)无 auto-retry,不跳过。- isRemoteAuthRetry = isRemoteAuthRetryErrorEvent(session, event);- if (!isPlannedUpgradeClose) {- agentInputCoordinatorHolder?.onTurnEvent(+ // F1-a Phase 2: assistant 文本持久化收口 main 单点(根除多窗各落一份的重复)。+ // 在 onEvent 同步路径只做 O(1):为在飞 assistant 分配 / 复用 persistId、累积全文,+ // 把 persistId 盖进广播 payload 让 renderer 在途气泡用同一 id;真正落库走模块内+ // 异步队列、不在此同步执行(规则19 热路径)。其它消息类型的 persistId 暂为+ // undefined,renderer 继续走原逻辑(后续 Phase 收口 tool_use / tool_result 等)。+ const eventAgentMeta = (event as { agentMeta?: AgentMeta | null }).agentMeta ?? null;+ // 跟踪会话最近一次非空 agentMeta(镜像 renderer state.lastAgentMeta),给 interaction+ // 边界 flush 当兜底锚点,保 agent_meta 不丢(rewind/fork)。+ if (eventAgentMeta) noteAgentMeta(session.id, eventAgentMeta);+ let persistId: string | undefined;+ // tool_result 家族:main 解析出的权威内容,盖进 payload 让 renderer 即时显示+ // (Option C:内容重排状态机只在 main 一份,与落库同源同值)。+ let resolvedContent: string | undefined;+ // 中断自愈的额度判据是「是否在推进」:模型产出了实质内容(文本 / 工具调用)就把+ // 连续失败计数归零;人工介入周期的硬总上限不归零,保证始终有限。+ // 刻意只认这两类事件:thinking / status / 空消息都不算产出;guard 侧是 O(1)、+ // 无 IO、无日志,放在热路径安全。+ if (isSubstantiveProgressEvent(event)) {+ const progressAttemptToken = event.turnAttemptToken;+ const accepted = interruptedTurnAutoResumeGuard.noteProgress(session.id,- 'error',- typeof broadcastEvent.data === 'object' &&- broadcastEvent.data !== null &&- typeof (broadcastEvent.data as { message?: unknown }).message === 'string'- ? (broadcastEvent.data as { message: string }).message- : undefined,- // 结构化信号:自动续跑的判据靠它们收紧(见 isInterruptedTurnError),不靠文本猜。- {- ...(typeof errData?.sdkError === 'string' ? { sdkError: errData.sdkError } : {}),- ...(typeof errData?.reason === 'string' ? { reason: errData.reason } : {}),- ...(typeof errData?.errorStatus === 'number'- ? { errorStatus: errData.errorStatus }- : {}),- },+ progressAttemptToken ?? undefined,);+ // 同一个信号也是「上一次重连真的成功了」的唯一证据;旧 attempt 的迟到事件+ // token 不匹配时不会结算当前新 attempt。+ if (accepted && typeof progressAttemptToken === 'number') {+ autoResumeBookkeeping.settleOutcome(session.id, progressAttemptToken, 'succeeded');+ }}- }- // F1-a Phase 2: assistant 文本持久化收口 main 单点(根除多窗各落一份的重复)。- // 在 onEvent 同步路径只做 O(1):为在飞 assistant 分配 / 复用 persistId、累积全文,- // 把 persistId 盖进广播 payload 让 renderer 在途气泡用同一 id;真正落库走模块内- // 异步队列、不在此同步执行(规则19 热路径)。其它消息类型的 persistId 暂为- // undefined,renderer 继续走原逻辑(后续 Phase 收口 tool_use / tool_result 等)。- const eventAgentMeta = (event as { agentMeta?: AgentMeta | null }).agentMeta ?? null;- // 跟踪会话最近一次非空 agentMeta(镜像 renderer state.lastAgentMeta),给 interaction- // 边界 flush 当兜底锚点,保 agent_meta 不丢(rewind/fork)。- if (eventAgentMeta) noteAgentMeta(session.id, eventAgentMeta);- let persistId: string | undefined;- // tool_result 家族:main 解析出的权威内容,盖进 payload 让 renderer 即时显示- // (Option C:内容重排状态机只在 main 一份,与落库同源同值)。- let resolvedContent: string | undefined;- // 中断自愈的额度判据是「是否在推进」:模型产出了实质内容(文本 / 工具调用)就把- // 连续失败计数归零;人工介入周期的硬总上限不归零,保证始终有限。- // 刻意只认这两类事件:thinking / status / 空消息都不算产出;guard 侧是 O(1)、- // 无 IO、无日志,放在热路径安全。- if (isSubstantiveProgressEvent(event)) {- const progressAttemptToken = event.turnAttemptToken;- const accepted = interruptedTurnAutoResumeGuard.noteProgress(- session.id,- progressAttemptToken ?? undefined,- );- // 同一个信号也是「上一次重连真的成功了」的唯一证据;旧 attempt 的迟到事件- // token 不匹配时不会结算当前新 attempt。- if (accepted && typeof progressAttemptToken === 'number') {- autoResumeBookkeeping.settleOutcome(+ if (event.type === 'text') {+ const td = event.data as { text?: unknown; isFinal?: unknown } | null;+ if (typeof td?.text === 'string') {+ orcaTeamServiceForEvents?.captureWorkerText(session.id, td.text, {+ isFinal: td.isFinal === true,+ });+ }+ persistId = onAssistantTextEvent(session.id,- progressAttemptToken,- 'succeeded',+ event.data as { text?: unknown; isFinal?: unknown },+ eventAgentMeta,);- }- }- if (event.type === 'text') {- const td = event.data as { text?: unknown; isFinal?: unknown } | null;- if (typeof td?.text === 'string') {- orcaTeamServiceForEvents?.captureWorkerText(session.id, td.text, {- isFinal: td.isFinal === true,- });- }- persistId = onAssistantTextEvent(- session.id,- event.data as { text?: unknown; isFinal?: unknown },- eventAgentMeta,- );- } else if (event.type === 'tool_use') {- // tool_use 边界:先 flush 在飞 assistant(保证 assistant 行先于其 tool_use 入队- // 落库),再落 tool_use 本身,拿回 persistId 盖进 payload。两者都只入队、不阻塞。- flushAssistantBlock(session.id, eventAgentMeta);- persistId = onToolUseEvent(- session.id,- event.data as { toolUseId?: unknown; toolName?: unknown; input?: unknown },- eventAgentMeta,- );- } else if (event.type === 'tool_result') {- const r = onToolResultEvent(- session.id,- event.data as { summary?: unknown; toolUseIds?: unknown },- eventAgentMeta,- );- persistId = r?.persistId;- resolvedContent = r?.content;- } else if (event.type === 'tool_result_full') {- const r = onToolResultFullEvent(- session.id,- event.data as { toolUseId?: unknown; fullText?: unknown },- eventAgentMeta,- );- persistId = r?.persistId;- resolvedContent = r?.content;- } else if (event.type === 'thinking') {- // thinking final/redacted 落库收口 main;clientId=blockId(renderer 同源),无需- // persistId 回传。start/delta 不落库。- onThinkingEvent(- session.id,- event.data as { stage?: unknown; blockId?: unknown; text?: unknown; durationMs?: unknown },- eventAgentMeta,- );- }- // 先 broadcast 保 UI 实时性,再 flush(flush 只入队、不阻塞)。- // Keep the raw event for main-side coordination/persistence, but only- // cross renderer/device-link boundaries with the redacted copy.- broadcastToAllWindows(MAKER_PUSH.EVENT, {- sessionId: session.id,- event: broadcastEvent,- persistId,- resolvedContent,- });- handleAgentIslandEventAfterBroadcast(session, broadcastEvent);- if (shouldMarkTurnTerminalIdleAfterBroadcast) {- sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(session.id);- // 后台活动检测:done / 终止型 error = 逻辑 turn 结束,记录结束时刻。- // 此后若该会话进程仍有 API 流量(后台子 agent),record 路径会点亮横幅。- noteClaudeSessionTurnState(session.id, false);- // turn 收尾打标(last_turn_ended_at)不在此处:done / terminal error 的本 turn- // 持久化(assistant flush / orphan tool_result / error 行)在下方 flush 块才- // 入队,统一在那之后走 markTurnEndedAfterPersistDrain(见该 helper 注释)。- // turn 边界(done / 终止型 error):必须在 tracker 标 idle **之后**再兑现本会话的- // 延迟凭证切换、唤醒被本会话挡住的等待者 —— vendor 可能不发前置 status:false,- // 提前唤醒会让 apply/重试读到 isSessionInTurn=true 而空转,退化到 10s 兜底- // (review P2 2026-07-04)。apply 内部串行 + 幂等,fire-and-forget 安全;- // planned upgrade close 等场景多唤一次也只是 no-op。- settlePendingCredentialSwitch(session.id, `event:${event.type}`);- deferredCodexRestartHolder?.onSessionSettled();- agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);- refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);- } else if (shouldMarkTurnStatusIdleAfterBroadcast) {- sessionTurnActivityTracker.scheduleIdleAfterStatusBroadcast(session.id);- // status:isRunning=false 即逻辑 turn 结束(可重试 error 不发这个信号)。- markTurnEndedAfterPersistDrain(session.id);- noteClaudeSessionTurnState(session.id, false);- }- if (event.type === 'done') {- void gitSnapshotCoordinator?.onTurnEnd(session.id);- }- if (isTerminalTurnErrorEvent(event)) {- gitSnapshotCoordinator?.onTurnAbort(session.id);- }- // done / 终止型 error 持久化边界:把在飞 assistant 落库(与 text isFinal 互斥幂等)。- // tool_use 边界的 flush 已在上面 broadcast 前做(需先于 tool_use 落库);- // ask_user / plan_review / permission 不走 onEvent(走 interaction listener),- // 它们的 flush 在 setInteractionListener 里。- //- // 可重试 error 仍属于同一 turn,不能 reset lastAgentMeta / tool_result 配对状态;- // 否则未来出现 turn 中途的非终止型 error 时会打断后续 tool_result 关联。- // 本 turn 最后一条 assistant 的 persistId(挂 per-turn 费用 / turn 边界用)。terminal- // error 同样 consume,写失败 seal 后再按需交接给 paired done;纯 tool 轮为 undefined。- let turnAssistantPersistId: string | undefined;- let turnBoundaryAssistantPersistId: string | undefined;- let isPairedFailedTurnDone = false;- if (event.type === 'done' || isTerminalTurnErrorEvent(event)) {- flushAssistantBlock(session.id, eventAgentMeta);- turnAssistantPersistId = consumeLastAssistantPersistId(session.id);- turnBoundaryAssistantPersistId = consumeLastTopLevelAssistantPersistId(session.id);- if (isTerminalTurnErrorEvent(event) && event.type !== 'done') {- // 失败 turn: 记账发生在稍后的配对 done(usage 在那条事件上), 把这里- // consume 到的 persistId 交接过去(见 pendingFailedTurnAssistantPersistId)。- if (turnAssistantPersistId) {- pendingFailedTurnAssistantPersistId.set(session.id, turnAssistantPersistId);- }- } else {- // done: 优先本事件 consume 的 id, 失败 turn 场景回收交接的 id;- // 无论用没用到都清掉, 防残留错配下一轮。- const pendingFailedPersistId = pendingFailedTurnAssistantPersistId.get(session.id);- if (!turnAssistantPersistId && pendingFailedPersistId) {- turnAssistantPersistId = pendingFailedPersistId;- isPairedFailedTurnDone = true;- }- pendingFailedTurnAssistantPersistId.delete(session.id);- }- flushOrphanToolResults(session.id, eventAgentMeta);- if (turnBoundaryAssistantPersistId) {- // 在同一 durable FIFO 内先盖 turn seal、再复用 local-db:messages:created 广播- // 更新后的完整行。失败轮的 paired done 只复用 id 做 usage 记账,不能把- // terminal error 已写的 false seal 覆盖成 true、让施工播报重新进入标题素材。- if (event.type !== 'done') {- void markAssistantTurnFailed(session.id, turnBoundaryAssistantPersistId);- } else if (!isPairedFailedTurnDone) {- void markAssistantTurnCompleted(session.id, turnBoundaryAssistantPersistId);- }- }- // error 行在 flushOrphanToolResults 之后入队,保证 orphan tool_result 排在- // error 行之前(历史时间线:tool 输出 → 错误卡,而非错误卡插到 tool 输出之前)。- // 自愈接管中 → 压住 error 行:成功续跑时历史里只留一条「已自动继续」分隔条,- // 救不回来时由 AutoResumeBookkeeping.finalizeSuppressedError 补落。判据取 coordinator 的实时- // 接管态(而非 host 自己的 map):退避期间用户若自己发了消息,接管态已被清,那之后- // 新 turn 的失败必须照常落库。- //- // 还有一种时序:terminal error 早于用户气泡落库完成到达时,接管决策要推迟到- // settlePendingTerminalEventAfterPersist 才能做(recovery 留不留得住是前提)。那时- // error 行早就落库了、压不回去,接管成功后历史里会同时留下错误卡与重连行(codex P1)。- // 所以决策未定时也一并压住(isAutoResumeDeferred),由 coordinator 在三个「最终没接管」- // 的出口回调 onResumableTurnErrorDiscarded 让它补落。- const autoResumeSuppressesPersist =- event.type === 'error' &&- (agentInputCoordinatorHolder?.isAutoResumePending(session.id) === true ||- agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id) === true);- if (- event.type === 'error' &&- !isPlannedUpgradeClose &&- !isRemoteAuthRetry &&- !autoResumeSuppressesPersist- ) {- onTurnErrorEvent(+ } else if (event.type === 'tool_use') {+ // tool_use 边界:先 flush 在飞 assistant(保证 assistant 行先于其 tool_use 入队+ // 落库),再落 tool_use 本身,拿回 persistId 盖进 payload。两者都只入队、不阻塞。+ flushAssistantBlock(session.id, eventAgentMeta);+ persistId = onToolUseEvent(session.id,- attributedEvent.data as {- message?: unknown;- reason?: unknown;- sdkError?: unknown;- } | null,+ event.data as { toolUseId?: unknown; toolName?: unknown; input?: unknown },eventAgentMeta,);- }- // 压住的错误详情必须在这里存一份:决策推迟场景下 onResumableTurnError 还没被调用过- // (它自己那份 set 发生在接管成立时),不存就无从补落。同 clientId 内容,覆盖无害。- if (autoResumeSuppressesPersist) {- autoResumeBookkeeping.stashSuppressedError(+ } else if (event.type === 'tool_result') {+ const r = onToolResultEvent(+ session.id,+ event.data as { summary?: unknown; toolUseIds?: unknown },+ eventAgentMeta,+ );+ persistId = r?.persistId;+ resolvedContent = r?.content;+ } else if (event.type === 'tool_result_full') {+ const r = onToolResultFullEvent(+ session.id,+ event.data as { toolUseId?: unknown; fullText?: unknown },+ eventAgentMeta,+ );+ persistId = r?.persistId;+ resolvedContent = r?.content;+ } else if (event.type === 'thinking') {+ // thinking final/redacted 落库收口 main;clientId=blockId(renderer 同源),无需+ // persistId 回传。start/delta 不落库。+ onThinkingEvent(session.id,- attributedEvent.data,- agentInputCoordinatorHolder?.getAutoResumeAttemptToken(session.id) ?? null,- agentInputCoordinatorHolder?.getAutoResumeDeferredOwner(session.id) ?? null,+ event.data as {+ stage?: unknown;+ blockId?: unknown;+ text?: unknown;+ durationMs?: unknown;+ },+ eventAgentMeta,);- } else if (event.type === 'error' && isTerminalTurnErrorEvent(event)) {- // replacement 可在 sendToAgent 返回前同步失败并让 coordinator 的 activeTurn- // 失效;这个新终态已经取代旧中断,按 dispatch phase 直接清旧 owner。- autoResumeBookkeeping.discardReplacementProvenByProviderEvent(session.id);- }- // deferred 路径保存 turn 开始时刻:isRemoteAuthRetry 时 onTurnErrorEvent 被跳过,- // renderer 会稍后调 persistTurnErrorDeferred IPC。在 resetTurnPersistState 清掉- // _turnStartedAtBySession 之前保存一份,让 deferred 路径能正确做 /clear 竞态 cap。- // 自愈压住 error 行时同理:补落发生在 resetTurnPersistState 之后(退避 3–20 秒,- // 或决策推迟的那一小段),不先存一份会让 /clear 竞态 cap 判错。- if (event.type === 'error' && (isRemoteAuthRetry || autoResumeSuppressesPersist)) {- saveTurnStartedAtForDeferred(session.id);- }- // turn 收尾打标:本 turn 已知持久化(assistant flush / orphan tool_result /- // error 行)已全部入队,在此统一定格并等排空后写。done 与 terminal error- // 同一规则(planned upgrade close / remote auth retry 分支无 error 行,- // drain 同样无害)。- markTurnEndedAfterPersistDrain(session.id);- resetTurnPersistState(session.id);- // sidebar-card-mode: 摘要触发挪到本轮 assistant 块 flush 入队之后(原先在- // done 早段、flush 之前触发,流式轮次会读到上一轮文本)。只在正常 done 触发。- // codex review:flushAssistantBlock 仅把 assistant insert 入队 writeChain、未落库,- // latestMessageText 立刻读库可能读到本轮 assistant 写入之前的旧状态;先 await- // drainPersistQueue() 等持久化队列排空,确立"读在写后"的边界,再起摘要。+ }+ // 先 broadcast 保 UI 实时性,再 flush(flush 只入队、不阻塞)。+ // Keep the raw event for main-side coordination/persistence, but only+ // cross renderer/device-link boundaries with the redacted copy.+ broadcastToAllWindows(MAKER_PUSH.EVENT, {+ sessionId: session.id,+ event: broadcastEvent,+ persistId,+ resolvedContent,+ });+ handleAgentIslandEventAfterBroadcast(session, broadcastEvent);+ if (shouldMarkTurnTerminalIdleAfterBroadcast) {+ sessionTurnActivityTracker.scheduleIdleAfterTerminalBroadcast(session.id);+ // 后台活动检测:done / 终止型 error = 逻辑 turn 结束,记录结束时刻。+ // 此后若该会话进程仍有 API 流量(后台子 agent),record 路径会点亮横幅。+ noteClaudeSessionTurnState(session.id, false);+ // turn 收尾打标(last_turn_ended_at)不在此处:done / terminal error 的本 turn+ // 持久化(assistant flush / orphan tool_result / error 行)在下方 flush 块才+ // 入队,统一在那之后走 markTurnEndedAfterPersistDrain(见该 helper 注释)。+ // turn 边界(done / 终止型 error):必须在 tracker 标 idle **之后**再兑现本会话的+ // 延迟凭证切换、唤醒被本会话挡住的等待者 —— vendor 可能不发前置 status:false,+ // 提前唤醒会让 apply/重试读到 isSessionInTurn=true 而空转,退化到 10s 兜底+ // (review P2 2026-07-04)。apply 内部串行 + 幂等,fire-and-forget 安全;+ // planned upgrade close 等场景多唤一次也只是 no-op。+ settlePendingCredentialSwitch(session.id, `event:${event.type}`);+ deferredCodexRestartHolder?.onSessionSettled();+ agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);+ refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);+ } else if (shouldMarkTurnStatusIdleAfterBroadcast) {+ sessionTurnActivityTracker.scheduleIdleAfterStatusBroadcast(session.id);+ // status:isRunning=false 即逻辑 turn 结束(可重试 error 不发这个信号)。+ markTurnEndedAfterPersistDrain(session.id);+ noteClaudeSessionTurnState(session.id, false);+ }if (event.type === 'done') {- void (async () => {- await drainPersistQueue();- // force:turn-done 是权威刷新点(本轮 assistant 已落库),必须以最新内容覆盖- // 任何 pin 触发 / 上一轮残留的摘要——绕过 in-flight 早返与 20s 节流- // (codex review:pin during running turn 会让卡片停在部分/旧摘要)。- await maybeGenerateSessionTaskSummary(session.id, { force: true });- })();+ void gitSnapshotCoordinator?.onTurnEnd(session.id);}- // will-assistant-message 出口钩子(先定案 → 一拍后替换):仅 done(非终止- // error)、有真实回复文本 + 已落库的 assistant persistId + 有启用的出口钩子- // 意识时,派一个独立异步续跑跑裁决并原地更新那条消息(rewrite 换文本 /- // render 换自绘卡)。同步守卫 hasEnabledGhostAssistantHook 保证无此类意识时- // 不 schedule —— 与今天行为逐字节一致,零额外开销(规则 10 不碰热路径)。- if (event.type === 'done' && turnAssistantPersistId) {- const doneResult = (event.data as { result?: unknown } | null)?.result;- const replyText = typeof doneResult === 'string' ? doneResult : '';- if (replyText.length > 0 && hasEnabledGhostAssistantHook()) {- runGhostAssistantReplyHook(session.id, turnAssistantPersistId, replyText);- }+ if (isTerminalTurnErrorEvent(event)) {+ gitSnapshotCoordinator?.onTurnAbort(session.id);}- // Worker turn 结束后交给 OrcaTeamService 处理 DB status、广播与 auto-bridge。- void (async () => {- try {- const doneData = event.data as { result?: unknown } | null;- const finalText = typeof doneData?.result === 'string' && doneData.result.length > 0- ? doneData.result- : '';- await workerTurnStartSequencer.waitForStart(session.id);- await orcaTeamServiceForEvents?.handleWorkerTerminalTurn({- sessionId: session.id,- status: isTerminalTurnErrorEvent(event) ? 'error' : 'done',- finalText,- });- } catch { /* non-fatal */ }- })();- }- if (pendingContextSnapshot) {- recordSessionContextSnapshot(- session.id,- pendingContextSnapshot.contextTokens,- pendingContextSnapshot.contextWindow,- );- }- if (pendingCodexAccountUsageSnapshot) {- recordCodexAccountUsageSnapshot(pendingCodexAccountUsageSnapshot);- }- // 每 turn 结束累加 daily_spend 表 + 广播给 renderer 右下角"今日 $X.XX" chip。- // 这些统计 side effect 必须在 EVENT broadcast 之后,避免同步 SQLite 或额外- // usage 广播延后 final/done 送达。- //- // 本轮费用 = HYBRID 定价: Anthropic 模型信任 SDK 自报 cost (OAuth 下=0、API 下=真实、- // cache-correct), 非 Anthropic provider 模型 (gpt-5.5 等) 用远端 gateway 价 × token- // 重算 —— 修 SDK 把它们按 Anthropic 价错算 (~2.5x) 的 bug。逐模型解析后四个 sink- // (今日 / session / per-message / 按模型) 同源同值。- // 守卫: index.ts:388 stream_end fallback / codex done 不带 total_cost_usd, typeof 检查会跳过。- if (event.type === 'done' && event.source === 'claude-code') {- const modelPromise = turnModelPromiseBySession.get(session.id) ?? readSessionModelForUsage(session.id);- turnModelPromiseBySession.delete(session.id);- const doneData = event.data as {- total_cost_usd?: unknown;- usage?: {- input_tokens?: number;- output_tokens?: number;- cache_read_input_tokens?: number;- cache_creation_input_tokens?: number;- };- modelUsage?: Record<string, unknown>;- } | undefined;- const cumulative = doneData?.total_cost_usd;- const modelUsage = doneData?.modelUsage;- let modelUsageDeltas: ModelUsageDeltaEntry[] | undefined;- if (modelUsage && typeof modelUsage === 'object') {- const { next, deltas } = computeModelUsageDeltas(- lastReportedModelUsageBySession.get(session.id),- modelUsage,- );- lastReportedModelUsageBySession.set(session.id, next);- modelUsageDeltas = deltas;- }- // total_cost_usd 累计基线: 主路径不靠它算钱, 但仍跟住, 以便万一某轮缺 modelUsage- // 走兜底时累计差才准。先取"更新前"基线给兜底用, 再写入本轮累计。- const prevReportedCost = lastReportedCostUsdBySession.get(session.id) ?? 0;- if (typeof cumulative === 'number' && cumulative >= 0) {- lastReportedCostUsdBySession.set(session.id, cumulative);- }- // 模型降级检测:所选模型(turn start 快照)整轮缺席于实际 modelUsage delta →- // 判定主线被上游静默替换(如 fable-5 高负载被路由到 opus-4-8),把标记挂到本轮- // 收尾 assistant 的 agent_meta 上(AssistantMessage 渲染降级提示行)。- // fire-and-forget,与记账 sink 互不阻塞;判定纯函数见 shared/modelMismatch.ts。- if (modelUsageDeltas && detectOutputLag(modelUsageDeltas)) {- // 上游在 done 时点还没结算本轮输出(实测 Vertex),这一轮的费用会偏低、下一轮偏高。- // 总量不丢,只是归属错位;不做纠正的理由见 usage/modelUsageDelta 文件头。- log.warn(- `turn output likely lagging upstream settlement (session=${session.id}): ` +- modelUsageDeltas- .map(- (d) =>- `${d.model} out=${d.outputTokensDelta} in=${d.inputTokensDelta} ` +- `cacheRead=${d.cacheReadTokensDelta} cacheCreate=${d.cacheCreateTokensDelta}`,- )- .join('; '),+ // done / 终止型 error 持久化边界:把在飞 assistant 落库(与 text isFinal 互斥幂等)。+ // tool_use 边界的 flush 已在上面 broadcast 前做(需先于 tool_use 落库);+ // ask_user / plan_review / permission 不走 onEvent(走 interaction listener),+ // 它们的 flush 在 setInteractionListener 里。+ //+ // 可重试 error 仍属于同一 turn,不能 reset lastAgentMeta / tool_result 配对状态;+ // 否则未来出现 turn 中途的非终止型 error 时会打断后续 tool_result 关联。+ // 本 turn 最后一条 assistant 的 persistId(挂 per-turn 费用 / turn 边界用)。terminal+ // error 同样 consume,写失败 seal 后再按需交接给 paired done;纯 tool 轮为 undefined。+ let turnAssistantPersistId: string | undefined;+ let turnBoundaryAssistantPersistId: string | undefined;+ let isPairedFailedTurnDone = false;+ if (event.type === 'done' || isTerminalTurnErrorEvent(event)) {+ flushAssistantBlock(session.id, eventAgentMeta);+ turnAssistantPersistId = consumeLastAssistantPersistId(session.id);+ turnBoundaryAssistantPersistId = consumeLastTopLevelAssistantPersistId(session.id);+ if (isTerminalTurnErrorEvent(event) && event.type !== 'done') {+ // 失败 turn: 记账发生在稍后的配对 done(usage 在那条事件上), 把这里+ // consume 到的 persistId 交接过去(见 pendingFailedTurnAssistantPersistId)。+ if (turnAssistantPersistId) {+ pendingFailedTurnAssistantPersistId.set(session.id, turnAssistantPersistId);+ }+ } else {+ // done: 优先本事件 consume 的 id, 失败 turn 场景回收交接的 id;+ // 无论用没用到都清掉, 防残留错配下一轮。+ const pendingFailedPersistId = pendingFailedTurnAssistantPersistId.get(session.id);+ if (!turnAssistantPersistId && pendingFailedPersistId) {+ turnAssistantPersistId = pendingFailedPersistId;+ isPairedFailedTurnDone = true;+ }+ pendingFailedTurnAssistantPersistId.delete(session.id);+ }+ flushOrphanToolResults(session.id, eventAgentMeta);+ if (turnBoundaryAssistantPersistId) {+ // 在同一 durable FIFO 内先盖 turn seal、再复用 local-db:messages:created 广播+ // 更新后的完整行。失败轮的 paired done 只复用 id 做 usage 记账,不能把+ // terminal error 已写的 false seal 覆盖成 true、让施工播报重新进入标题素材。+ if (event.type !== 'done') {+ void markAssistantTurnFailed(session.id, turnBoundaryAssistantPersistId);+ } else if (!isPairedFailedTurnDone) {+ void markAssistantTurnCompleted(session.id, turnBoundaryAssistantPersistId);+ }+ }+ // error 行在 flushOrphanToolResults 之后入队,保证 orphan tool_result 排在+ // error 行之前(历史时间线:tool 输出 → 错误卡,而非错误卡插到 tool 输出之前)。+ // 自愈接管中 → 压住 error 行:成功续跑时历史里只留一条「已自动继续」分隔条,+ // 救不回来时由 AutoResumeBookkeeping.finalizeSuppressedError 补落。判据取 coordinator 的实时+ // 接管态(而非 host 自己的 map):退避期间用户若自己发了消息,接管态已被清,那之后+ // 新 turn 的失败必须照常落库。+ //+ // 还有一种时序:terminal error 早于用户气泡落库完成到达时,接管决策要推迟到+ // settlePendingTerminalEventAfterPersist 才能做(recovery 留不留得住是前提)。那时+ // error 行早就落库了、压不回去,接管成功后历史里会同时留下错误卡与重连行(codex P1)。+ // 所以决策未定时也一并压住(isAutoResumeDeferred),由 coordinator 在三个「最终没接管」+ // 的出口回调 onResumableTurnErrorDiscarded 让它补落。+ const autoResumeSuppressesPersist =+ event.type === 'error' &&+ (agentInputCoordinatorHolder?.isAutoResumePending(session.id) === true ||+ agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id) === true);+ if (+ event.type === 'error' &&+ !isPlannedUpgradeClose &&+ !isRemoteAuthRetry &&+ !autoResumeSuppressesPersist+ ) {+ onTurnErrorEvent(+ session.id,+ attributedEvent.data as {+ message?: unknown;+ reason?: unknown;+ sdkError?: unknown;+ } | null,+ eventAgentMeta,+ );+ }+ // 压住的错误详情必须在这里存一份:决策推迟场景下 onResumableTurnError 还没被调用过+ // (它自己那份 set 发生在接管成立时),不存就无从补落。同 clientId 内容,覆盖无害。+ if (autoResumeSuppressesPersist) {+ autoResumeBookkeeping.stashSuppressedError(+ session.id,+ attributedEvent.data,+ agentInputCoordinatorHolder?.getAutoResumeAttemptToken(session.id) ?? null,+ agentInputCoordinatorHolder?.getAutoResumeDeferredOwner(session.id) ?? null,+ );+ } else if (event.type === 'error' && isTerminalTurnErrorEvent(event)) {+ // replacement 可在 sendToAgent 返回前同步失败并让 coordinator 的 activeTurn+ // 失效;这个新终态已经取代旧中断,按 dispatch phase 直接清旧 owner。+ autoResumeBookkeeping.discardReplacementProvenByProviderEvent(session.id);+ }+ // deferred 路径保存 turn 开始时刻:isRemoteAuthRetry 时 onTurnErrorEvent 被跳过,+ // renderer 会稍后调 persistTurnErrorDeferred IPC。在 resetTurnPersistState 清掉+ // _turnStartedAtBySession 之前保存一份,让 deferred 路径能正确做 /clear 竞态 cap。+ // 自愈压住 error 行时同理:补落发生在 resetTurnPersistState 之后(退避 3–20 秒,+ // 或决策推迟的那一小段),不先存一份会让 /clear 竞态 cap 判错。+ if (event.type === 'error' && (isRemoteAuthRetry || autoResumeSuppressesPersist)) {+ saveTurnStartedAtForDeferred(session.id);+ }+ // turn 收尾打标:本 turn 已知持久化(assistant flush / orphan tool_result /+ // error 行)已全部入队,在此统一定格并等排空后写。done 与 terminal error+ // 同一规则(planned upgrade close / remote auth retry 分支无 error 行,+ // drain 同样无害)。+ markTurnEndedAfterPersistDrain(session.id);+ resetTurnPersistState(session.id);+ // sidebar-card-mode: 摘要触发挪到本轮 assistant 块 flush 入队之后(原先在+ // done 早段、flush 之前触发,流式轮次会读到上一轮文本)。只在正常 done 触发。+ // codex review:flushAssistantBlock 仅把 assistant insert 入队 writeChain、未落库,+ // latestMessageText 立刻读库可能读到本轮 assistant 写入之前的旧状态;先 await+ // drainPersistQueue() 等持久化队列排空,确立"读在写后"的边界,再起摘要。+ if (event.type === 'done') {+ void (async () => {+ await drainPersistQueue();+ // force:turn-done 是权威刷新点(本轮 assistant 已落库),必须以最新内容覆盖+ // 任何 pin 触发 / 上一轮残留的摘要——绕过 in-flight 早返与 20s 节流+ // (codex review:pin during running turn 会让卡片停在部分/旧摘要)。+ await maybeGenerateSessionTaskSummary(session.id, { force: true });+ })();+ }+ // will-assistant-message 出口钩子(先定案 → 一拍后替换):仅 done(非终止+ // error)、有真实回复文本 + 已落库的 assistant persistId + 有启用的出口钩子+ // 意识时,派一个独立异步续跑跑裁决并原地更新那条消息(rewrite 换文本 /+ // render 换自绘卡)。同步守卫 hasEnabledGhostAssistantHook 保证无此类意识时+ // 不 schedule —— 与今天行为逐字节一致,零额外开销(规则 10 不碰热路径)。+ if (event.type === 'done' && turnAssistantPersistId) {+ const doneResult = (event.data as { result?: unknown } | null)?.result;+ const replyText = typeof doneResult === 'string' ? doneResult : '';+ if (replyText.length > 0 && hasEnabledGhostAssistantHook()) {+ runGhostAssistantReplyHook(session.id, turnAssistantPersistId, replyText);+ }+ }+ // Worker turn 结束后交给 OrcaTeamService 处理 DB status、广播与 auto-bridge。+ void (async () => {+ try {+ const doneData = event.data as { result?: unknown } | null;+ const finalText =+ typeof doneData?.result === 'string' && doneData.result.length > 0+ ? doneData.result+ : '';+ await workerTurnStartSequencer.waitForStart(session.id);+ await orcaTeamServiceForEvents?.handleWorkerTerminalTurn({+ sessionId: session.id,+ status: isTerminalTurnErrorEvent(event) ? 'error' : 'done',+ finalText,+ });+ } catch {+ /* non-fatal */+ }+ })();+ }+ if (pendingContextSnapshot) {+ recordSessionContextSnapshot(+ session.id,+ pendingContextSnapshot.contextTokens,+ pendingContextSnapshot.contextWindow,);}- if (turnAssistantPersistId && modelUsageDeltas && modelUsageDeltas.length > 0) {- const mismatchClientId = turnAssistantPersistId;- const actualEntries = modelUsageDeltas.map((d) => ({- model: d.model,- outputTokens: d.outputTokensDelta,- }));- void modelPromise- .then((selectedModel) => {- const mismatch = detectClaudeModelMismatch(selectedModel, actualEntries);- if (mismatch) {- return recordModelMismatchOnMessage({- sessionId: session.id,- clientId: mismatchClientId,- mismatch,- });- }- })- .catch(() => { /* 模型解析失败:跳过降级检测,非致命 */ });+ if (pendingCodexAccountUsageSnapshot) {+ recordCodexAccountUsageSnapshot(pendingCodexAccountUsageSnapshot);}- if (modelUsageDeltas && modelUsageDeltas.length > 0) {- // 主路径: 逐模型 HYBRID 定价 (Anthropic→SDK, 非 Anthropic→gateway), 四个 sink- // 由同一份解析结果驱动。价格表走 main 端内存 + 磁盘缓存, stale 快返并后台刷新。- const deltas = modelUsageDeltas;- void (async () => {- const sessionProviderForBilling = getSessionProvider(session.id);- const observedClaudeRoute =- sessionProviderForBilling == null ? readClaudeSessionRoute(session.id) : null;- const explicitProviderBillingRoute = billingRouteForExplicitProvider(- sessionProviderForBilling,- sessionProviderForBilling- ? getActiveCatalog().providers.find(- (provider) => provider.id === sessionProviderForBilling,- )?.access?.kind- : null,- );- const isClaudeSubscriptionSession = !session.remoteHostId && (- sessionProviderForBilling === 'anthropic'- || (- sessionProviderForBilling == null- && (observedClaudeRoute != null- ? observedClaudeRoute === 'subscription'- : !readClaudeApiKey())- )+ // 每 turn 结束累加 daily_spend 表 + 广播给 renderer 右下角"今日 $X.XX" chip。+ // 这些统计 side effect 必须在 EVENT broadcast 之后,避免同步 SQLite 或额外+ // usage 广播延后 final/done 送达。+ //+ // 本轮费用 = HYBRID 定价: Anthropic 模型信任 SDK 自报 cost (OAuth 下=0、API 下=真实、+ // cache-correct), 非 Anthropic provider 模型 (gpt-5.5 等) 用远端 gateway 价 × token+ // 重算 —— 修 SDK 把它们按 Anthropic 价错算 (~2.5x) 的 bug。逐模型解析后四个 sink+ // (今日 / session / per-message / 按模型) 同源同值。+ // 守卫: index.ts:388 stream_end fallback / codex done 不带 total_cost_usd, typeof 检查会跳过。+ if (event.type === 'done' && event.source === 'claude-code') {+ const modelPromise =+ turnModelPromiseBySession.get(session.id) ?? readSessionModelForUsage(session.id);+ turnModelPromiseBySession.delete(session.id);+ const doneData = event.data as+ | {+ total_cost_usd?: unknown;+ usage?: {+ input_tokens?: number;+ output_tokens?: number;+ cache_read_input_tokens?: number;+ cache_creation_input_tokens?: number;+ };+ modelUsage?: Record<string, unknown>;+ }+ | undefined;+ const cumulative = doneData?.total_cost_usd;+ const modelUsage = doneData?.modelUsage;+ let modelUsageDeltas: ModelUsageDeltaEntry[] | undefined;+ if (modelUsage && typeof modelUsage === 'object') {+ const { next, deltas } = computeModelUsageDeltas(+ lastReportedModelUsageBySession.get(session.id),+ modelUsage,);- const billingRoute: BillingRoute = session.remoteHostId- ? 'unknown'- : isClaudeSubscriptionSession- ? 'subscription'- : explicitProviderBillingRoute- ?? (observedClaudeRoute === 'gateway' ? 'xd-gateway' : 'unknown');- const pricing =- billingRoute === 'xd-gateway'- ? await getGatewayModelPricingForModel()- : getReferenceModelPricing();- const { turnMoney, estimatedTurnMoney, perModel } = resolveClaudeTurnCostSinks(- deltas,- pricing,- {- providerId: sessionProviderForBilling,- billingRoute,- region: CURRENT_CINDY_REGION,- },+ lastReportedModelUsageBySession.set(session.id, next);+ modelUsageDeltas = deltas;+ }+ // total_cost_usd 累计基线: 主路径不靠它算钱, 但仍跟住, 以便万一某轮缺 modelUsage+ // 走兜底时累计差才准。先取"更新前"基线给兜底用, 再写入本轮累计。+ const prevReportedCost = lastReportedCostUsdBySession.get(session.id) ?? 0;+ if (typeof cumulative === 'number' && cumulative >= 0) {+ lastReportedCostUsdBySession.set(session.id, cumulative);+ }+ // 模型降级检测:所选模型(turn start 快照)整轮缺席于实际 modelUsage delta →+ // 判定主线被上游静默替换(如 fable-5 高负载被路由到 opus-4-8),把标记挂到本轮+ // 收尾 assistant 的 agent_meta 上(AssistantMessage 渲染降级提示行)。+ // fire-and-forget,与记账 sink 互不阻塞;判定纯函数见 shared/modelMismatch.ts。+ if (modelUsageDeltas && detectOutputLag(modelUsageDeltas)) {+ // 上游在 done 时点还没结算本轮输出(实测 Vertex),这一轮的费用会偏低、下一轮偏高。+ // 总量不丢,只是归属错位;不做纠正的理由见 usage/modelUsageDelta 文件头。+ log.warn(+ `turn output likely lagging upstream settlement (session=${session.id}): ` ++ modelUsageDeltas+ .map(+ (d) =>+ `${d.model} out=${d.outputTokensDelta} in=${d.inputTokensDelta} ` ++ `cacheRead=${d.cacheReadTokensDelta} cacheCreate=${d.cacheCreateTokensDelta}`,+ )+ .join('; '),);- // 按模型记账 (首页仪表盘"按模型拆分"): 写归一化裸 id, 与 codex 行 / 价格表对齐。- // 订阅轮打 #billing=subscription 标记(Claude 订阅:Anthropic 模型 + cost=0),- // 或 bridge 订阅轮(chatgpt// xai/ 前缀,source==='subscription');两类均需触发- // rebroadcastTodaySpend 刷新首页仪表盘。- const modelUsageWrites: Promise<unknown>[] = [];- let hasSubscriptionValueRow = false;- for (const m of perModel) {- const isClaudeSubscriptionValueRow =- isClaudeSubscriptionSession && !m.money && isAnthropicModel(m.model);- const isBridgeSubscriptionRow =- m.source === 'subscription' && isSubscriptionDirectModel(m.model);- if (isClaudeSubscriptionValueRow || isBridgeSubscriptionRow) hasSubscriptionValueRow = true;- modelUsageWrites.push(recordModelTurnUsage({- agentKind: 'claude-code',- model: isClaudeSubscriptionValueRow ? claudeSubscriptionUsageModelKey(m.model) : m.model,- // daily_model_usage does not persist RegionalMoney.kind. Keep reference estimates- // out of this actual-cost row so they cannot be reconstructed as real API spend.- money: m.money?.kind === 'actual-cost' ? m.money : null,- inputTokensDelta: m.deltas.inputTokens,- outputTokensDelta: m.deltas.outputTokens,- cacheReadTokensDelta: m.deltas.cacheReadTokens,- cacheCreateTokensDelta: m.deltas.cacheCreateTokens,- }));- }- // 无真实费用、但产生订阅价值或 provider 参考估值的轮次不走- // recordTurnSpend。等模型行落库后重广播今日 spend 快照,通知已打开的首页- // 仪表盘刷新(对齐 codex 订阅轮的 rebroadcastCodexTodayUsage)。- if ((hasSubscriptionValueRow || estimatedTurnMoney) && !turnMoney) {- void Promise.allSettled(modelUsageWrites).then(() => rebroadcastTodaySpend());- }- if (turnMoney && turnMoney.amount > 0) {- // 保留 #216 的 token/cache 明细随费用落库 (MessageActionBar tooltip)。- // deltas 非空 → buildClaudeTurnUsageDetails 用 deltas 里的 model, fallbackModel 不取用。- // 传 perModel → 落「按模型成本明细」(含 subagent 跑的模型, 如 Haiku)。- const turnUsageDetails = buildClaudeTurnUsageDetails(doneData?.usage, deltas, 'unknown', perModel);- recordTurnSpend(turnMoney);- recordSessionTurnSpend(session.id, turnMoney);- // per-message 维度优先挂 assistant;纯 tool turn 则按 scheduler runId 直接归因。- const changedScheduleId = await recordSchedulerTurnCost({- sessionId: session.id,- clientId: turnAssistantPersistId,- money: turnMoney,- turnUsageDetails,- turnOrigin: event.turnOrigin,+ }+ if (turnAssistantPersistId && modelUsageDeltas && modelUsageDeltas.length > 0) {+ const mismatchClientId = turnAssistantPersistId;+ const actualEntries = modelUsageDeltas.map((d) => ({+ model: d.model,+ outputTokens: d.outputTokensDelta,+ }));+ void modelPromise+ .then((selectedModel) => {+ const mismatch = detectClaudeModelMismatch(selectedModel, actualEntries);+ if (mismatch) {+ return recordModelMismatchOnMessage({+ sessionId: session.id,+ clientId: mismatchClientId,+ mismatch,+ });+ }+ })+ .catch(() => {+ /* 模型解析失败:跳过降级检测,非致命 */});- if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);- } else if (turnAssistantPersistId) {- // 无真实计费轮的「本轮价值」估算,挂到消息(isEstimate:true,chip 的- // "本会话价值"由 useSessionEstimatedValue 汇总),不进 daily_spend /- // sessions.total_cost_usd(那些是真实账单)。provider 参考价与两类订阅估值- // 可叠加(如 Claude 订阅主会话 + bridge 订阅子 agent):- // - provider-api 参考价:远程目录中的公开参考价,不是供应商真实账单;- // - bridge 订阅模型(chatgpt/ / xai/,source==='subscription'):静态参考价折算;- // - Claude 订阅会话(显式选 Anthropic,SDK 自报 cost=0):Anthropic 牌价折算- // (纯 Anthropic 轮 pricing 为 null → 家族牌价兜底表,不为估值发起网络请求)。- // 混合轮(真实计费 > 0)走上面的真实分支,订阅部分不另挂估算 —— 一条消息只有一个- // cost 字段,真实计费优先;订阅 token 明细仍在 turnUsageDetails.perModelCost 里。- const estimatedValues: RegionalMoney[] = estimatedTurnMoney- ? [estimatedTurnMoney]- : [];+ }+ if (modelUsageDeltas && modelUsageDeltas.length > 0) {+ // 主路径: 逐模型 HYBRID 定价 (Anthropic→SDK, 非 Anthropic→gateway), 四个 sink+ // 由同一份解析结果驱动。价格表走 main 端内存 + 磁盘缓存, stale 快返并后台刷新。+ const deltas = modelUsageDeltas;+ void (async () => {+ const sessionProviderForBilling = getSessionProvider(session.id);+ const observedClaudeRoute =+ sessionProviderForBilling == null ? readClaudeSessionRoute(session.id) : null;+ const explicitProviderBillingRoute = billingRouteForExplicitProvider(+ sessionProviderForBilling,+ sessionProviderForBilling+ ? getActiveCatalog().providers.find(+ (provider) => provider.id === sessionProviderForBilling,+ )?.access?.kind+ : null,+ );+ const isClaudeSubscriptionSession =+ !session.remoteHostId &&+ (sessionProviderForBilling === 'anthropic' ||+ (sessionProviderForBilling == null &&+ (observedClaudeRoute != null+ ? observedClaudeRoute === 'subscription'+ : !readClaudeApiKey())));+ const billingRoute: BillingRoute = session.remoteHostId+ ? 'unknown'+ : isClaudeSubscriptionSession+ ? 'subscription'+ : (explicitProviderBillingRoute ??+ (observedClaudeRoute === 'gateway' ? 'xd-gateway' : 'unknown'));+ const pricing =+ billingRoute === 'xd-gateway'+ ? await getGatewayModelPricingForModel()+ : getReferenceModelPricing();+ const { turnMoney, estimatedTurnMoney, perModel } = resolveClaudeTurnCostSinks(+ deltas,+ pricing,+ {+ providerId: sessionProviderForBilling,+ billingRoute,+ region: CURRENT_CINDY_REGION,+ },+ );+ // 按模型记账 (首页仪表盘"按模型拆分"): 写归一化裸 id, 与 codex 行 / 价格表对齐。+ // 订阅轮打 #billing=subscription 标记(Claude 订阅:Anthropic 模型 + cost=0),+ // 或 bridge 订阅轮(chatgpt// xai/ 前缀,source==='subscription');两类均需触发+ // rebroadcastTodaySpend 刷新首页仪表盘。+ const modelUsageWrites: Promise<unknown>[] = [];+ let hasSubscriptionValueRow = false;for (const m of perModel) {- if (m.source !== 'subscription') continue;- const quote = getSubscriptionDirectValuePrice(m.model, 'claude-code', pricing);- const value = computePriceQuoteTurnMoney(- m.deltas,- quote ?? undefined,- currentLedgerCurrency(),+ const isClaudeSubscriptionValueRow =+ isClaudeSubscriptionSession && !m.money && isAnthropicModel(m.model);+ const isBridgeSubscriptionRow =+ m.source === 'subscription' && isSubscriptionDirectModel(m.model);+ if (isClaudeSubscriptionValueRow || isBridgeSubscriptionRow)+ hasSubscriptionValueRow = true;+ modelUsageWrites.push(+ recordModelTurnUsage({+ agentKind: 'claude-code',+ model: isClaudeSubscriptionValueRow+ ? claudeSubscriptionUsageModelKey(m.model)+ : m.model,+ // daily_model_usage does not persist RegionalMoney.kind. Keep reference estimates+ // out of this actual-cost row so they cannot be reconstructed as real API spend.+ money: m.money?.kind === 'actual-cost' ? m.money : null,+ inputTokensDelta: m.deltas.inputTokens,+ outputTokensDelta: m.deltas.outputTokens,+ cacheReadTokensDelta: m.deltas.cacheReadTokens,+ cacheCreateTokensDelta: m.deltas.cacheCreateTokens,+ }),);- if (value?.amount) estimatedValues.push(value);}- if (isClaudeSubscriptionSession) {- const claudeEstimated = estimateClaudeSubscriptionTurnValue(+ // 无真实费用、但产生订阅价值或 provider 参考估值的轮次不走+ // recordTurnSpend。等模型行落库后重广播今日 spend 快照,通知已打开的首页+ // 仪表盘刷新(对齐 codex 订阅轮的 rebroadcastCodexTodayUsage)。+ if ((hasSubscriptionValueRow || estimatedTurnMoney) && !turnMoney) {+ void Promise.allSettled(modelUsageWrites).then(() => rebroadcastTodaySpend());+ }+ if (turnMoney && turnMoney.amount > 0) {+ // 保留 #216 的 token/cache 明细随费用落库 (MessageActionBar tooltip)。+ // deltas 非空 → buildClaudeTurnUsageDetails 用 deltas 里的 model, fallbackModel 不取用。+ // 传 perModel → 落「按模型成本明细」(含 subagent 跑的模型, 如 Haiku)。+ const turnUsageDetails = buildClaudeTurnUsageDetails(+ doneData?.usage,+ deltas,+ 'unknown',perModel,- currentLedgerCurrency(),- pricing,);- if (claudeEstimated?.amount) estimatedValues.push(claudeEstimated);- }- const turnEstimatedValue =- estimatedValues.length > 0- ? addRegionalMoney(estimatedValues)- : null;- const turnUsageDetails = buildClaudeTurnUsageDetails(doneData?.usage, deltas, 'unknown', perModel);- if (turnEstimatedValue && turnEstimatedValue.amount > 0) {+ recordTurnSpend(turnMoney);+ recordSessionTurnSpend(session.id, turnMoney);+ // per-message 维度优先挂 assistant;纯 tool turn 则按 scheduler runId 直接归因。const changedScheduleId = await recordSchedulerTurnCost({sessionId: session.id,clientId: turnAssistantPersistId,- money: turnEstimatedValue,+ money: turnMoney,turnUsageDetails,turnOrigin: event.turnOrigin,});if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);- } else {- // 真实计费与订阅估值都拿不到(典型:网关目录整体不下发价格、模型不在价表)- // —— 钱没有,但 token 明细是算好的,落下来让 UI 退回显示本轮 token。+ } else if (turnAssistantPersistId) {+ // 无真实计费轮的「本轮价值」估算,挂到消息(isEstimate:true,chip 的+ // "本会话价值"由 useSessionEstimatedValue 汇总),不进 daily_spend /+ // sessions.total_cost_usd(那些是真实账单)。provider 参考价与两类订阅估值+ // 可叠加(如 Claude 订阅主会话 + bridge 订阅子 agent):+ // - provider-api 参考价:远程目录中的公开参考价,不是供应商真实账单;+ // - bridge 订阅模型(chatgpt/ / xai/,source==='subscription'):静态参考价折算;+ // - Claude 订阅会话(显式选 Anthropic,SDK 自报 cost=0):Anthropic 牌价折算+ // (纯 Anthropic 轮 pricing 为 null → 家族牌价兜底表,不为估值发起网络请求)。+ // 混合轮(真实计费 > 0)走上面的真实分支,订阅部分不另挂估算 —— 一条消息只有一个+ // cost 字段,真实计费优先;订阅 token 明细仍在 turnUsageDetails.perModelCost 里。+ const estimatedValues: RegionalMoney[] = estimatedTurnMoney+ ? [estimatedTurnMoney]+ : [];+ for (const m of perModel) {+ if (m.source !== 'subscription') continue;+ const quote = getSubscriptionDirectValuePrice(m.model, 'claude-code', pricing);+ const value = computePriceQuoteTurnMoney(+ m.deltas,+ quote ?? undefined,+ currentLedgerCurrency(),+ );+ if (value?.amount) estimatedValues.push(value);+ }+ if (isClaudeSubscriptionSession) {+ const claudeEstimated = estimateClaudeSubscriptionTurnValue(+ perModel,+ currentLedgerCurrency(),+ pricing,+ );+ if (claudeEstimated?.amount) estimatedValues.push(claudeEstimated);+ }+ const turnEstimatedValue =+ estimatedValues.length > 0 ? addRegionalMoney(estimatedValues) : null;+ const turnUsageDetails = buildClaudeTurnUsageDetails(+ doneData?.usage,+ deltas,+ 'unknown',+ perModel,+ );+ if (turnEstimatedValue && turnEstimatedValue.amount > 0) {+ const changedScheduleId = await recordSchedulerTurnCost({+ sessionId: session.id,+ clientId: turnAssistantPersistId,+ money: turnEstimatedValue,+ turnUsageDetails,+ turnOrigin: event.turnOrigin,+ });+ if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);+ } else {+ // 真实计费与订阅估值都拿不到(典型:网关目录整体不下发价格、模型不在价表)+ // —— 钱没有,但 token 明细是算好的,落下来让 UI 退回显示本轮 token。+ await recordTurnUsageOnMessage({+ sessionId: session.id,+ clientId: turnAssistantPersistId,+ turnUsageDetails,+ });+ }+ }+ })();+ } else if (typeof cumulative === 'number' && cumulative >= 0) {+ // 窄兜底: 罕见地 done 只带 total_cost_usd、没 modelUsage —— 拆不了 daily_model_usage,+ // 但至少用累计差把总额 / session / message 记上, 别漏整轮 (review #4)。+ const rawDelta = Math.max(0, cumulative - prevReportedCost);+ void (async () => {+ let resolvedModel = 'unknown';+ try {+ const model = await modelPromise;+ resolvedModel = model;+ } catch {+ /* non-fatal: 保留 SDK 原始 cost */+ }+ const turnUsageDetails = buildClaudeTurnUsageDetails(+ doneData?.usage,+ undefined,+ resolvedModel,+ );+ // 本分支有三个"记不了钱"的出口(本轮 cost 未增长 / 订阅直连 / 订阅与网关路由),+ // 账本口径一个字不改,但都把本轮 token 明细落下来 —— 钱算不出来不代表用量+ // 算不出来,UI 那一格据此退回显示 token 而不是空着。+ const recordUsageOnly = async () => {+ if (!turnAssistantPersistId) return;await recordTurnUsageOnMessage({sessionId: session.id,clientId: turnAssistantPersistId,turnUsageDetails,});+ };+ if (rawDelta <= 0) {+ await recordUsageOnly();+ return;}- }- })();- } else if (typeof cumulative === 'number' && cumulative >= 0) {- // 窄兜底: 罕见地 done 只带 total_cost_usd、没 modelUsage —— 拆不了 daily_model_usage,- // 但至少用累计差把总额 / session / message 记上, 别漏整轮 (review #4)。- const rawDelta = Math.max(0, cumulative - prevReportedCost);- void (async () => {- let resolvedModel = 'unknown';- try {- const model = await modelPromise;- resolvedModel = model;- } catch { /* non-fatal: 保留 SDK 原始 cost */ }- const turnUsageDetails = buildClaudeTurnUsageDetails(doneData?.usage, undefined, resolvedModel);- // 本分支有三个"记不了钱"的出口(本轮 cost 未增长 / 订阅直连 / 订阅与网关路由),- // 账本口径一个字不改,但都把本轮 token 明细落下来 —— 钱算不出来不代表用量- // 算不出来,UI 那一格据此退回显示 token 而不是空着。- const recordUsageOnly = async () => {- if (!turnAssistantPersistId) return;- await recordTurnUsageOnMessage({- sessionId: session.id,- clientId: turnAssistantPersistId,- turnUsageDetails,- });- };- if (rawDelta <= 0) {- await recordUsageOnly();- return;- }- const providerId = getSessionProvider(session.id);- const observedRoute =- providerId == null ? readClaudeSessionRoute(session.id) : null;- const explicitProviderRoute = billingRouteForExplicitProvider(- providerId,- providerId- ? getActiveCatalog().providers.find((provider) => provider.id === providerId)- ?.access?.kind- : null,- );- const route: BillingRoute = session.remoteHostId- ? 'unknown'- : providerId === 'anthropic' || observedRoute === 'subscription'- ? 'subscription'- : explicitProviderRoute- ?? (observedRoute === 'gateway' ? 'xd-gateway' : 'unknown');- // 订阅直连轮(chatgpt/ / xai/)走窄兜底时: 真实计费恒 0, 不写 daily_spend /- // sessions.total_cost_usd(与主路径 resolveTurnCost 的 subscription gate 同口径,- // 避免把订阅 SDK 自报 cost 误记进计费)。但显式 provider-api 是权威路由:- // 自定义 API 供应商可能供应带订阅前缀的模型 id,不能按前缀把真实费用判掉。- if (route !== 'provider-api' && isSubscriptionDirectModel(resolvedModel)) {- await recordUsageOnly();- return;- }- if (route === 'subscription' || route === 'xd-gateway') {- await recordUsageOnly();- return;- }- const ledgerCurrency =- (await getGatewayAccountCurrency()) ?? currentLedgerCurrency();- const money = usdToLedgerCurrency(rawDelta, ledgerCurrency);- recordTurnSpend(money);- recordSessionTurnSpend(session.id, money);- const changedScheduleId = await recordSchedulerTurnCost({- sessionId: session.id,- clientId: turnAssistantPersistId,- money,- turnUsageDetails,- turnOrigin: event.turnOrigin,- });- if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);- })();- }- // 与 spend 记账并列的另一个 turn-done side-effect: 刷新 Claude 账号月度配额- // (LiteLLM /v2/user/info)。fire-and-forget, 模块内 2s 超时 + 10s 节流。- // 故意放在 cumulative 块外面: spend 走 turn delta, 配额走 HTTP API, 两件事独立;- // 但仍在 done && claude-code 的 if 内, 不要每个事件都打一次。- void triggerClaudeAccountUsageRefresh();- // chatgpt/ 订阅轮: 额外触发 ChatGPT wham 额度刷新(与 codex 同一 ChatGPT 账户),让底部- // chip 的订阅额度实时更新 —— bridge 轮不产生 codex account_usage 事件,须主动触发。- void modelPromise- .then((m) => { if (m && m.startsWith(CHATGPT_MODEL_PREFIX)) triggerCodexAccountUsageRefresh(); })- .catch(() => { /* 模型解析失败: 跳过, 非致命 */ });- // Claude 订阅账号余量 (oauth/usage 端点) 同理 turn-done 触发一次 —— 节流 (180s) /- // 429 退避 / 未连订阅 no-op 都在 reader 内部; turn 内的实时刷新由 proxy 旁路读- // unified headers 兜住, 这里只负责把 scoped 分模型窗口等端点独有数据拉新。- triggerClaudeSubscriptionUsageRefresh();- }- // Codex done 事件: 记 today token 累计 (替代老 registerCodexIpc 里的 recordCodexTurnUsage 接入点)。- // codex/index.ts 在 turn.completed 时把 SDK usage 翻成 camelCase 塞进 done.data.usage, 这里直接转给 broadcaster。- // Codex SDK 不报 cost, 所以走 token 量(codex chip 显示 "本 session N token"), 跟 Claude 的 $ chip 是两条管道。- if (event.type === 'done' && event.source === 'codex') {- // 本会话显式选定的供应商('xd' / 'openai' / null=默认)。退役全局 authMode 后,- // 「是否走订阅(不计网关费)」改由 spawn 注入 + 该会话是否显式选了 XD 网关决定。- const sessionProvider = getSessionProvider(session.id);- const isRemoteCodexSession = Boolean(session.remoteHostId);- const isCustomProviderRoute =- !isRemoteCodexSession && isUserProviderSession(session.id);- const codexAuthInjection = isRemoteCodexSession ? null : getCodexProxyAuthInjection();- const modelPromise = turnModelPromiseBySession.get(session.id) ?? readSessionModelForUsage(session.id);- turnModelPromiseBySession.delete(session.id);- const usage = (event.data as { usage?: unknown } | undefined)?.usage;- if (usage) recordCodexTurnUsage(usage);- // 按模型记账: codex done.data.usage 是 **per-turn 增量语义** (maker-core- // codexDoneUsage 契约: promptTokens=本 turn 未命中输入, completionTokens=输出+推理- // 合并, cachedTokens=命中缓存; 整 turn 没收到 tokenUsage/updated 时全 0)。- // 直接入库, 不做 delta 化 —— 历史上 promptTokens 曾是 contextTokens 快照、这里- // 做过 per-session delta 化, 语义改为 per-turn 后那套逻辑会把后小于前的 turn 记 0。- if (usage && typeof usage === 'object') {- const u = usage as { promptTokens?: number; completionTokens?: number; reasoningTokens?: number; cachedTokens?: number };- const promptTokens = Number(u.promptTokens) || 0;- const completionTokens = Number(u.completionTokens) || 0;- const cachedTokens = Number(u.cachedTokens) || 0;- void recordSessionTurnTokens(- session.id,- promptTokens + completionTokens + cachedTokens,- );- // 先落 daily_model_usage token 行, 再等价格表补 API cost。首页 usage push 会在- // ~2s 后刷新, 不能让冷价格表 / 离线 fetch 把模型 token 行延后到刷新之后。- // 后续 cost-only 增量不会重复累计 token。- void (async () => {- let pricingModel = 'unknown';- let turnModel = 'unknown';- try {- turnModel = await modelPromise;- // 价格查表用归一化裸 id, 与 daily_model_usage 的 key 一致- // (codex 当前不带 [1m], 归一化防御未来变体后缀导致查表 miss)。- pricingModel = normalizeModelIdForPricing(turnModel);- } catch {- // 模型读取失败时仍记录 token, 聚合 UI 会归到 unknown。- }- const isCodexBudgetRoute =- (sessionProvider == null || sessionProvider === 'xd')- && pricingModel.startsWith('codex/');- const isCodexXaiProviderRoute =- (sessionProvider == null || sessionProvider === 'xai')- && pricingModel.startsWith(XAI_MODEL_PREFIX);- const isCodexOpenAiProviderRoute =- sessionProvider == null || sessionProvider === 'openai';- const hasGatewayKey = Boolean(readClaudeApiKey());- const hasEffectiveGatewayRoute =- !isRemoteCodexSession &&- !isCustomProviderRoute &&- (- codexAuthInjection === 'env-key' ||- isCodexBudgetRoute ||- (sessionProvider === 'xd' && hasGatewayKey)- );- // 显式来源的订阅判定以目录 access.kind 为权威(内置 anthropic 的 Claude.ai- // 订阅同样是订阅价值,不能只认 OpenAI/xAI);目录缺 access 的旧快照仍靠下面- // 的 openai oauth 分支兜底。- const sessionProviderAccessKind = sessionProvider- ? getActiveCatalog().providers.find((provider) => provider.id === sessionProvider)- ?.access?.kind- : null;- const isCodexSubscriptionAccessRoute =- !isRemoteCodexSession &&- sessionProvider != null &&- sessionProvider !== 'xd' &&- sessionProviderAccessKind === 'subscription' &&- !hasEffectiveGatewayRoute;- const isSubscriptionValue = isRemoteCodexSession ||- isCodexXaiProviderRoute ||- isCodexSubscriptionAccessRoute ||- (- isCodexOpenAiProviderRoute- && codexAuthInjection === 'oauth-bearer'- && !hasEffectiveGatewayRoute+ const providerId = getSessionProvider(session.id);+ const observedRoute = providerId == null ? readClaudeSessionRoute(session.id) : null;+ const explicitProviderRoute = billingRouteForExplicitProvider(+ providerId,+ providerId+ ? getActiveCatalog().providers.find((provider) => provider.id === providerId)+ ?.access?.kind+ : null,);- const usesReferencePriceEstimate =- !isSubscriptionValue &&- !isRemoteCodexSession &&- !hasEffectiveGatewayRoute &&- Boolean(sessionProvider && sessionProvider !== 'xd');- const modelUsageKey = isSubscriptionValue- ? codexSubscriptionUsageModelKey(pricingModel)- : codexApiUsageModelKey(pricingModel);- await recordModelTurnUsage({- agentKind: 'codex',- model: modelUsageKey,- inputTokensDelta: promptTokens,- outputTokensDelta: completionTokens,- cacheReadTokensDelta: cachedTokens,- cacheCreateTokensDelta: 0,- }).finally(() => rebroadcastCodexTodayUsage());-- // Codex SDK 不报 $, 用价格表折算。普通模型 + oauth(订阅)显示为 token 价值;api 模式和 codex/- // 折扣模型走 gateway API, 显示为 API cost。远端 Codex 由远端 daemon- // 路由,本机不知道远端 OAuth/API 事实,因此只显示 token 价值,不写本地- // gateway cost。只有真实本地 API cost 写入 sessions.total_cost_usd,- // 避免 scheduler 的 Cost 汇总混入订阅价值或远端账号消耗。- // fire-and-forget 不阻塞事件循环;价格表走 main 端内存 + 磁盘缓存,- // stale 快返并后台刷新,- // 拉不到 / 模型无条目 → 只落 token 明细,UI 退回显示本轮 token。- // 明细在 try 外构造:它只依赖上面已拿到的 token 数,价格请求抛错时也要能落。- const turnUsageDetails = buildTurnUsageDetails({- inputTokens: promptTokens,- outputTokens: completionTokens,- cacheReadTokens: cachedTokens,- cacheCreateTokens: 0,- model: turnModel,- });- const recordCodexUsageOnly = async () => {- if (!turnAssistantPersistId) return;- await recordTurnUsageOnMessage({+ const route: BillingRoute = session.remoteHostId+ ? 'unknown'+ : providerId === 'anthropic' || observedRoute === 'subscription'+ ? 'subscription'+ : (explicitProviderRoute ??+ (observedRoute === 'gateway' ? 'xd-gateway' : 'unknown'));+ // 订阅直连轮(chatgpt/ / xai/)走窄兜底时: 真实计费恒 0, 不写 daily_spend /+ // sessions.total_cost_usd(与主路径 resolveTurnCost 的 subscription gate 同口径,+ // 避免把订阅 SDK 自报 cost 误记进计费)。但显式 provider-api 是权威路由:+ // 自定义 API 供应商可能供应带订阅前缀的模型 id,不能按前缀把真实费用判掉。+ if (route !== 'provider-api' && isSubscriptionDirectModel(resolvedModel)) {+ await recordUsageOnly();+ return;+ }+ if (route === 'subscription' || route === 'xd-gateway') {+ await recordUsageOnly();+ return;+ }+ const ledgerCurrency = (await getGatewayAccountCurrency()) ?? currentLedgerCurrency();+ const money = usdToLedgerCurrency(rawDelta, ledgerCurrency);+ recordTurnSpend(money);+ recordSessionTurnSpend(session.id, money);+ const changedScheduleId = await recordSchedulerTurnCost({sessionId: session.id,clientId: turnAssistantPersistId,+ money,turnUsageDetails,+ turnOrigin: event.turnOrigin,});+ if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);+ })();+ }+ // 与 spend 记账并列的另一个 turn-done side-effect: 刷新 Claude 账号月度配额+ // (LiteLLM /v2/user/info)。fire-and-forget, 模块内 2s 超时 + 10s 节流。+ // 故意放在 cumulative 块外面: spend 走 turn delta, 配额走 HTTP API, 两件事独立;+ // 但仍在 done && claude-code 的 if 内, 不要每个事件都打一次。+ void triggerClaudeAccountUsageRefresh();+ // chatgpt/ 订阅轮: 额外触发 ChatGPT wham 额度刷新(与 codex 同一 ChatGPT 账户),让底部+ // chip 的订阅额度实时更新 —— bridge 轮不产生 codex account_usage 事件,须主动触发。+ void modelPromise+ .then((m) => {+ if (m && m.startsWith(CHATGPT_MODEL_PREFIX)) triggerCodexAccountUsageRefresh();+ })+ .catch(() => {+ /* 模型解析失败: 跳过, 非致命 */+ });+ // Claude 订阅账号余量 (oauth/usage 端点) 同理 turn-done 触发一次 —— 节流 (180s) /+ // 429 退避 / 未连订阅 no-op 都在 reader 内部; turn 内的实时刷新由 proxy 旁路读+ // unified headers 兜住, 这里只负责把 scoped 分模型窗口等端点独有数据拉新。+ triggerClaudeSubscriptionUsageRefresh();+ }+ // Codex done 事件: 记 today token 累计 (替代老 registerCodexIpc 里的 recordCodexTurnUsage 接入点)。+ // codex/index.ts 在 turn.completed 时把 SDK usage 翻成 camelCase 塞进 done.data.usage, 这里直接转给 broadcaster。+ // Codex SDK 不报 cost, 所以走 token 量(codex chip 显示 "本 session N token"), 跟 Claude 的 $ chip 是两条管道。+ if (event.type === 'done' && event.source === 'codex') {+ // 本会话显式选定的供应商('xd' / 'openai' / null=默认)。退役全局 authMode 后,+ // 「是否走订阅(不计网关费)」改由 spawn 注入 + 该会话是否显式选了 XD 网关决定。+ const sessionProvider = getSessionProvider(session.id);+ const isRemoteCodexSession = Boolean(session.remoteHostId);+ const isCustomProviderRoute = !isRemoteCodexSession && isUserProviderSession(session.id);+ const codexAuthInjection = isRemoteCodexSession ? null : getCodexProxyAuthInjection();+ const modelPromise =+ turnModelPromiseBySession.get(session.id) ?? readSessionModelForUsage(session.id);+ turnModelPromiseBySession.delete(session.id);+ const usage = (event.data as { usage?: unknown } | undefined)?.usage;+ if (usage) recordCodexTurnUsage(usage);+ // 按模型记账: codex done.data.usage 是 **per-turn 增量语义** (maker-core+ // codexDoneUsage 契约: promptTokens=本 turn 未命中输入, completionTokens=输出+推理+ // 合并, cachedTokens=命中缓存; 整 turn 没收到 tokenUsage/updated 时全 0)。+ // 直接入库, 不做 delta 化 —— 历史上 promptTokens 曾是 contextTokens 快照、这里+ // 做过 per-session delta 化, 语义改为 per-turn 后那套逻辑会把后小于前的 turn 记 0。+ if (usage && typeof usage === 'object') {+ const u = usage as {+ promptTokens?: number;+ completionTokens?: number;+ reasoningTokens?: number;+ cachedTokens?: number;};- try {- const pricing = isSubscriptionValue- ? getReferenceModelPricing()- : hasEffectiveGatewayRoute- ? await getGatewayModelPricingForModel()- : usesReferencePriceEstimate- ? getReferenceModelPricing()- : null;- // 订阅估值按显式来源取各自的日期定价路由:内置 anthropic 走 Anthropic- // registry 参考价(含 codex 侧价格覆盖),默认/openai 保持 OpenAI 价表。- const subscriptionValueProviderId =- isCodexSubscriptionAccessRoute && sessionProvider != null- ? sessionProvider- : 'openai';- const price = isCodexXaiProviderRoute- ? getSubscriptionDirectValuePrice(pricingModel, 'codex', pricing)- : isSubscriptionValue- ? getCodexProviderSubscriptionValuePrice(- subscriptionValueProviderId,- pricingModel,- pricing,- )- : hasEffectiveGatewayRoute- ? getModelPriceQuote(pricing, 'xd', pricingModel)- : usesReferencePriceEstimate- ? getModelPriceQuote(pricing, sessionProvider, pricingModel, 'codex')- : undefined;- const money = computePriceQuoteTurnMoney(- codexUsageToTokens(u),- price ?? undefined,- currentLedgerCurrency(),- );- // Only Gateway sale prices are actual API spend. Third-party/user reference quotes- // are value estimates and daily_model_usage cannot preserve RegionalMoney.kind, so- // writing them into #billing=api would later reconstruct an estimate as actual cost.- if (!isSubscriptionValue && money && price?.source === 'gateway') {- await recordModelTurnUsage({- agentKind: 'codex',- model: modelUsageKey,- money,- inputTokensDelta: 0,- outputTokensDelta: 0,- cacheReadTokensDelta: 0,- cacheCreateTokensDelta: 0,- });+ const promptTokens = Number(u.promptTokens) || 0;+ const completionTokens = Number(u.completionTokens) || 0;+ const cachedTokens = Number(u.cachedTokens) || 0;+ void recordSessionTurnTokens(session.id, promptTokens + completionTokens + cachedTokens);+ // 先落 daily_model_usage token 行, 再等价格表补 API cost。首页 usage push 会在+ // ~2s 后刷新, 不能让冷价格表 / 离线 fetch 把模型 token 行延后到刷新之后。+ // 后续 cost-only 增量不会重复累计 token。+ void (async () => {+ let pricingModel = 'unknown';+ let turnModel = 'unknown';+ try {+ turnModel = await modelPromise;+ // 价格查表用归一化裸 id, 与 daily_model_usage 的 key 一致+ // (codex 当前不带 [1m], 归一化防御未来变体后缀导致查表 miss)。+ pricingModel = normalizeModelIdForPricing(turnModel);+ } catch {+ // 模型读取失败时仍记录 token, 聚合 UI 会归到 unknown。}- if (money && money.amount > 0) {- const isActualApiCost = !isSubscriptionValue && price?.source === 'gateway';- if (isActualApiCost) {- void recordTurnSpend(money);- void recordSessionTurnSpend(session.id, money);- }- const changedScheduleId = await recordSchedulerTurnCost({+ const isCodexBudgetRoute =+ (sessionProvider == null || sessionProvider === 'xd') &&+ pricingModel.startsWith('codex/');+ const isCodexXaiProviderRoute =+ (sessionProvider == null || sessionProvider === 'xai') &&+ pricingModel.startsWith(XAI_MODEL_PREFIX);+ const isCodexOpenAiProviderRoute =+ sessionProvider == null || sessionProvider === 'openai';+ const hasGatewayKey = Boolean(readClaudeApiKey());+ const hasEffectiveGatewayRoute =+ !isRemoteCodexSession &&+ !isCustomProviderRoute &&+ (codexAuthInjection === 'env-key' ||+ isCodexBudgetRoute ||+ (sessionProvider === 'xd' && hasGatewayKey));+ // 显式来源的订阅判定以目录 access.kind 为权威(内置 anthropic 的 Claude.ai+ // 订阅同样是订阅价值,不能只认 OpenAI/xAI);目录缺 access 的旧快照仍靠下面+ // 的 openai oauth 分支兜底。+ const sessionProviderAccessKind = sessionProvider+ ? getActiveCatalog().providers.find((provider) => provider.id === sessionProvider)+ ?.access?.kind+ : null;+ const isCodexSubscriptionAccessRoute =+ !isRemoteCodexSession &&+ sessionProvider != null &&+ sessionProvider !== 'xd' &&+ sessionProviderAccessKind === 'subscription' &&+ !hasEffectiveGatewayRoute;+ const isSubscriptionValue =+ isRemoteCodexSession ||+ isCodexXaiProviderRoute ||+ isCodexSubscriptionAccessRoute ||+ (isCodexOpenAiProviderRoute &&+ codexAuthInjection === 'oauth-bearer' &&+ !hasEffectiveGatewayRoute);+ const usesReferencePriceEstimate =+ !isSubscriptionValue &&+ !isRemoteCodexSession &&+ !hasEffectiveGatewayRoute &&+ Boolean(sessionProvider && sessionProvider !== 'xd');+ const modelUsageKey = isSubscriptionValue+ ? codexSubscriptionUsageModelKey(pricingModel)+ : codexApiUsageModelKey(pricingModel);+ await recordModelTurnUsage({+ agentKind: 'codex',+ model: modelUsageKey,+ inputTokensDelta: promptTokens,+ outputTokensDelta: completionTokens,+ cacheReadTokensDelta: cachedTokens,+ cacheCreateTokensDelta: 0,+ }).finally(() => rebroadcastCodexTodayUsage());++ // Codex SDK 不报 $, 用价格表折算。普通模型 + oauth(订阅)显示为 token 价值;api 模式和 codex/+ // 折扣模型走 gateway API, 显示为 API cost。远端 Codex 由远端 daemon+ // 路由,本机不知道远端 OAuth/API 事实,因此只显示 token 价值,不写本地+ // gateway cost。只有真实本地 API cost 写入 sessions.total_cost_usd,+ // 避免 scheduler 的 Cost 汇总混入订阅价值或远端账号消耗。+ // fire-and-forget 不阻塞事件循环;价格表走 main 端内存 + 磁盘缓存,+ // stale 快返并后台刷新,+ // 拉不到 / 模型无条目 → 只落 token 明细,UI 退回显示本轮 token。+ // 明细在 try 外构造:它只依赖上面已拿到的 token 数,价格请求抛错时也要能落。+ const turnUsageDetails = buildTurnUsageDetails({+ inputTokens: promptTokens,+ outputTokens: completionTokens,+ cacheReadTokens: cachedTokens,+ cacheCreateTokens: 0,+ model: turnModel,+ });+ const recordCodexUsageOnly = async () => {+ if (!turnAssistantPersistId) return;+ await recordTurnUsageOnMessage({sessionId: session.id,clientId: turnAssistantPersistId,- money,turnUsageDetails,- turnOrigin: event.turnOrigin,});- if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);- } else {- await recordCodexUsageOnly();- }- } catch {- // token row 已在价格请求前落库;价格失败只影响 API cost / message cost。- // 消息那一格仍要有事实可看:补落一次 token 明细。patch 是 agent_meta merge、- // 写的又是同一份明细,所以与上面成功分支重复执行也是幂等的(自身失败只 warn)。- await recordCodexUsageOnly();- }- })();- }- // 走 gateway/API 口径(同一把 XD key 的 LiteLLM 计费)的 codex turn,done 后刷新账号配额- // (与 cc 同口径, chip 显示 daily/monthly/key cost)。命中:会话显式选了 XD 网关、无 OAuth- // token 的 env-key fallback、或 codex/ 预算模型。普通 oauth 订阅没有 $ 配额,不刷。- void modelPromise- .then((model) => {- const hasGatewayKey = Boolean(readClaudeApiKey());- if (!isRemoteCodexSession &&- !isCustomProviderRoute &&- !model.startsWith(XAI_MODEL_PREFIX) &&- (codexAuthInjection === 'env-key' || model.startsWith('codex/') || (sessionProvider === 'xd' && hasGatewayKey))) {- void triggerClaudeAccountUsageRefresh();- }- })- .catch(() => {- if (sessionProvider === 'xd' && readClaudeApiKey()) {- void triggerClaudeAccountUsageRefresh();- }- });- }- // Pi done 事件同样携带 per-turn token/cache 明细。Pi 复用 Cindy 的 provider- // 路由,因此计费形态必须看 session provider,而不是把它当成一个新的计费方:- // openai / anthropic / xai → 用户订阅,显示剩余窗口 + 本对话价值;- // xd / 默认网关 → 实际 gateway cost。- // usage 事实无论价格是否可解析都持久化,保证新模型也能看到 cache 命中明细。- if (event.type === 'done' && event.source === 'pi') {- const sessionProvider = getSessionProvider(session.id);- const modelPromise =- turnModelPromiseBySession.get(session.id) ?? readSessionModelForUsage(session.id);- turnModelPromiseBySession.delete(session.id);- const rawUsage = (event.data as { usage?: unknown } | undefined)?.usage;- if (rawUsage && typeof rawUsage === 'object') {- const tokens = piUsageToTokens(rawUsage as {- inputTokens?: number;- outputTokens?: number;- cacheReadTokens?: number;- cacheCreationTokens?: number;- });- const totalTokens =- tokens.inputTokens +- tokens.outputTokens +- tokens.cacheReadTokens +- tokens.cacheCreateTokens;- void recordSessionTurnTokens(session.id, totalTokens);- void (async () => {- let turnModel = 'unknown';- try {- turnModel = await modelPromise;- } catch {- // 模型读取失败仍持久化 token/cache,模型显示为 unknown。- }- const pricingModel = normalizeModelIdForPricing(turnModel);- const effectiveProvider =- sessionProvider ??- (pricingModel.startsWith(CHATGPT_MODEL_PREFIX)- ? 'openai'- : pricingModel.startsWith(XAI_MODEL_PREFIX)- ? 'xai'- : null);- const isSubscriptionValue =- effectiveProvider === 'openai'- || effectiveProvider === 'anthropic'- || effectiveProvider === 'xai'- || isSubscriptionDirectModel(pricingModel);- const turnUsageDetails = buildTurnUsageDetails({- ...tokens,- model: turnModel,- });-- // Pi 也必须进 daily_model_usage,否则首页仪表盘会把 Pi 的- // token/cache 全部漏掉。先落 usage 事实,价格解析失败也不影响。- const modelUsageKey = isSubscriptionValue- ? piSubscriptionUsageModelKey(pricingModel)- : pricingModel;- await recordModelTurnUsage({- agentKind: 'pi',- model: modelUsageKey,- inputTokensDelta: tokens.inputTokens,- outputTokensDelta: tokens.outputTokens,- cacheReadTokensDelta: tokens.cacheReadTokens,- cacheCreateTokensDelta: tokens.cacheCreateTokens,- });- void rebroadcastTodaySpend();-- try {- // 自定义(source:'user')provider——本地 Ollama / 用户自付费兼容端点——即便- // 模型 id 与 XD 目录重名,也不能套用 XD 网关定价当作 Cindy 消费入账;只记 token- // (上方已入库),不写 money(codex review)。仅 xd / 默认网关与订阅路由计费。- const isCustomProviderRoute = isUserProviderSession(session.id);- const pricing =- isSubscriptionValue || isCustomProviderRoute- ? null- : await getGatewayModelPricingForModel();- const price =- effectiveProvider === 'openai'- || effectiveProvider === 'anthropic'- || effectiveProvider === 'xai'- ? getModelPriceQuote(null, effectiveProvider, pricingModel)- : isSubscriptionDirectModel(pricingModel)- ? getSubscriptionDirectValuePrice(pricingModel)- : isCustomProviderRoute- ? null- : getModelPriceQuote(pricing, 'xd', pricingModel);- const money = computePriceQuoteTurnMoney(- tokens,- price ?? undefined,- currentLedgerCurrency(),- );- if (money && money.amount > 0) {- if (!isSubscriptionValue) {- // token 已在上方入库;这里只补真实 API/gateway 费用,- // 避免重复累加 token。订阅价值则由 #billing=subscription 读时估算。+ };+ try {+ const pricing = isSubscriptionValue+ ? getReferenceModelPricing()+ : hasEffectiveGatewayRoute+ ? await getGatewayModelPricingForModel()+ : usesReferencePriceEstimate+ ? getReferenceModelPricing()+ : null;+ // 订阅估值按显式来源取各自的日期定价路由:内置 anthropic 走 Anthropic+ // registry 参考价(含 codex 侧价格覆盖),默认/openai 保持 OpenAI 价表。+ const subscriptionValueProviderId =+ isCodexSubscriptionAccessRoute && sessionProvider != null+ ? sessionProvider+ : 'openai';+ const price = isCodexXaiProviderRoute+ ? getSubscriptionDirectValuePrice(pricingModel, 'codex', pricing)+ : isSubscriptionValue+ ? getCodexProviderSubscriptionValuePrice(+ subscriptionValueProviderId,+ pricingModel,+ pricing,+ )+ : hasEffectiveGatewayRoute+ ? getModelPriceQuote(pricing, 'xd', pricingModel)+ : usesReferencePriceEstimate+ ? getModelPriceQuote(pricing, sessionProvider, pricingModel, 'codex')+ : undefined;+ const money = computePriceQuoteTurnMoney(+ codexUsageToTokens(u),+ price ?? undefined,+ currentLedgerCurrency(),+ );+ // Only Gateway sale prices are actual API spend. Third-party/user reference quotes+ // are value estimates and daily_model_usage cannot preserve RegionalMoney.kind, so+ // writing them into #billing=api would later reconstruct an estimate as actual cost.+ if (!isSubscriptionValue && money && price?.source === 'gateway') {await recordModelTurnUsage({- agentKind: 'pi',+ agentKind: 'codex',model: modelUsageKey,money,inputTokensDelta: 0,@@ -4192,128 +4249,283 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): voidcacheReadTokensDelta: 0,cacheCreateTokensDelta: 0,});- void recordTurnSpend(money);- void recordSessionTurnSpend(session.id, money);}- const changedScheduleId = await recordSchedulerTurnCost({- sessionId: session.id,- clientId: turnAssistantPersistId,- money,- turnUsageDetails,- turnOrigin: event.turnOrigin,- });- if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);- } else if (turnAssistantPersistId && turnUsageDetails) {- await recordTurnUsageOnMessage({- sessionId: session.id,- clientId: turnAssistantPersistId,- turnUsageDetails,- });+ if (money && money.amount > 0) {+ const isActualApiCost = !isSubscriptionValue && price?.source === 'gateway';+ if (isActualApiCost) {+ void recordTurnSpend(money);+ void recordSessionTurnSpend(session.id, money);+ }+ const changedScheduleId = await recordSchedulerTurnCost({+ sessionId: session.id,+ clientId: turnAssistantPersistId,+ money,+ turnUsageDetails,+ turnOrigin: event.turnOrigin,+ });+ if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);+ } else {+ await recordCodexUsageOnly();+ }+ } catch {+ // token row 已在价格请求前落库;价格失败只影响 API cost / message cost。+ // 消息那一格仍要有事实可看:补落一次 token 明细。patch 是 agent_meta merge、+ // 写的又是同一份明细,所以与上面成功分支重复执行也是幂等的(自身失败只 warn)。+ await recordCodexUsageOnly();}- } catch {- // 价格读取失败不能连带丢失 token/cache 事实。- if (turnAssistantPersistId && turnUsageDetails) {- await recordTurnUsageOnMessage({- sessionId: session.id,- clientId: turnAssistantPersistId,- turnUsageDetails,- });+ })();+ }+ // 走 gateway/API 口径(同一把 XD key 的 LiteLLM 计费)的 codex turn,done 后刷新账号配额+ // (与 cc 同口径, chip 显示 daily/monthly/key cost)。命中:会话显式选了 XD 网关、无 OAuth+ // token 的 env-key fallback、或 codex/ 预算模型。普通 oauth 订阅没有 $ 配额,不刷。+ void modelPromise+ .then((model) => {+ const hasGatewayKey = Boolean(readClaudeApiKey());+ if (+ !isRemoteCodexSession &&+ !isCustomProviderRoute &&+ !model.startsWith(XAI_MODEL_PREFIX) &&+ (codexAuthInjection === 'env-key' ||+ model.startsWith('codex/') ||+ (sessionProvider === 'xd' && hasGatewayKey))+ ) {+ void triggerClaudeAccountUsageRefresh();}- }+ })+ .catch(() => {+ if (sessionProvider === 'xd' && readClaudeApiKey()) {+ void triggerClaudeAccountUsageRefresh();+ }+ });+ }+ // Pi done 事件同样携带 per-turn token/cache 明细。Pi 复用 Cindy 的 provider+ // 路由,因此计费形态必须看 session provider,而不是把它当成一个新的计费方:+ // openai / anthropic / xai → 用户订阅,显示剩余窗口 + 本对话价值;+ // xd / 默认网关 → 实际 gateway cost。+ // usage 事实无论价格是否可解析都持久化,保证新模型也能看到 cache 命中明细。+ if (event.type === 'done' && event.source === 'pi') {+ const sessionProvider = getSessionProvider(session.id);+ const modelPromise =+ turnModelPromiseBySession.get(session.id) ?? readSessionModelForUsage(session.id);+ turnModelPromiseBySession.delete(session.id);+ const rawUsage = (event.data as { usage?: unknown } | undefined)?.usage;+ if (rawUsage && typeof rawUsage === 'object') {+ const tokens = piUsageToTokens(+ rawUsage as {+ inputTokens?: number;+ outputTokens?: number;+ cacheReadTokens?: number;+ cacheCreationTokens?: number;+ },+ );+ const totalTokens =+ tokens.inputTokens ++ tokens.outputTokens ++ tokens.cacheReadTokens ++ tokens.cacheCreateTokens;+ void recordSessionTurnTokens(session.id, totalTokens);+ void (async () => {+ let turnModel = 'unknown';+ try {+ turnModel = await modelPromise;+ } catch {+ // 模型读取失败仍持久化 token/cache,模型显示为 unknown。+ }+ const pricingModel = normalizeModelIdForPricing(turnModel);+ const effectiveProvider =+ sessionProvider ??+ (pricingModel.startsWith(CHATGPT_MODEL_PREFIX)+ ? 'openai'+ : pricingModel.startsWith(XAI_MODEL_PREFIX)+ ? 'xai'+ : null);+ const isSubscriptionValue =+ effectiveProvider === 'openai' ||+ effectiveProvider === 'anthropic' ||+ effectiveProvider === 'xai' ||+ isSubscriptionDirectModel(pricingModel);+ const turnUsageDetails = buildTurnUsageDetails({+ ...tokens,+ model: turnModel,+ });- if (effectiveProvider === 'openai') {- triggerCodexAccountUsageRefresh();- } else if (effectiveProvider === 'anthropic') {- triggerClaudeSubscriptionUsageRefresh();- } else if (effectiveProvider === 'xd' || effectiveProvider == null) {- void triggerClaudeAccountUsageRefresh();- }- // xAI 没有独立订阅窗口端点;Responses bridge 从响应 headers 实时更新- // useXaiRateLimit 消费的快照,无需额外网络请求。- })();+ // Pi 也必须进 daily_model_usage,否则首页仪表盘会把 Pi 的+ // token/cache 全部漏掉。先落 usage 事实,价格解析失败也不影响。+ const modelUsageKey = isSubscriptionValue+ ? piSubscriptionUsageModelKey(pricingModel)+ : pricingModel;+ await recordModelTurnUsage({+ agentKind: 'pi',+ model: modelUsageKey,+ inputTokensDelta: tokens.inputTokens,+ outputTokensDelta: tokens.outputTokens,+ cacheReadTokensDelta: tokens.cacheReadTokens,+ cacheCreateTokensDelta: tokens.cacheCreateTokens,+ });+ void rebroadcastTodaySpend();++ try {+ // 自定义(source:'user')provider——本地 Ollama / 用户自付费兼容端点——即便+ // 模型 id 与 XD 目录重名,也不能套用 XD 网关定价当作 Cindy 消费入账;只记 token+ // (上方已入库),不写 money(codex review)。仅 xd / 默认网关与订阅路由计费。+ const isCustomProviderRoute = isUserProviderSession(session.id);+ const pricing =+ isSubscriptionValue || isCustomProviderRoute+ ? null+ : await getGatewayModelPricingForModel();+ const price =+ effectiveProvider === 'openai' ||+ effectiveProvider === 'anthropic' ||+ effectiveProvider === 'xai'+ ? getModelPriceQuote(null, effectiveProvider, pricingModel)+ : isSubscriptionDirectModel(pricingModel)+ ? getSubscriptionDirectValuePrice(pricingModel)+ : isCustomProviderRoute+ ? null+ : getModelPriceQuote(pricing, 'xd', pricingModel);+ const money = computePriceQuoteTurnMoney(+ tokens,+ price ?? undefined,+ currentLedgerCurrency(),+ );+ if (money && money.amount > 0) {+ if (!isSubscriptionValue) {+ // token 已在上方入库;这里只补真实 API/gateway 费用,+ // 避免重复累加 token。订阅价值则由 #billing=subscription 读时估算。+ await recordModelTurnUsage({+ agentKind: 'pi',+ model: modelUsageKey,+ money,+ inputTokensDelta: 0,+ outputTokensDelta: 0,+ cacheReadTokensDelta: 0,+ cacheCreateTokensDelta: 0,+ });+ void recordTurnSpend(money);+ void recordSessionTurnSpend(session.id, money);+ }+ const changedScheduleId = await recordSchedulerTurnCost({+ sessionId: session.id,+ clientId: turnAssistantPersistId,+ money,+ turnUsageDetails,+ turnOrigin: event.turnOrigin,+ });+ if (changedScheduleId) broadcastSchedulerChanged(changedScheduleId);+ } else if (turnAssistantPersistId && turnUsageDetails) {+ await recordTurnUsageOnMessage({+ sessionId: session.id,+ clientId: turnAssistantPersistId,+ turnUsageDetails,+ });+ }+ } catch {+ // 价格读取失败不能连带丢失 token/cache 事实。+ if (turnAssistantPersistId && turnUsageDetails) {+ await recordTurnUsageOnMessage({+ sessionId: session.id,+ clientId: turnAssistantPersistId,+ turnUsageDetails,+ });+ }+ }++ if (effectiveProvider === 'openai') {+ triggerCodexAccountUsageRefresh();+ } else if (effectiveProvider === 'anthropic') {+ triggerClaudeSubscriptionUsageRefresh();+ } else if (effectiveProvider === 'xd' || effectiveProvider == null) {+ void triggerClaudeAccountUsageRefresh();+ }+ // xAI 没有独立订阅窗口端点;Responses bridge 从响应 headers 实时更新+ // useXaiRateLimit 消费的快照,无需额外网络请求。+ })();+ }}- }- }));- registration.disposers.push(session.onStatusChange((status) => {- if (wiredSessionsById.get(session.id)?.session !== session) return;- // The local window broadcast is best-effort, but keep this guard here as- // well because status callbacks are a lifecycle boundary: a third-party- // bridge must not be able to skip session cleanup by throwing.- try {- broadcastToAllWindows(MAKER_PUSH.STATUS_CHANGED, { sessionId: session.id, status });- } catch (err) {- log.warn('session status broadcast failed', {- sessionId: session.id,- status,- error: err instanceof Error ? err.message : String(err),- });- }- if (status === 'closed') {+ }),+ );+ registration.disposers.push(+ session.onStatusChange((status) => {+ if (wiredSessionsById.get(session.id)?.session !== session) return;+ // The local window broadcast is best-effort, but keep this guard here as+ // well because status callbacks are a lifecycle boundary: a third-party+ // bridge must not be able to skip session cleanup by throwing.try {- cleanupPendingInteractionsForSession(session.id, 'session_closed');- // 会话关闭同样是"终止":退避窗口有 3–20 秒,期间会话可能被独立关掉(切 agent、- // 远端断开、宿主回收)。只清 coordinator 不够 —— 排期中的定时器与悬空的重连记录- // 都还活着,前者会到点往已关闭的会话补发消息(coordinator 关闭路径保留 recovery,- // 补发会把用户关掉的会话重新拉起来),后者会把结果错绑到下一个会话实例(codex P1)。- interruptedTurnAutoResumeGuard.noteSessionReset(session.id);- autoResumeBookkeeping.teardown(session.id);- agentInputCoordinatorHolder?.onSessionClosed(session.id);- // 会话关闭:兑现延迟凭证切换(直接写 route),并唤醒被它挡住的等待者。- pendingCredentialSwitchHolder?.onSessionClosed(session.id);- deferredCodexRestartHolder?.onSessionSettled();- agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);- refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);- gitSnapshotCoordinator?.onSessionClosed(session.id);- clearOrcaMcpHydrated(session.id);- knownNonOrcaSessionIds.delete(session.id);- lastReportedCostUsdBySession.delete(session.id);- lastReportedModelUsageBySession.delete(session.id);- turnModelPromiseBySession.delete(session.id);- // 后台活动检测:会话进程已关闭(closeSession / 删除),清账并广播横幅熄灭。- clearClaudeSessionBackgroundActivity(session.id);- clearSessionPersistState(session.id);- // 进程关闭 ≠ 通知作废:临时会话调度(非 heartbeat / 非 persistentSession)在 run- // 终态后立刻 closeSession,此刻完成卡片刚在灵动岛上弹出来。硬删条目会让它当场- // 消失,所以这条路径保留仍在展示的卡片,由 dwell 到期或用户 ack 收掉。- handleAgentIslandSessionClosedAfterCleanup(session.id, 'process-closed');+ broadcastToAllWindows(MAKER_PUSH.STATUS_CHANGED, { sessionId: session.id, status });} catch (err) {- log.warn('session close cleanup failed; forcing idle reconciliation', {+ log.warn('session status broadcast failed', {sessionId: session.id,+ status,error: err instanceof Error ? err.message : String(err),});- } finally {- // Wiring teardown is independent of the best-effort product cleanup- // above. A single disposer or listener error must not leave a closed- // session reachable from the in-memory routing map.- cancelDirectAbortReconciliation(session.id);- pendingFailedTurnAssistantPersistId.delete(session.id);- wiredSessionsById.delete(session.id);- for (const dispose of registration.disposers) {+ }+ if (status === 'closed') {+ try {+ cleanupPendingInteractionsForSession(session.id, 'session_closed');+ // 会话关闭同样是"终止":退避窗口有 3–20 秒,期间会话可能被独立关掉(切 agent、+ // 远端断开、宿主回收)。只清 coordinator 不够 —— 排期中的定时器与悬空的重连记录+ // 都还活着,前者会到点往已关闭的会话补发消息(coordinator 关闭路径保留 recovery,+ // 补发会把用户关掉的会话重新拉起来),后者会把结果错绑到下一个会话实例(codex P1)。+ interruptedTurnAutoResumeGuard.noteSessionReset(session.id);+ autoResumeBookkeeping.teardown(session.id);+ agentInputCoordinatorHolder?.onSessionClosed(session.id);+ // 会话关闭:兑现延迟凭证切换(直接写 route),并唤醒被它挡住的等待者。+ pendingCredentialSwitchHolder?.onSessionClosed(session.id);+ deferredCodexRestartHolder?.onSessionSettled();+ agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);+ refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);+ gitSnapshotCoordinator?.onSessionClosed(session.id);+ clearOrcaMcpHydrated(session.id);+ knownNonOrcaSessionIds.delete(session.id);+ lastReportedCostUsdBySession.delete(session.id);+ lastReportedModelUsageBySession.delete(session.id);+ turnModelPromiseBySession.delete(session.id);+ // 后台活动检测:会话进程已关闭(closeSession / 删除),清账并广播横幅熄灭。+ clearClaudeSessionBackgroundActivity(session.id);+ clearSessionPersistState(session.id);+ // 进程关闭 ≠ 通知作废:临时会话调度(非 heartbeat / 非 persistentSession)在 run+ // 终态后立刻 closeSession,此刻完成卡片刚在灵动岛上弹出来。硬删条目会让它当场+ // 消失,所以这条路径保留仍在展示的卡片,由 dwell 到期或用户 ack 收掉。+ handleAgentIslandSessionClosedAfterCleanup(session.id, 'process-closed');+ } catch (err) {+ log.warn('session close cleanup failed; forcing idle reconciliation', {+ sessionId: session.id,+ error: err instanceof Error ? err.message : String(err),+ });+ } finally {+ // Wiring teardown is independent of the best-effort product cleanup+ // above. A single disposer or listener error must not leave a closed+ // session reachable from the in-memory routing map.+ cancelDirectAbortReconciliation(session.id);+ pendingFailedTurnAssistantPersistId.delete(session.id);+ wiredSessionsById.delete(session.id);+ for (const dispose of registration.disposers) {+ try {+ dispose();+ } catch (err) {+ log.warn('session disposer failed during close teardown', {+ sessionId: session.id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }try {- dispose();+ session.setInteractionListener(null);} catch (err) {- log.warn('session disposer failed during close teardown', {+ log.warn('session interaction listener teardown failed', {sessionId: session.id,error: err instanceof Error ? err.message : String(err),});}+ // This must run even when an owner-boundary-sensitive cleanup above+ // rejects. A closed Session cannot keep the desktop turn boundary busy.+ sessionTurnActivityTracker.deleteSession(session.id);+ sessionTurnBoundaryGenerationById.delete(session.id);+ markSessionTurnEnded(session.id);}- try {- session.setInteractionListener(null);- } catch (err) {- log.warn('session interaction listener teardown failed', {- sessionId: session.id,- error: err instanceof Error ? err.message : String(err),- });- }- // This must run even when an owner-boundary-sensitive cleanup above- // rejects. A closed Session cannot keep the desktop turn boundary busy.- sessionTurnActivityTracker.deleteSession(session.id);- sessionTurnBoundaryGenerationById.delete(session.id);- markSessionTurnEnded(session.id);}- }- }));+ }),+ );// 注入 interaction listener (permission/ask/plan 三合一,renderer 按 kind 弹不同 UI)installDesktopInteractionListener(session);@@ -4341,7 +4553,9 @@ export interface RegisterMakerIpcOptions {export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): void {log.info('registering maker:* IPC handlers');getAgentIslandService()?.setPermissionResolver(resolvePendingPermissionFromAgentIsland);- sessionTurnActivityTracker.setTurnKeepaliveChangeListener(options.onAnySessionTurnKeepaliveChange ?? null);+ sessionTurnActivityTracker.setTurnKeepaliveChangeListener(+ options.onAnySessionTurnKeepaliveChange ?? null,+ );gitSnapshotCoordinator = createGitSnapshotCoordinator(maker);// 接上 DB 改名通知(用户手动改名后自动起名收手)与拦截意识探针(装了// will-user-message 钩子时不把用户原话送去标题模型)。@@ -4386,10 +4600,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (!payload || typeof payload !== 'object') return;const p = payload as Partial<NewMakerDraftSnapshot>;if (- !p.lastByVendor || typeof p.lastByVendor !== 'object'- || !p.fastModeByModel || typeof p.fastModeByModel !== 'object'- || !p.effortByModel || typeof p.effortByModel !== 'object'- ) return;+ !p.lastByVendor ||+ typeof p.lastByVendor !== 'object' ||+ !p.fastModeByModel ||+ typeof p.fastModeByModel !== 'object' ||+ !p.effortByModel ||+ typeof p.effortByModel !== 'object'+ )+ return;setNewMakerDraftCache({lastByVendor: p.lastByVendor,fastModeByModel: p.fastModeByModel,@@ -4600,9 +4818,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)registerNewMakerWorktreePreferenceHandler(createElectronIpcHandlerRegistry(), {isDeviceLinkInvoke,assertTrustedCaller: (event) =>- assertTrustedAppRendererEvent(- event as Parameters<typeof assertTrustedAppRendererEvent>[0],- ),+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]),broadcast: broadcastToAllWindows,});@@ -4660,11 +4876,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)fast?: unknown;};if (- typeof p.sessionId !== 'string' || !p.sessionId- || (p.agent !== 'claude-code' && p.agent !== 'codex' && p.agent !== 'pi')- || typeof p.providerId !== 'string' || !p.providerId- || typeof p.model !== 'string' || !p.model- ) return;+ typeof p.sessionId !== 'string' ||+ !p.sessionId ||+ (p.agent !== 'claude-code' && p.agent !== 'codex' && p.agent !== 'pi') ||+ typeof p.providerId !== 'string' ||+ !p.providerId ||+ typeof p.model !== 'string' ||+ !p.model+ )+ return;tapWindowBroadcast(MAKER_PUSH.SESSION_MODEL_PREF_CHANGED, {sessionId: p.sessionId,agent: p.agent,@@ -4690,10 +4910,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)refreshBuiltinProviderModels(providerId, {refreshXd: options.refreshXdGatewayModels,refreshAnthropic: refreshAnthropicModelsFromHttp,- refreshOpenAi: () => maker.refreshAgentLocalModels(- 'codex',- { credentialMode: 'oauth-bearer' },- ),+ refreshOpenAi: () =>+ maker.refreshAgentLocalModels('codex', { credentialMode: 'oauth-bearer' }),refreshXaiCatalog: async () => {await refreshActiveCatalogFromSource();},@@ -4769,20 +4987,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const oauth = provider?.auth.oauth;if (!provider || !oauth) throw new Error(`provider '${providerId}' has no oauth descriptor`);let rollbackCredentials: (() => boolean) | undefined;- const result = await runGenericOAuthLogin(- { id: provider.id, name: provider.name },- oauth,- {- onProgress: (progress) =>- broadcastToAllWindows(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {- providerId,- ...progress,- }),- onCredentialPersisted: (rollback) => {- rollbackCredentials = rollback;- },+ const result = await runGenericOAuthLogin({ id: provider.id, name: provider.name }, oauth, {+ onProgress: (progress) =>+ broadcastToAllWindows(MAKER_PUSH.PROVIDER_OAUTH_PROGRESS, {+ providerId,+ ...progress,+ }),+ onCredentialPersisted: (rollback) => {+ rollbackCredentials = rollback;},- );+ });if (result.ok && isCurrent()) {// 授权成功后按 agent 自动发现模型(与内置订阅体验统一,用户不必手填模型):// 发现端点 = 描述符显式声明 ?? 由该 runtime 的 baseUrl 推导(…/v1/models)。@@ -4797,11 +5011,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)for (const agent of provider.agents) {if (!isCurrent()) break;const upstream = provider.routing[agent]?.upstream;- const url = oauth.modelsDiscoveryUrl ?? (upstream ? deriveModelsDiscoveryUrl(upstream) : null);+ const url =+ oauth.modelsDiscoveryUrl ?? (upstream ? deriveModelsDiscoveryUrl(upstream) : null);if (!url) continue;// 去重键含 agent:发现请求头按 wire 分派(cc 带 anthropic-version),同 URL 不同 wire 不能共用响应。const key = `${agent}\n${url}`;- if (!fetched.has(key)) fetched.set(key, await discoverGenericOAuthModels(providerId, oauth, url, agent));+ if (!fetched.has(key))+ fetched.set(key, await discoverGenericOAuthModels(providerId, oauth, url, agent));if (!isCurrent()) break;const models = fetched.get(key);if (!models || models.length === 0) continue;@@ -4859,8 +5075,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}},oauthCancel: (providerId) => cancelGenericOAuthLogin(providerId),- removeOAuthCredentials: (providerId) =>- removeGenericOAuthCredentialsReversibly(providerId),+ removeOAuthCredentials: (providerId) => removeGenericOAuthCredentialsReversibly(providerId),});// 自定义 MCP 服务器 CRUD —— CRUD 成功后刷新两个 agent 的 mcpProviders 数组@@ -4963,81 +5178,97 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)ipcMain.handle(MAKER_INVOKE.LIST_AGENT_COMMANDS, (_e, agentKind: unknown) => {try {return { success: true, commands: maker.listAgentCommands(requireAgentKind(agentKind)) };- } catch (err) {- return { success: false, error: err instanceof Error ? err.message : String(err), commands: [] };- }- });-- ipcMain.handle(MAKER_INVOKE.LIST_AGENT_SKILLS, async (_e, agentKind: unknown, params: unknown) => {- try {- const kind = requireAgentKind(agentKind);- const skillParams = (params ?? {}) as { workingDir?: string; forceReload?: boolean };- const linksChanged = await prepareProjectSkillLinksFailSoft(skillParams?.workingDir);- if (kind === 'codex' && linksChanged) {- skillParams.forceReload = true;- }- if (kind === 'codex') {- await desktopCodexAuthAdapter.ensureGlobalCodexAssets();- } else if (kind === 'claude-code') {- await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();- }- const result = await maker.listAgentSkills(- kind,- skillParams,- );- return { success: true, ...result };- } catch (err) {- return { success: false, error: err instanceof Error ? err.message : String(err), skills: [] };- }- });-- ipcMain.handle(MAKER_INVOKE.SCAN_AT_RESOURCES, async (_e, agentKind: unknown, params: unknown) => {- try {- const resourceParams = params as { workingDir: string; cap?: number; query?: string };- await prepareProjectSkillLinksFailSoft(resourceParams?.workingDir);- const kind = requireAgentKind(agentKind);- const includeProjectAgents = supportsAtProjectAgentResources(kind);- const [result, customizationResult] = await Promise.all([- maker.scanAtResources(kind, resourceParams),- includeProjectAgents- ? maker.listCustomizations({- agentKind: 'claude-code',- workingDirs: [resourceParams.workingDir],- kinds: ['agent'],- }).catch((err: unknown) => {- log.warn('Project Agent @ catalog failed; keeping workspace resources available', err);- return null;- })- : Promise.resolve(null),- ]);- const projectAgents = customizationResult- ? listAtProjectAgentResources(- customizationResult.items,- resourceParams.workingDir,- resourceParams.query,- )- : [];- const merged = finalizeAtProjectAgentResources(- kind,- result.items,- projectAgents,- resourceParams.cap,- );- return {- success: true,- items: merged.items,- truncated: result.truncated || merged.capped,- };} catch (err) {return {success: false,error: err instanceof Error ? err.message : String(err),- items: [],- truncated: false,+ commands: [],};}});+ ipcMain.handle(+ MAKER_INVOKE.LIST_AGENT_SKILLS,+ async (_e, agentKind: unknown, params: unknown) => {+ try {+ const kind = requireAgentKind(agentKind);+ const skillParams = (params ?? {}) as { workingDir?: string; forceReload?: boolean };+ const linksChanged = await prepareProjectSkillLinksFailSoft(skillParams?.workingDir);+ if (kind === 'codex' && linksChanged) {+ skillParams.forceReload = true;+ }+ if (kind === 'codex') {+ await desktopCodexAuthAdapter.ensureGlobalCodexAssets();+ } else if (kind === 'claude-code') {+ await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();+ }+ const result = await maker.listAgentSkills(kind, skillParams);+ return { success: true, ...result };+ } catch (err) {+ return {+ success: false,+ error: err instanceof Error ? err.message : String(err),+ skills: [],+ };+ }+ },+ );++ ipcMain.handle(+ MAKER_INVOKE.SCAN_AT_RESOURCES,+ async (_e, agentKind: unknown, params: unknown) => {+ try {+ const resourceParams = params as { workingDir: string; cap?: number; query?: string };+ await prepareProjectSkillLinksFailSoft(resourceParams?.workingDir);+ const kind = requireAgentKind(agentKind);+ const includeProjectAgents = supportsAtProjectAgentResources(kind);+ const [result, customizationResult] = await Promise.all([+ maker.scanAtResources(kind, resourceParams),+ includeProjectAgents+ ? maker+ .listCustomizations({+ agentKind: 'claude-code',+ workingDirs: [resourceParams.workingDir],+ kinds: ['agent'],+ })+ .catch((err: unknown) => {+ log.warn(+ 'Project Agent @ catalog failed; keeping workspace resources available',+ err,+ );+ return null;+ })+ : Promise.resolve(null),+ ]);+ const projectAgents = customizationResult+ ? listAtProjectAgentResources(+ customizationResult.items,+ resourceParams.workingDir,+ resourceParams.query,+ )+ : [];+ const merged = finalizeAtProjectAgentResources(+ kind,+ result.items,+ projectAgents,+ resourceParams.cap,+ );+ return {+ success: true,+ items: merged.items,+ truncated: result.truncated || merged.capped,+ };+ } catch (err) {+ return {+ success: false,+ error: err instanceof Error ? err.message : String(err),+ items: [],+ truncated: false,+ };+ }+ },+ );+ipcMain.handle(MAKER_INVOKE.AT_CONTEXT_LIST, async (event, payload: unknown) => {assertTrustedAppRendererEvent(event);const request = parseAtContextCatalogRequest(payload);@@ -5125,7 +5356,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)function buildCreateOptsWithStderr(o: CreateOpts) {// 把 vendor 子进程 stderr 引到主进程日志,否则 "process exited with code 1" 之类// 的失败信息会被默默丢掉。renderer 仍可以通过 vendorOptions 自定义,这里只在缺省时兜底。- return withCreateSessionStderr(o, (agentKind, line) => log.warn(`[${agentKind}/stderr] ${line}`));+ return withCreateSessionStderr(o, (agentKind, line) =>+ log.warn(`[${agentKind}/stderr] ${line}`),+ );}function isSessionRunningError(err: unknown): boolean {@@ -5169,7 +5402,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}function orcaSessionStatus(sessionId: string): string {- const session = maker.getSession(sessionId) as ({ getStatus?: () => string } | null);+ const session = maker.getSession(sessionId) as { getStatus?: () => string } | null;return session?.getStatus?.() ?? 'not_running';}@@ -5178,11 +5411,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const [row] = await db.select({ content: messages.content }).from(messages)- .where(and(- eq(messages.sessionId, workerSessionId),- eq(messages.role, 'assistant'),- isNull(messages.rewindAt),- ))+ .where(+ and(+ eq(messages.sessionId, workerSessionId),+ eq(messages.role, 'assistant'),+ isNull(messages.rewindAt),+ ),+ ).orderBy(desc(messages.createdAt), desc(messages.id)).limit(1);return visibleMessageTextForConversationSearch('assistant', row?.content ?? '');@@ -5371,9 +5606,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions).where(eq(sessions.id, o.id)).limit(1);verifiedResume =- !!row &&- row.model === o.model &&- (row.providerId ?? null) === (o.providerId ?? null);+ !!row && row.model === o.model && (row.providerId ?? null) === (o.providerId ?? null);} catch {verifiedResume = false;}@@ -5403,10 +5636,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sessionId: session.id,providerId: o.providerId,updateProviderId: async (targetSessionId, providerId) => {- await db- .update(sessions)- .set({ providerId })- .where(eq(sessions.id, targetSessionId));+ await db.update(sessions).set({ providerId }).where(eq(sessions.id, targetSessionId));},readProviderId: async (targetSessionId) => {const [pRow] = await db@@ -5469,7 +5699,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (live) return false;const db = getDbClient().drizzle;- const [row] = await db.select().from(sessions).where(eq(sessions.id, target.sessionId)).limit(1);+ const [row] = await db+ .select()+ .from(sessions)+ .where(eq(sessions.id, target.sessionId))+ .limit(1);if (!row) return false;const workerVendorOptions = {@@ -5565,9 +5799,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// remoteHostId 创建后不变,进程内缓存安全。const sessionIdForLookup =(session as { id?: string } | null | undefined)?.id ??- (createOpts && typeof createOpts === 'object'- ? (createOpts as { id?: unknown }).id- : null);+ (createOpts && typeof createOpts === 'object' ? (createOpts as { id?: unknown }).id : null);if (typeof sessionIdForLookup === 'string' && sessionIdForLookup) {remoteHostIdToEnsure = await readSessionRemoteHostIdCached(sessionIdForLookup);}@@ -5575,7 +5807,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (!remoteHostIdToEnsure) return;if (createOpts && typeof createOpts === 'object') {- const mutableCreateOpts = createOpts as { remoteHostId?: string; makerMemoryEnabled?: boolean };+ const mutableCreateOpts = createOpts as {+ remoteHostId?: string;+ makerMemoryEnabled?: boolean;+ };mutableCreateOpts.remoteHostId = remoteHostIdToEnsure;// SSH remote 与本地同语义:Maker Memory 跟随控制端设置 (scope 由// maker-core 按 remoteHostId+workingDir 隔离)。调用方显式给的值优先@@ -5593,7 +5828,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await ensureRemoteHostReady(remoteHostIdToEnsure);const ensureAgentKind: 'claude-code' | 'codex' | 'pi' | null =- session?.agentKind === 'codex' || session?.agentKind === 'claude-code' || session?.agentKind === 'pi'+ session?.agentKind === 'codex' ||+ session?.agentKind === 'claude-code' ||+ session?.agentKind === 'pi'? session.agentKind: createOpts && typeof createOpts === 'object'? (() => {@@ -5645,8 +5882,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// Maker Memory 全局开着时把 cindy_memory 一并注入远端 daemon config。isMakerMemoryEnabled: () => maker.makerMemory?.isEnabled() ?? false,});- if (result.ok && result.daemonRebootstrapped && !codexRemoteHasLiveTurn(remoteHostIdToEnsure)) {- await detachIdleRemoteCodexSessionsOnHost(remoteHostIdToEnsure, 'codex-mcp-daemon-rebootstrap');+ if (+ result.ok &&+ result.daemonRebootstrapped &&+ !codexRemoteHasLiveTurn(remoteHostIdToEnsure)+ ) {+ await detachIdleRemoteCodexSessionsOnHost(+ remoteHostIdToEnsure,+ 'codex-mcp-daemon-rebootstrap',+ );return { remoteCodexDaemonRebootstrapped: true };}}@@ -5665,12 +5909,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 声明消除整类风险 (reviewer R27 指出;当前调用点虽均在初始化后, 不// 留隐患)。function codexRemoteHasLiveTurn(hostId: string): boolean {- return maker.listActiveSessions().some(- (s) =>- s.remoteHostId === hostId &&- s.agentKind === 'codex' &&- (agentInputCoordinatorHolder?.hasActiveTurnForRewind(s.id) ?? false),- );+ return maker+ .listActiveSessions()+ .some(+ (s) =>+ s.remoteHostId === hostId &&+ s.agentKind === 'codex' &&+ (agentInputCoordinatorHolder?.hasActiveTurnForRewind(s.id) ?? false),+ );}setRemoteCodexLiveTurnChecker(codexRemoteHasLiveTurn);// agent-proxy 的漂移应用 (重启 daemon / 迁移拆除隧道) 会打断该 host 上@@ -5678,16 +5924,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 必须两个通道都看 (R3 review P1), 不能沿用 MCP ensure 的 codex-only// 判定 (那边 daemon 重启只影响 codex, 语义不同)。function remoteAgentHasLiveTurn(hostId: string): boolean {- return maker.listActiveSessions().some(- (s) =>- s.remoteHostId === hostId &&- (s.agentKind === 'codex' || s.agentKind === 'claude-code') &&- (agentInputCoordinatorHolder?.hasActiveTurnForRewind(s.id) ?? false),- );+ return maker+ .listActiveSessions()+ .some(+ (s) =>+ s.remoteHostId === hostId &&+ (s.agentKind === 'codex' || s.agentKind === 'claude-code') &&+ (agentInputCoordinatorHolder?.hasActiveTurnForRewind(s.id) ?? false),+ );}setAgentProxyLiveTurnChecker(remoteAgentHasLiveTurn);- async function detachIdleRemoteCodexSessionsOnHost(hostId: string, reason: string): Promise<void> {+ async function detachIdleRemoteCodexSessionsOnHost(+ hostId: string,+ reason: string,+ ): Promise<void> {const detachTasks: Array<Promise<void>> = [];for (const s of maker.listActiveSessions()) {if (s.remoteHostId !== hostId || s.agentKind !== 'codex') continue;@@ -5746,7 +5997,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)).then(async (result) => {if (result?.ok && result.daemonRebootstrapped && !codexRemoteHasLiveTurn(remoteHostId)) {- await detachIdleRemoteCodexSessionsOnHost(remoteHostId, 'codex-mcp-turn-settled-rebootstrap');+ await detachIdleRemoteCodexSessionsOnHost(+ remoteHostId,+ 'codex-mcp-turn-settled-rebootstrap',+ );}});return;@@ -5758,52 +6012,47 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)};const makerSessionRegistry = createElectronIpcHandlerRegistry();- registerMakerSessionCreateHandler(- makerSessionRegistry,- {- // CREATE_SESSION 同样先走 remote ensure:remote draft (尤其 collab- // lead) 的 SSH 重连 / agent 安装 / codex daemon MCP 注入必须先于- // bootstrap, 否则 lead 首个 turn 没有 cindy_orca, 与 orca 架构文档的- // "session start/resume 前置" 契约不符。本地会话 ensure 内部直接返回。- bootstrapSession: async (co) => {- await ensureRemoteReadyForSessionStart({ createOpts: co });- return bootstrapSession(co);- },- markOrcaRoleIfNeeded,- markKnownNonOrcaIfApplicable,- allocateDialogueWorkspace: ensureDialogueWorkspaceDir,- createSessionId: createId,- now: Date.now,- withSessionLock: withSendToSessionLock,- sendWorkerReadyMessage: (session) => {- // Orca worker 首次创建时发一条初始化消息,强制 codex 写 rollout 文件,- // 避免 app 重启后 thread/resume 因 rollout 缺失而失败。- observeFireAndForgetSendOutcome(- session.send({ type: 'user', content: ORCA_WORKER_READY_MESSAGE }, { planMode: false }),- {- owner: 'orca-worker-ready',- entrypoint: 'CREATE_SESSION',- sessionId: session.id,- agentKind: session.agentKind,- action: 'worker-ready-placeholder',- context: `CREATE_SESSION/${session.id}/worker-ready-placeholder`,- },- );- },- broadcastSessionCreated,- logCreateSession: (fields) => log.info('create-session invoked', fields),- warnStderr: (agentKind, line) => log.warn(`[${agentKind}/stderr] ${line}`),+ registerMakerSessionCreateHandler(makerSessionRegistry, {+ // CREATE_SESSION 同样先走 remote ensure:remote draft (尤其 collab+ // lead) 的 SSH 重连 / agent 安装 / codex daemon MCP 注入必须先于+ // bootstrap, 否则 lead 首个 turn 没有 cindy_orca, 与 orca 架构文档的+ // "session start/resume 前置" 契约不符。本地会话 ensure 内部直接返回。+ bootstrapSession: async (co) => {+ await ensureRemoteReadyForSessionStart({ createOpts: co });+ return bootstrapSession(co);},- );+ markOrcaRoleIfNeeded,+ markKnownNonOrcaIfApplicable,+ allocateDialogueWorkspace: ensureDialogueWorkspaceDir,+ createSessionId: createId,+ now: Date.now,+ withSessionLock: withSendToSessionLock,+ sendWorkerReadyMessage: (session) => {+ // Orca worker 首次创建时发一条初始化消息,强制 codex 写 rollout 文件,+ // 避免 app 重启后 thread/resume 因 rollout 缺失而失败。+ observeFireAndForgetSendOutcome(+ session.send({ type: 'user', content: ORCA_WORKER_READY_MESSAGE }, { planMode: false }),+ {+ owner: 'orca-worker-ready',+ entrypoint: 'CREATE_SESSION',+ sessionId: session.id,+ agentKind: session.agentKind,+ action: 'worker-ready-placeholder',+ context: `CREATE_SESSION/${session.id}/worker-ready-placeholder`,+ },+ );+ },+ broadcastSessionCreated,+ logCreateSession: (fields) => log.info('create-session invoked', fields),+ warnStderr: (agentKind, line) => log.warn(`[${agentKind}/stderr] ${line}`),+ });registerPrecreatedWorktreeDiscardHandler(makerSessionRegistry, {assertCaller: (event) => {// device-link 的真实调用身份由 invoke async context + allowlist 证明;本机直调仍// 必须来自 Cindy 自有顶层 Renderer,不能把删除能力交给 WebView/Ghost。if (!isDeviceLinkInvoke()) {- assertTrustedAppRendererEvent(- event as Parameters<typeof assertTrustedAppRendererEvent>[0],- );+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);}},withSessionLock: withSendToSessionLock,@@ -5819,11 +6068,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)discard: (sessionId, expectedPath, options) =>worktreeManager.discardPrecreatedWorktree(sessionId, expectedPath, options),discardByRecoveryKey: (sessionId, recoveryKey, options) =>- worktreeManager.discardPrecreatedWorktreeByRecoveryKey(- sessionId,- recoveryKey,- options,- ),+ worktreeManager.discardPrecreatedWorktreeByRecoveryKey(sessionId, recoveryKey, options),});// turn 运行中登记的切换意图(下一条消息发送时刻由 send 事务 apply)。@@ -5904,7 +6149,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},getLiveSession: (sessionId) => maker.getSession(sessionId),closeSession: (sessionId) => maker.closeSession(sessionId, 'agent-switch'),- listMessagesForHandoff: (sessionId, after) => listMessagesForAgentHandoff(sessionId, 400, after),+ listMessagesForHandoff: (sessionId, after) =>+ listMessagesForAgentHandoff(sessionId, 400, after),findParkedEngineSession: (sessionId, targetDbKind) =>findParkedEngineSession(sessionId, targetDbKind),applyAgentSwitchToDb: applyAgentSwitchToSessionRow,@@ -5978,8 +6224,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)registerMakerSessionAgentSwitchHandler(makerSessionRegistry, agentSwitchDeps);registerMakerMessageDeleteHandler(makerSessionRegistry, {getSessionRow: async (sessionId) => {- const [row] = await getDbClient().drizzle- .select({ status: sessions.status, agentKind: sessions.agentKind })+ const [row] = await getDbClient()+ .drizzle.select({ status: sessions.status, agentKind: sessions.agentKind }).from(sessions).where(eq(sessions.id, sessionId)).limit(1);@@ -6095,7 +6341,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)typeof leadRow?.workingDir === 'string' ? leadRow.workingDir : lead?.workDir;const normalizedWorkingDir =typeof rawWorkingDir === 'string'- ? normalizeWorkingDirForProjectSettings(rawWorkingDir) ?? rawWorkingDir+ ? (normalizeWorkingDirForProjectSettings(rawWorkingDir) ?? rawWorkingDir): rawWorkingDir;const liveWorkspaceKind = (lead as { workspaceKind?: unknown } | undefined)?.workspaceKind;const workspaceKind =@@ -6110,8 +6356,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentKind: lead?.agentKind ?? leadRow?.agentKind ?? null,},(pluginId, workingDir) => getPluginRegistry().isEnabled(pluginId, workingDir),- (workingDir) =>- matchDialogueWorkspacePath(workingDir, dialogueWorkspaceRootDir()) !== null,+ (workingDir) => matchDialogueWorkspacePath(workingDir, dialogueWorkspaceRootDir()) !== null,);}@@ -6128,7 +6373,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)let baselineStarted = false;const pendingHandoff = await agentHandoffPending.peek(session.id);const outgoingMessage: UserMessage = pendingHandoff- ? (prependHandoffToUserMessage({ type: 'user', content: message }, pendingHandoff) as UserMessage)+ ? (prependHandoffToUserMessage(+ { type: 'user', content: message },+ pendingHandoff,+ ) as UserMessage): { type: 'user', content: message };try {const sendResult = await session.send(outgoingMessage, {@@ -6156,25 +6404,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}}- async function sendToSessionInternal(- params: {- targetSessionId?: string;- message: string;- persistedContent?: string;- clientId?: string;- dispatcherSessionId?: string;- title?: string;- useWorktree?: boolean;- /** create 分支可选:新 session 的工作目录覆盖(绝对路径,须已存在;jump 忽略)。#811 */- workingDir?: string;- onAccepted?: () => void | Promise<void>;- onAcceptedRollback?: () => void | Promise<void>;- origin?: AgentInputQueuedMessage['origin'];- createDefaults?: SendToSessionCreateDefaults;- /** 安全调用方可要求新会话不比来源会话拥有更高的权限。 */- inheritSourcePermissionMode?: boolean;- },- ): Promise<SendToSessionInternalResult> {+ async function sendToSessionInternal(params: {+ targetSessionId?: string;+ message: string;+ persistedContent?: string;+ clientId?: string;+ dispatcherSessionId?: string;+ title?: string;+ useWorktree?: boolean;+ /** create 分支可选:新 session 的工作目录覆盖(绝对路径,须已存在;jump 忽略)。#811 */+ workingDir?: string;+ onAccepted?: () => void | Promise<void>;+ onAcceptedRollback?: () => void | Promise<void>;+ origin?: AgentInputQueuedMessage['origin'];+ createDefaults?: SendToSessionCreateDefaults;+ /** 安全调用方可要求新会话不比来源会话拥有更高的权限。 */+ inheritSourcePermissionMode?: boolean;+ }): Promise<SendToSessionInternalResult> {const {targetSessionId,message,@@ -6373,7 +6619,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (sendResult.accepted) {commitAgentIslandUserPrompt(session.id, clientId);} else {- rollbackAgentIslandUserPrompt(session.id, clientId, 'send_to_session:create:not-dispatched');+ rollbackAgentIslandUserPrompt(+ session.id,+ clientId,+ 'send_to_session:create:not-dispatched',+ );}}assertDesktopSendDispatched(sendResult, 'send_to_session create');@@ -6479,9 +6729,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentKind: meta.agentKind,wakeKind: 'queued' as const,targetTitle: dbRow.title,- targetLastUserSendAt: dbRow.userSendAt !== null- ? new Date(dbRow.userSendAt).toISOString()- : null,+ targetLastUserSendAt:+ dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,};}@@ -6529,9 +6778,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentKind: meta.agentKind,wakeKind: 'queued' as const,targetTitle: dbRow.title,- targetLastUserSendAt: dbRow.userSendAt !== null- ? new Date(dbRow.userSendAt).toISOString()- : null,+ targetLastUserSendAt:+ dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,};}// idle-live send 前的轻量 MCP 漂移判定 (纯本地, 零远程 RTT):@@ -6554,15 +6802,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (ensureResult?.remoteCodexDaemonRebootstrapped) {live = undefined;} else {- const driftCleared = !hasPendingRemoteMcpDrift(live.remoteHostId, codexRemoteDriftOpts());+ const driftCleared = !hasPendingRemoteMcpDrift(+ live.remoteHostId,+ codexRemoteDriftOpts(),+ );if (driftCleared) {try {await live.detach();} catch (err) {- log.warn('sendToSession: detach after drift rebootstrap failed, falling through to lazy-resume', {- targetSessionId,- err: err instanceof Error ? err.message : String(err),- });+ log.warn(+ 'sendToSession: detach after drift rebootstrap failed, falling through to lazy-resume',+ {+ targetSessionId,+ err: err instanceof Error ? err.message : String(err),+ },+ );}live = undefined;}@@ -6581,10 +6835,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)try {await live.detach();} catch (err) {- log.warn('sendToSession: detach stale remote CC session failed, falling through to lazy-resume', {- targetSessionId,- err: err instanceof Error ? err.message : String(err),- });+ log.warn(+ 'sendToSession: detach stale remote CC session failed, falling through to lazy-resume',+ {+ targetSessionId,+ err: err instanceof Error ? err.message : String(err),+ },+ );}// detach 后不得继续 live 直发 (session 已 closed) — 置空落入// 下方 lazy-resume (bootstrap 重建 → factory forceFresh)。@@ -6593,20 +6850,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}if (live) {try {- const sendResult = await sendUserMessageWithAwaitedGitBaseline(- live,- message,- {- planMode: false,- onAccepted: persistUserMessage,- onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),- },- );+ const sendResult = await sendUserMessageWithAwaitedGitBaseline(live, message, {+ planMode: false,+ onAccepted: persistUserMessage,+ onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),+ });if (userPromptPreviewStarted) {if (sendResult.accepted) {commitAgentIslandUserPrompt(targetSessionId, clientId);} else {- rollbackAgentIslandUserPrompt(targetSessionId, clientId, 'send_to_session:live:not-dispatched');+ rollbackAgentIslandUserPrompt(+ targetSessionId,+ clientId,+ 'send_to_session:live:not-dispatched',+ );}}assertDesktopSendDispatched(sendResult, 'send_to_session live');@@ -6616,14 +6873,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentKind: meta.agentKind,wakeKind: 'already-active' as const,targetTitle: dbRow.title,- targetLastUserSendAt: dbRow.userSendAt !== null- ? new Date(dbRow.userSendAt).toISOString()- : null,+ targetLastUserSendAt:+ dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,};} catch (err) {if (isSessionRunningError(err)) {if (userPromptPreviewStarted) {- rollbackAgentIslandUserPrompt(targetSessionId, clientId, 'send_to_session:live:queued-before-dispatch');+ rollbackAgentIslandUserPrompt(+ targetSessionId,+ clientId,+ 'send_to_session:live:queued-before-dispatch',+ );}await enqueueSendToSessionMessage({targetSessionId,@@ -6642,13 +6902,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentKind: meta.agentKind,wakeKind: 'queued' as const,targetTitle: dbRow.title,- targetLastUserSendAt: dbRow.userSendAt !== null- ? new Date(dbRow.userSendAt).toISOString()- : null,+ targetLastUserSendAt:+ dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,};}if (userPromptPreviewStarted) {- rollbackAgentIslandUserPrompt(targetSessionId, clientId, 'send_to_session:live:failed-before-dispatch');+ rollbackAgentIslandUserPrompt(+ targetSessionId,+ clientId,+ 'send_to_session:live:failed-before-dispatch',+ );}return {ok: false as const,@@ -6685,20 +6948,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await ensureRemoteReadyForSessionStart({ createOpts });const { session } = await bootstrapSession(createOpts);await markOrcaRoleIfNeeded(session.id, createOpts.orcaRole);- const sendResult = await sendUserMessageWithAwaitedGitBaseline(- session,- message,- {- planMode: false,- onAccepted: persistUserMessage,- onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),- },- );+ const sendResult = await sendUserMessageWithAwaitedGitBaseline(session, message, {+ planMode: false,+ onAccepted: persistUserMessage,+ onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),+ });if (userPromptPreviewStarted) {if (sendResult.accepted) {commitAgentIslandUserPrompt(targetSessionId, clientId);} else {- rollbackAgentIslandUserPrompt(targetSessionId, clientId, 'send_to_session:resumed:not-dispatched');+ rollbackAgentIslandUserPrompt(+ targetSessionId,+ clientId,+ 'send_to_session:resumed:not-dispatched',+ );}}assertDesktopSendDispatched(sendResult, 'send_to_session resumed');@@ -6708,14 +6971,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentKind: meta.agentKind,wakeKind: 'resumed' as const,targetTitle: dbRow.title,- targetLastUserSendAt: dbRow.userSendAt !== null- ? new Date(dbRow.userSendAt).toISOString()- : null,+ targetLastUserSendAt:+ dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,};} catch (err) {if (isSessionRunningError(err)) {if (userPromptPreviewStarted) {- rollbackAgentIslandUserPrompt(targetSessionId, clientId, 'send_to_session:resumed:queued-before-dispatch');+ rollbackAgentIslandUserPrompt(+ targetSessionId,+ clientId,+ 'send_to_session:resumed:queued-before-dispatch',+ );}await enqueueSendToSessionMessage({targetSessionId,@@ -6734,13 +7000,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentKind: meta.agentKind,wakeKind: 'queued' as const,targetTitle: dbRow.title,- targetLastUserSendAt: dbRow.userSendAt !== null- ? new Date(dbRow.userSendAt).toISOString()- : null,+ targetLastUserSendAt:+ dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,};}if (userPromptPreviewStarted) {- rollbackAgentIslandUserPrompt(targetSessionId, clientId, 'send_to_session:resumed:failed-before-dispatch');+ rollbackAgentIslandUserPrompt(+ targetSessionId,+ clientId,+ 'send_to_session:resumed:failed-before-dispatch',+ );}return {ok: false as const,@@ -6811,8 +7080,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// fork 必须基于一条已经完成的 assistant 回复。这里固定选择当前有效历史里// 最新一条回复,让插件只能表达“从现在这里分叉”,不能偷偷挑更早的消息。- const [latestAssistant] = await getDbClient().drizzle- .select({ clientId: messages.clientId })+ const [latestAssistant] = await getDbClient()+ .drizzle.select({ clientId: messages.clientId }).from(messages).where(and(@@ -6833,10 +7102,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)let forkedSessionId: string;try {- const forked = await forkSessionAtMessage(- request.sourceSessionId,- latestAssistant.clientId,- );+ const forked = await forkSessionAtMessage(request.sourceSessionId, latestAssistant.clientId);forkedSessionId = forked.id;broadcastSessionCreated(forked.id);} catch (err) {@@ -6877,8 +7143,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)readSessionId: readGhostErrandSessionId,writeSessionId: writeGhostErrandSessionId,getSessionRow: async (sessionId) => {- const [row] = await getDbClient().drizzle- .select({+ const [row] = await getDbClient()+ .drizzle.select({status: sessions.status,agentKind: sessions.agentKind,model: sessions.model,@@ -6914,8 +7180,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)getObservableSession: (sessionId) => maker.getSession(sessionId) ?? null,onSilentStopSettled,readLatestAssistantText: async (sessionId, sinceMs) => {- const [row] = await getDbClient().drizzle- .select({ content: messages.content })+ const [row] = await getDbClient()+ .drizzle.select({ content: messages.content }).from(messages).where(and(@@ -7126,38 +7392,44 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)isSessionRunningError,log,});- const dispatchOrEnqueueOrcaInterAgentMessage = orcaInterAgentDispatcher.dispatchOrEnqueueOrcaInterAgentMessage;+ const dispatchOrEnqueueOrcaInterAgentMessage =+ orcaInterAgentDispatcher.dispatchOrEnqueueOrcaInterAgentMessage;dispatchInterAgentMessageHolder = dispatchOrEnqueueOrcaInterAgentMessage;- ipcMain.handle(MAKER_INVOKE.SESSION_ENABLE_ORCA, async (_e, leadSessionId: unknown, opts: unknown) => {- if (typeof leadSessionId !== 'string') throwIpcError('INVALID_PARAMS', 'leadSessionId required');- const body = (opts ?? {}) as {- workerAgent?: unknown;- delegateTask?: unknown;- role?: unknown;- label?: unknown;- model?: unknown;- effort?: unknown;- fast?: unknown;- providerId?: unknown;- };- const workerAgent: AgentKind =- body.workerAgent === 'codex' ? 'codex' : body.workerAgent === 'pi' ? 'pi' : 'claude-code';- const delegateTask = typeof body.delegateTask === 'string' ? body.delegateTask : undefined;- return enableOrcaInternal(leadSessionId, {- workerAgent,- delegateTask,- role: typeof body.role === 'string' ? body.role : undefined,- label: typeof body.label === 'string' ? body.label : undefined,- model: typeof body.model === 'string' ? body.model : undefined,- effort: typeof body.effort === 'string' ? body.effort as OrcaWorkerEffort : undefined,- fast: typeof body.fast === 'boolean' ? body.fast : undefined,- // 只认非空(trim 后)string 为显式来源;其余(null/空白/缺省/异型)一律按「未显式」处理。- providerId: typeof body.providerId === 'string' && body.providerId.trim().length > 0- ? body.providerId.trim()- : undefined,- });- });+ ipcMain.handle(+ MAKER_INVOKE.SESSION_ENABLE_ORCA,+ async (_e, leadSessionId: unknown, opts: unknown) => {+ if (typeof leadSessionId !== 'string')+ throwIpcError('INVALID_PARAMS', 'leadSessionId required');+ const body = (opts ?? {}) as {+ workerAgent?: unknown;+ delegateTask?: unknown;+ role?: unknown;+ label?: unknown;+ model?: unknown;+ effort?: unknown;+ fast?: unknown;+ providerId?: unknown;+ };+ const workerAgent: AgentKind =+ body.workerAgent === 'codex' ? 'codex' : body.workerAgent === 'pi' ? 'pi' : 'claude-code';+ const delegateTask = typeof body.delegateTask === 'string' ? body.delegateTask : undefined;+ return enableOrcaInternal(leadSessionId, {+ workerAgent,+ delegateTask,+ role: typeof body.role === 'string' ? body.role : undefined,+ label: typeof body.label === 'string' ? body.label : undefined,+ model: typeof body.model === 'string' ? body.model : undefined,+ effort: typeof body.effort === 'string' ? (body.effort as OrcaWorkerEffort) : undefined,+ fast: typeof body.fast === 'boolean' ? body.fast : undefined,+ // 只认非空(trim 后)string 为显式来源;其余(null/空白/缺省/异型)一律按「未显式」处理。+ providerId:+ typeof body.providerId === 'string' && body.providerId.trim().length > 0+ ? body.providerId.trim()+ : undefined,+ });+ },+ );/*** clearLeadOrcaRoleState — 把一个 Lead session 的协同身份彻底清干净:DB orca_role=null@@ -7180,7 +7452,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});} catch (err) {log.warn('disableOrca: setVendorOptions on alive Lead failed', {- leadSessionId, err: err instanceof Error ? err.message : String(err),+ leadSessionId,+ err: err instanceof Error ? err.message : String(err),});}}@@ -7213,7 +7486,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 让「关闭协同」成为可靠的逃生口。const role = await getSessionOrcaRole(leadSessionId);if (role === 'lead') {- log.warn('disableOrca: no active team but lead orca_role stranded; reconciling', { leadSessionId });+ log.warn('disableOrca: no active team but lead orca_role stranded; reconciling', {+ leadSessionId,+ });// 上一次关闭若在 archiveWorkersByTeam 之前被打断,team 已非 active 但 worker session 还停在// active + hidden + unreachable —— 一并补齐归档,否则它们会成为永远触达不到的孤儿 worker。const orphanedWorkerSessionIds = await reconcileInactiveTeamWorkersForLead(leadSessionId);@@ -7223,7 +7498,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}if (orphanedWorkerSessionIds.length > 0) {log.warn('disableOrca: archived orphaned workers from non-active team(s)', {- leadSessionId, count: orphanedWorkerSessionIds.length,+ leadSessionId,+ count: orphanedWorkerSessionIds.length,});}await clearLeadOrcaRoleState(leadSessionId);@@ -7245,14 +7521,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}} catch (err) {log.warn('disableOrca: abort failed (continuing to close)', {- sessionId: w.sessionId, err: err instanceof Error ? err.message : String(err),+ sessionId: w.sessionId,+ err: err instanceof Error ? err.message : String(err),});}try {await maker.closeSession(w.sessionId);} catch (err) {log.warn('disableOrca: closeSession failed', {- sessionId: w.sessionId, err: err instanceof Error ? err.message : String(err),+ sessionId: w.sessionId,+ err: err instanceof Error ? err.message : String(err),});}}@@ -7267,13 +7545,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)await clearLeadOrcaRoleState(leadSessionId);log.info('disableOrca done', {- leadSessionId, teamId: team.id, archivedCount: activeWorkers.length,+ leadSessionId,+ teamId: team.id,+ archivedCount: activeWorkers.length,});return { ok: true };}ipcMain.handle(MAKER_INVOKE.SESSION_DISABLE_ORCA, async (_e, leadSessionId: unknown) => {- if (typeof leadSessionId !== 'string') throwIpcError('INVALID_PARAMS', 'leadSessionId required');+ if (typeof leadSessionId !== 'string')+ throwIpcError('INVALID_PARAMS', 'leadSessionId required');return disableOrcaInternal(leadSessionId);});@@ -7281,13 +7562,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)ipcMain.handle(MAKER_INVOKE.WORKER_CREATE, async (_e, body: unknown) => {const b = body as Record<string, unknown> | null | undefined;- if (!b || typeof b.leadSessionId !== 'string') throwIpcError('INVALID_PARAMS', 'leadSessionId required');- if (typeof b.role !== 'string' || b.role.length < 1 || b.role.length > 32) throwIpcError('INVALID_PARAMS', 'role must be 1-32 chars');+ if (!b || typeof b.leadSessionId !== 'string')+ throwIpcError('INVALID_PARAMS', 'leadSessionId required');+ if (typeof b.role !== 'string' || b.role.length < 1 || b.role.length > 32)+ throwIpcError('INVALID_PARAMS', 'role must be 1-32 chars');if (typeof b.label !== 'string') throwIpcError('INVALID_PARAMS', 'label required');const label = normalizeOrcaWorkerLabel(b.label);if (!label.ok) throwIpcError('INVALID_PARAMS', label.message);const agent =- b.agent === 'codex' ? ('codex' as const) : b.agent === 'pi' ? ('pi' as const) : ('claude-code' as const);+ b.agent === 'codex'+ ? ('codex' as const)+ : b.agent === 'pi'+ ? ('pi' as const)+ : ('claude-code' as const);const model = typeof b.model === 'string' && b.model.length > 0 ? b.model : undefined;await assertLeadCollabProjectEnabled(b.leadSessionId);const result = await orcaLifecycleService.createWorker({@@ -7295,14 +7582,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)role: b.role,agent,model,- effort: typeof b.effort === 'string' ? b.effort as OrcaWorkerEffort : undefined,+ effort: typeof b.effort === 'string' ? (b.effort as OrcaWorkerEffort) : undefined,fast: typeof b.fast === 'boolean' ? b.fast : undefined,// 只认非空(trim 后)string 为显式来源;其余(null/空白/缺省/异型)一律按「未显式」处理。- providerId: typeof b.providerId === 'string' && b.providerId.trim().length > 0- ? b.providerId.trim()- : undefined,+ providerId:+ typeof b.providerId === 'string' && b.providerId.trim().length > 0+ ? b.providerId.trim()+ : undefined,label: label.value,- initialTask: typeof b.initialTask === 'string' && b.initialTask.length > 0 ? b.initialTask : undefined,+ initialTask:+ typeof b.initialTask === 'string' && b.initialTask.length > 0 ? b.initialTask : undefined,});if (!result.ok) throwOrcaServiceFailure(result);return {@@ -7316,14 +7605,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});ipcMain.handle(MAKER_INVOKE.WORKER_LIST, async (_e, leadSessionId: unknown) => {- if (typeof leadSessionId !== 'string') throwIpcError('INVALID_PARAMS', 'leadSessionId required');+ if (typeof leadSessionId !== 'string')+ throwIpcError('INVALID_PARAMS', 'leadSessionId required');return listWorkersByLead(leadSessionId);});ipcMain.handle(MAKER_INVOKE.WORKER_SWITCH_FOCUS, async (_e, body: unknown) => {const b = body as Record<string, unknown> | null | undefined;- if (!b || typeof b.leadSessionId !== 'string') throwIpcError('INVALID_PARAMS', 'leadSessionId required');- if (typeof b.workerIdOrLabel !== 'string') throwIpcError('INVALID_PARAMS', 'workerIdOrLabel required');+ if (!b || typeof b.leadSessionId !== 'string')+ throwIpcError('INVALID_PARAMS', 'leadSessionId required');+ if (typeof b.workerIdOrLabel !== 'string')+ throwIpcError('INVALID_PARAMS', 'workerIdOrLabel required');const workers = await listWorkersByLead(b.leadSessionId);const target = findFocusTargetWorker(workers, b.workerIdOrLabel);@@ -7338,16 +7630,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)try {const didResume = await resumeOrcaWorkerSessionIfMissing(target);if (didResume) {- log.info('switchFocus: resumed idle worker (session only, no status change)', { workerId: target.id, sessionId: target.sessionId });+ log.info('switchFocus: resumed idle worker (session only, no status change)', {+ workerId: target.id,+ sessionId: target.sessionId,+ });}} catch (err) {log.warn('switchFocus: resume failed', {- workerId: target.id, err: err instanceof Error ? err.message : String(err),+ workerId: target.id,+ err: err instanceof Error ? err.message : String(err),});}}- broadcastToAllWindows(MAKER_PUSH.ORCA_WORKER_CHANGED, { leadSessionId: b.leadSessionId as string });+ broadcastToAllWindows(MAKER_PUSH.ORCA_WORKER_CHANGED, {+ leadSessionId: b.leadSessionId as string,+ });return { ok: true, workerId: target.id };});@@ -7358,9 +7656,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});ipcMain.handle(MAKER_INVOKE.TEAM_END, async (_e, leadSessionId: unknown) => {- if (typeof leadSessionId !== 'string') throwIpcError('INVALID_PARAMS', 'leadSessionId required');+ if (typeof leadSessionId !== 'string')+ throwIpcError('INVALID_PARAMS', 'leadSessionId required');const result = await disableOrcaInternal(leadSessionId);- broadcastToAllWindows(MAKER_PUSH.ORCA_WORKER_CHANGED, { leadSessionId: leadSessionId as string });+ broadcastToAllWindows(MAKER_PUSH.ORCA_WORKER_CHANGED, {+ leadSessionId: leadSessionId as string,+ });return result;});@@ -7369,8 +7670,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// A failed restore is itself a pending condition: never close a worker while// its durable follow-up snapshot is still unavailable.if (!inputCoordinator.isQueueRestored(sessionId)) return true;- return inputCoordinator.hasPendingQueuedWork(sessionId) ||- inputCoordinator.hasQueuedItemWhere(sessionId, () => true, { includeRecovery: true });+ return (+ inputCoordinator.hasPendingQueuedWork(sessionId) ||+ inputCoordinator.hasQueuedItemWhere(sessionId, () => true, { includeRecovery: true })+ );};const orcaTeamService = createOrcaTeamService({@@ -7385,7 +7688,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)markWorkerIdle: async (workerId) => {const now = Date.now();const db = getDbClient().drizzle;- await db.update(orcaWorkers)+ await db+ .update(orcaWorkers).set({ status: 'idle', idleSince: now, updatedAt: now }).where(eq(orcaWorkers.id, workerId));},@@ -7408,8 +7712,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// A failed restore is itself a pending condition: never close a worker while// its durable follow-up snapshot is still unavailable.if (!inputCoordinator.isQueueRestored(sessionId)) return true;- return inputCoordinator.hasPendingQueuedWork(sessionId) ||- inputCoordinator.hasQueuedItemWhere(sessionId, () => true, { includeRecovery: true });+ return (+ inputCoordinator.hasPendingQueuedWork(sessionId) ||+ inputCoordinator.hasQueuedItemWhere(sessionId, () => true, { includeRecovery: true })+ );},hasSendToSessionLock: (sessionId) => sendToSessionLocks.has(sessionId),archiveWorkerSession: archiveSingleWorkerSession,@@ -7419,7 +7725,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)broadcastOrcaWorkerChanged: (leadSessionId) => {broadcastToAllWindows(MAKER_PUSH.ORCA_WORKER_CHANGED, { leadSessionId });},- dispatchWorkerMessage: async ({ targetSessionId, message, workerId, dispatchMeta, onAccepted, onAcceptedRollback }) => {+ dispatchWorkerMessage: async ({+ targetSessionId,+ message,+ workerId,+ dispatchMeta,+ onAccepted,+ onAcceptedRollback,+ }) => {const result = await dispatchOrEnqueueOrcaInterAgentMessage({targetSessionId,rawContent: message,@@ -7492,7 +7805,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)readCollaborationSettings,getLeadSessionRow: async (leadSessionId) => {const db = getDbClient().drizzle;- const [leadRow] = await db.select().from(sessions).where(eq(sessions.id, leadSessionId)).limit(1);+ const [leadRow] = await db+ .select()+ .from(sessions)+ .where(eq(sessions.id, leadSessionId))+ .limit(1);if (!leadRow) return null;return {id: leadRow.id,@@ -7538,9 +7855,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)name: provider.name,models: models.map((model) => model.id),// Fast 能力 per-(provider, model):显式来源的 Fast 判定按该来源自己的条目。- fastModels: models- .filter((model) => model.supportsFastMode)- .map((model) => model.id),+ fastModels: models.filter((model) => model.supportsFastMode).map((model) => model.id),// effort 档位同样 per-(provider, model):供 service 按实际路由来源重归一。effortMetaByModel: Object.fromEntries(models.map((model) => [@@ -7554,7 +7869,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// chat-bridged codex 供应商标记 (SSH 远端 worker 兼容闸用,// 见 orcaWorkerCreationService R23 P2 校验;wireProtocol 仅// codex 侧存在, 其他 agent 恒 false)。- chatBridgedCodex: agent === 'codex' && provider.routing[agent]?.wireProtocol === 'openai-chat',+ chatBridgedCodex:+ agent === 'codex' && provider.routing[agent]?.wireProtocol === 'openai-chat',};});return {@@ -7563,9 +7879,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)codex: availabilityFor('codex'),pi: availabilityFor('pi'),},- resolveDefaultProviderIdForModel: (agent, model) => (- effectiveSourceIdForModel(views, null, model, agent)- ),+ resolveDefaultProviderIdForModel: (agent, model) =>+ effectiveSourceIdForModel(views, null, model, agent),};},readClaudeApiKey,@@ -7723,13 +8038,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions).from(orcaWorkers).innerJoin(orcaTeams, eq(orcaTeams.id, orcaWorkers.teamId)).innerJoin(sessions, eq(sessions.id, orcaWorkers.sessionId))- .where(and(- isNull(orcaWorkers.idleSince),- inArray(orcaWorkers.status, ORCA_IDLE_RELEASE_STATUSES),- sql`${orcaWorkers.updatedAt} < ${updatedBefore}`,- eq(orcaTeams.status, 'active'),- eq(sessions.status, 'active'),- ));+ .where(+ and(+ isNull(orcaWorkers.idleSince),+ inArray(orcaWorkers.status, ORCA_IDLE_RELEASE_STATUSES),+ sql`${orcaWorkers.updatedAt} < ${updatedBefore}`,+ eq(orcaTeams.status, 'active'),+ eq(sessions.status, 'active'),+ ),+ );},getSession: (sessionId) => maker.getSession(sessionId) ?? null,withSessionLock: withSendToSessionLock,@@ -7746,8 +8063,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return result.changes === 1;},touchWorker: async (workerId, updatedAt) => {- await getDbClient().drizzle- .update(orcaWorkers)+ await getDbClient()+ .drizzle.update(orcaWorkers).set({ updatedAt }).where(eq(orcaWorkers.id, workerId));},@@ -7771,11 +8088,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)disableOrca: disableOrcaInternal,// MCP worker 派活必须经 OrcaTeamService,确保 running、resume idle、广播和// 公开错误码映射都与 IPC handler WORKER_SEND_TO 保持同一套状态机。- sendToWorker: ({ callerLeadSessionId, targetSessionId, message }) => orcaTeamService.sendToWorker({- callerLeadSessionId,- targetSessionId,- message,- }),+ sendToWorker: ({ callerLeadSessionId, targetSessionId, message }) =>+ orcaTeamService.sendToWorker({+ callerLeadSessionId,+ targetSessionId,+ message,+ }),// 排队消息控制统一走 OrcaTeamService,复用 resolveWorkerRef 归属校验与// coordinator 的 remove/replace 原语(cancel 经 remove 触发 discard settle)。listWorkerQueuedMessages: (params) => orcaTeamService.listWorkerQueuedMessages(params),@@ -7788,7 +8106,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)} catch (err) {return {ok: false,- errorCode: err instanceof Error && (err as unknown as { code?: string }).code ? (err as unknown as { code: string }).code : 'INTERNAL',+ errorCode:+ err instanceof Error && (err as unknown as { code?: string }).code+ ? (err as unknown as { code: string }).code+ : 'INTERNAL',message: err instanceof Error ? err.message : String(err),};}@@ -7800,7 +8121,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)} catch (err) {return {ok: false,- errorCode: err instanceof Error && (err as unknown as { code?: string }).code ? (err as unknown as { code: string }).code : 'INTERNAL',+ errorCode:+ err instanceof Error && (err as unknown as { code?: string }).code+ ? (err as unknown as { code: string }).code+ : 'INTERNAL',message: err instanceof Error ? err.message : String(err),};}@@ -7828,7 +8152,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)} catch (err) {return {ok: false,- errorCode: err instanceof Error && (err as unknown as { code?: string }).code ? (err as unknown as { code: string }).code : 'INTERNAL',+ errorCode:+ err instanceof Error && (err as unknown as { code?: string }).code+ ? (err as unknown as { code: string }).code+ : 'INTERNAL',message: err instanceof Error ? err.message : String(err),};}@@ -7852,35 +8179,64 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)})),};} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},getWorkspaceInfo: async ({ leadSessionId }) => {try {return await getOrcaWorkspaceInfoReadOnly(createOrcaDiagnosticsDeps(), leadSessionId);} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},getWorkerStatus: async ({ leadSessionId, workerId }) => {try {- return await getOrcaWorkerDiagnosticStatusReadOnly(createOrcaDiagnosticsDeps(), leadSessionId, workerId);+ return await getOrcaWorkerDiagnosticStatusReadOnly(+ createOrcaDiagnosticsDeps(),+ leadSessionId,+ workerId,+ );} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},readWorker: async ({ leadSessionId, workerId }) => {try {- return await readOrcaWorkerOutputReadOnly(createOrcaDiagnosticsDeps(), leadSessionId, workerId);+ return await readOrcaWorkerOutputReadOnly(+ createOrcaDiagnosticsDeps(),+ leadSessionId,+ workerId,+ );} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},switchFocus: async ({ leadSessionId, workerIdOrLabel }) => {try {const workers = await listWorkersByLead(leadSessionId);const target = findFocusTargetWorker(workers, workerIdOrLabel);- if (!target) return { ok: false, errorCode: 'WORKER_NOT_FOUND', message: `no worker matching "${workerIdOrLabel}"` };+ if (!target)+ return {+ ok: false,+ errorCode: 'WORKER_NOT_FOUND',+ message: `no worker matching "${workerIdOrLabel}"`,+ };await setWorkerFocus(target.teamId, target.id);@@ -7894,14 +8250,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)broadcastToAllWindows(MAKER_PUSH.ORCA_WORKER_CHANGED, { leadSessionId });return { ok: true, workerId: target.id };} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},idleWorker: async ({ callerLeadSessionId, workerId, expectedStatus }) => {try {return await orcaTeamService.idleWorker({ callerLeadSessionId, workerId, expectedStatus });} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},endTeam: async ({ leadSessionId }) => {@@ -7910,14 +8274,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)broadcastToAllWindows(MAKER_PUSH.ORCA_WORKER_CHANGED, { leadSessionId });return { ok: true };} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},archiveWorker: async ({ callerLeadSessionId, workerId }) => {try {return await orcaTeamService.archiveWorker({ callerLeadSessionId, workerId });} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},listAvailableModels: async ({ agent }) => {@@ -7932,11 +8304,93 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}return { ok: true, ...result };} catch (err) {- return { ok: false, errorCode: 'INTERNAL', message: err instanceof Error ? err.message : String(err) };+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}},};+ const createUserMessageDurably: typeof createDbMessage = async (sessionId, message, opts) => {+ // 真实用户消息(renderer 发送事务)→ 给两个自动续跑守卫充值额度。+ //+ // **必须按 agentMeta.autoResume 排除自动补发的消息。** silent-stop 的自动续跑+ // 走 session.send 直发、天然绕开本路径,但**中断自动续跑走的正是本路径**+ // (coordinator 队列 → makerSendTransaction.onAccepted → 这里)。不排除的话它+ // 每次续跑都给自己(和 silent-stop)重新充值,「每条人话最多买 N 个自动 turn」+ // 这条防死循环的硬保证就没了 —— 上游连环抽风时会无限自动续跑。+ if (isAutoResumeUserMessage(message.agentMeta)) {+ // 这条自动续跑消息的结果还不知道,登记待确认(产出→succeeded / 再被打断→failed)。+ const attemptToken = autoResumeAttemptTokenFromAgentMeta(message.agentMeta);+ if (attemptToken !== null) {+ autoResumeBookkeeping.registerPendingOutcome(sessionId, attemptToken, message.clientId);+ }+ } else {+ const origin =+ message.agentMeta && typeof message.agentMeta === 'object'+ ? (message.agentMeta as { origin?: unknown }).origin+ : undefined;+ const originKind =+ origin && typeof origin === 'object' ? (origin as { kind?: unknown }).kind : undefined;+ // Scheduler prompts are automatic inputs, not fresh human intervention. They may+ // share the coordinator persistence path with composer messages, but must not recharge+ // the interrupted-turn episode budget and defeat its hard upper bound.+ const isAutomaticPrompt =+ originKind === 'scheduler' || originKind === 'goal' || originKind === 'orca';+ silentStopAutoResumeGuard.noteUserSend(sessionId);+ if (!isAutomaticPrompt) interruptedTurnAutoResumeGuard.noteUserSend(sessionId);+ }+ // 落库失败 → 撤掉刚才那条待确认登记:那条消息压根不存在,留着会让后续事件去 patch+ // 一个不存在的 clientId,map 也一直脏着(copilot review)。登记刻意放在写之前(不能+ // 让写完到登记之间的事件漏掉结算),所以这里补一条失败回滚。+ const releasePendingOutcomeOnFailure = () => {+ if (!isAutoResumeUserMessage(message.agentMeta)) return;+ const attemptToken = autoResumeAttemptTokenFromAgentMeta(message.agentMeta);+ if (attemptToken !== null) {+ autoResumeBookkeeping.releasePendingOutcome(sessionId, attemptToken, message.clientId);+ }+ };+ try {+ return await enqueueDurableWrite(`user:${sessionId}:${message.clientId}`, (ownerScope) => {+ // Coordinator accepts can stamp transcriptParentUuid early; this late FIFO+ // fallback covers makerSendTransaction/direct createDbMessage paths.+ const transcriptParentUuid = getLastAssistantTranscriptUuid(sessionId);+ const hasTranscriptParent =+ typeof message.agentMeta?.transcriptParentUuid === 'string' &&+ message.agentMeta.transcriptParentUuid.length > 0;+ const enrichedMessage =+ transcriptParentUuid && !hasTranscriptParent+ ? {+ ...message,+ agentMeta: {+ ...message.agentMeta,+ transcriptParentUuid,+ },+ }+ : message;+ // session-agent-switch:user 行逐行 stamp 当前引擎(见 messages.agent_kind 注释)。+ const agentKind = getSessionDbAgentKind(sessionId);+ const scopedOpts = {+ ...(opts ?? {}),+ // Keep a committed user row durable across an owner switch, while+ // preventing createMessage from relabelling its broadcast to the+ // next owner after the media-ref await.+ broadcastOwnerScope: ownerScope,+ };+ return createDbMessage(+ sessionId,+ agentKind ? { ...enrichedMessage, agentKind } : enrichedMessage,+ scopedOpts,+ );+ });+ } catch (err) {+ releasePendingOutcomeOnFailure();+ throw err;+ }+ };+const { sendToAgentAccepted: sendToAgentAcceptedUnlocked } = createMakerSendTransaction({getSession: (sessionId) => maker.getSession(sessionId),closeSession: (sessionId) => maker.closeSession(sessionId),@@ -7957,87 +8411,36 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)prepareSendUserMessage: (sessionId, message) =>prepareUserMessageForAgent(sessionId, message, 'send'),materializeDirectSendOssAttachments,- createDbMessage: async (sessionId, message, opts) => {- // 真实用户消息(renderer 发送事务)→ 给两个自动续跑守卫充值额度。- //- // **必须按 agentMeta.autoResume 排除自动补发的消息。** silent-stop 的自动续跑- // 走 session.send 直发、天然绕开本路径,但**中断自动续跑走的正是本路径**- // (coordinator 队列 → makerSendTransaction.onAccepted → 这里)。不排除的话它- // 每次续跑都给自己(和 silent-stop)重新充值,「每条人话最多买 N 个自动 turn」- // 这条防死循环的硬保证就没了 —— 上游连环抽风时会无限自动续跑。- if (isAutoResumeUserMessage(message.agentMeta)) {- // 这条自动续跑消息的结果还不知道,登记待确认(产出→succeeded / 再被打断→failed)。- const attemptToken = autoResumeAttemptTokenFromAgentMeta(message.agentMeta);- if (attemptToken !== null) {- autoResumeBookkeeping.registerPendingOutcome(- sessionId,- attemptToken,- message.clientId,- );- }- } else {- const origin =- message.agentMeta && typeof message.agentMeta === 'object'- ? (message.agentMeta as { origin?: unknown }).origin- : undefined;- const originKind =- origin && typeof origin === 'object'- ? (origin as { kind?: unknown }).kind- : undefined;- // Scheduler prompts are automatic inputs, not fresh human intervention. They may- // share the coordinator persistence path with composer messages, but must not recharge- // the interrupted-turn episode budget and defeat its hard upper bound.- const isAutomaticPrompt =- originKind === 'scheduler' || originKind === 'goal' || originKind === 'orca';- silentStopAutoResumeGuard.noteUserSend(sessionId);- if (!isAutomaticPrompt) interruptedTurnAutoResumeGuard.noteUserSend(sessionId);- }- // 落库失败 → 撤掉刚才那条待确认登记:那条消息压根不存在,留着会让后续事件去 patch- // 一个不存在的 clientId,map 也一直脏着(copilot review)。登记刻意放在写之前(不能- // 让写完到登记之间的事件漏掉结算),所以这里补一条失败回滚。- const releasePendingOutcomeOnFailure = () => {- if (!isAutoResumeUserMessage(message.agentMeta)) return;- const attemptToken = autoResumeAttemptTokenFromAgentMeta(message.agentMeta);- if (attemptToken !== null) {- autoResumeBookkeeping.releasePendingOutcome(- sessionId,- attemptToken,- message.clientId,- );- }- };- const result = await enqueueDurableWrite(`user:${sessionId}:${message.clientId}`, () => {- // Coordinator accepts can stamp transcriptParentUuid early; this late FIFO- // fallback covers makerSendTransaction/direct createDbMessage paths.- const transcriptParentUuid = getLastAssistantTranscriptUuid(sessionId);- const hasTranscriptParent = typeof message.agentMeta.transcriptParentUuid === 'string' &&- message.agentMeta.transcriptParentUuid.length > 0;- const enrichedMessage = transcriptParentUuid && !hasTranscriptParent- ? {- ...message,- agentMeta: {- ...message.agentMeta,- transcriptParentUuid,- },- }- : message;- // session-agent-switch:user 行逐行 stamp 当前引擎(见 messages.agent_kind 注释)。- const agentKind = getSessionDbAgentKind(sessionId);- return createDbMessage(- sessionId,- agentKind ? { ...enrichedMessage, agentKind } : enrichedMessage,- opts,- );- }).catch((err: unknown) => {- releasePendingOutcomeOnFailure();- throw err;- });- return result;+ createDbMessage: createUserMessageDurably,+ rewindPersistedUserMessageAfterClear: (sessionId, clientId) =>+ enqueueDurableWrite(`user-rewind:${sessionId}:${clientId}`, () =>+ rewindPersistedUserMessageAfterClear(sessionId, clientId),+ ),+ isClearBoundaryCurrent: (sessionId, expected, expectedGeneration) => {+ const coordinator = agentInputCoordinatorHolder;+ if (!coordinator) return true;+ if (+ expectedGeneration !== undefined &&+ !coordinator.isGenerationCurrent(sessionId, expectedGeneration)+ ) {+ return false;+ }+ return coordinator.getClearBoundaryMs(sessionId) === expected;},linkPiUserEntry: (sessionId, clientId, piEntryId) =>enqueueDurableWrite(`pi-entry-link:${sessionId}:${clientId}`, () =>- patchMessageAgentMeta(sessionId, clientId, { piEntryId })),+ patchMessageAgentMeta(sessionId, clientId, { piEntryId }),+ ),beforeDispatchDirectUserTurn: (sessionId) => gitSnapshotCoordinator?.onTurnStart(sessionId),+ assertBeforeVendorDispatch: (sessionId, sendOpts) => {+ const remote = isDeviceLinkInvoke();+ assertRemoteInputClearNotInFlight(sessionId, remote);+ const precondition = readRemoteInputClearBoundaryPrecondition(sendOpts);+ if (precondition.present) {+ assertCurrentInputClearBoundary(sessionId, precondition.expected);+ }+ assertCurrentInputGeneration(sessionId, readExpectedInputGeneration(sendOpts));+ },onUndispatchedDirectUserTurn: (sessionId) => gitSnapshotCoordinator?.onTurnAbort(sessionId),ackInterruptedTurnDispatched: async (sessionId, endedAt) => {await ackSessionTurnEndedDurable(sessionId, endedAt);@@ -8083,7 +8486,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 未知一律 false)。必须在这里现取,不能提前求值缓存——同一个装配好的事务会服务// 后续所有 send,来源是逐次调用的属性。isMobileClientInvoke: () => isMobileControllerInvoke(),- applyPendingAgentSwitch: (sessionId) => applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId),+ applyPendingAgentSwitch: (sessionId) =>+ applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId),log,});@@ -8101,7 +8505,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)* vendor start failures are hard pre-accept failures so renderer rolls back* the optimistic bubble instead of resurrecting the message as a new turn.*/- const steerToAgentAccepted = async (sessionId: unknown, message: unknown, sendOpts?: unknown): Promise<void> => {+ const steerToAgentAccepted = async (+ sessionId: unknown,+ message: unknown,+ sendOpts?: unknown,+ ): Promise<void> => {if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');const sess = maker.getSession(sessionId);if (!sess) {@@ -8115,7 +8523,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)activeBeforeNormalize: sess.isTurnRunning(),});if (!sess.capabilities.sameTurnSteer.supported) {- throwIpcError('UNSUPPORTED_CAPABILITY', `Agent ${sess.agentKind} does not support same-turn steer`);+ throwIpcError(+ 'UNSUPPORTED_CAPABILITY',+ `Agent ${sess.agentKind} does not support same-turn steer`,+ );}if (!sess.isTurnRunning()) {throwIpcError('NO_ACTIVE_TURN', `Session ${sessionId} has no active turn`);@@ -8151,16 +8562,26 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)signal?: AbortSignal;/** coordinator 从队列项透传的手机来源(main 构造,非 wire 输入)。 */fromMobileClient?: boolean;+ expectedClearBoundaryMs?: number | null;+ expectedInputGeneration?: number;};// 手机说明同样只进 wire payload(steer 路径不落库用户消息,天然不污染原话)。// 两个来源都要认:IPC 直连 steer 时 async context 在;coordinator 投递时靠透传。- const steerNote = isMobileControllerInvoke() || so.fromMobileClient === true- ? buildMobileClientPromptNote()- : null;+ const steerNote =+ isMobileControllerInvoke() || so.fromMobileClient === true+ ? buildMobileClientPromptNote()+ : null;const steerPayload = steerNote? prependNoteToWireUserMessage(normalized as HandoffWireMessage, steerNote): normalized;try {+ const remote = isDeviceLinkInvoke();+ assertRemoteInputClearNotInFlight(sessionId, remote);+ const precondition = readRemoteInputClearBoundaryPrecondition(sendOpts);+ if (precondition.present) {+ assertCurrentInputClearBoundary(sessionId, precondition.expected);+ }+ assertCurrentInputGeneration(sessionId, readExpectedInputGeneration(sendOpts));await sess.steer(steerPayload as never, {logTitle: meta?.title,messageUuid: so.messageUuid,@@ -8170,7 +8591,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)log.info('steer: delivered', { sessionId, agentKind: sess.agentKind });} catch (err) {const messageText = err instanceof Error ? err.message : String(err);- const isClosedDeliveryFailure = /session (?:is )?closed|closed session|input queue is closed/i.test(messageText);+ const isClosedDeliveryFailure =+ /session (?:is )?closed|closed session|input queue is closed/i.test(messageText);if (!isClosedDeliveryFailure && /no active .*turn|has no active turn/i.test(messageText)) {log.warn('steer: no active turn during delivery', {sessionId,@@ -8188,84 +8610,122 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}};- registerMakerSessionSendHandler(- makerSessionRegistry,- { sendToAgentAccepted },- );-- ipcMain.handle(MAKER_INVOKE.STEER, async (_e, sessionId: unknown, message: unknown, sendOpts?: unknown) => {- // **wire sendOpts 必须消毒**(review P1/P2,两个 bot 各报一次):这个 channel 在- // device-link allowlist 里开放,`sendOpts` 是调用方可控输入。不剥的话,桌面 renderer- // 或任意获准远控的非手机客户端只要传 `{ fromMobileClient: true }`,就能让本轮拿到伪造- // 的手机环境说明、按错误的来源调整产物形态。- //- // 契约与 maker:send 一致(sessionSendHandler 同样在 IPC 边界剥):**该字段只由 main- // 盖章**。coordinator 的内部 steerToAgent 调用不经过这里,透传值不受影响。- await steerToAgentAccepted(sessionId, message, stripMainOnlySendOpts(sendOpts));+ registerMakerSessionSendHandler(makerSessionRegistry, {+ sendToAgentAccepted,+ assertRemoteInputControlBoundary: (sessionId, opts) =>+ assertRemoteInputControlBoundary(sessionId, isDeviceLinkInvoke(), opts),});- ipcMain.handle(MAKER_INVOKE.GET_CONTEXT_USAGE, async (_e, sessionId: unknown, createOpts?: unknown): Promise<ContextUsageData> => {- if (typeof sessionId !== 'string' || sessionId.length === 0) {- throwIpcError('INVALID_PARAMS', 'sessionId required');- }- let sess = maker.getSession(sessionId);- if (!sess) {- if (!createOpts) {- throwIpcError('NOT_FOUND', `Session ${sessionId} is not running`);- }- const co = buildCreateOptsWithStderr({ ...(createOpts as CreateOpts), id: sessionId });- // session-agent-switch:先按 DB 行校正再判 claude-only——否则切到 codex 后- // 残留的 claude createOpts 会在这里 spawn 出旧引擎的 live session 并被后续- // send 复用(会话被劫持回旧引擎,2026-07-20 审计实锤)。- await reconcileCreateOptsAgainstDb(sessionId, co);- if (co.agentKind !== 'claude-code') {- throwIpcError('UNSUPPORTED_CAPABILITY', `Agent ${co.agentKind} does not support context usage`);- }- const okLazy = await checkWorkDirExists(sessionId, co.workingDir, co.agentKind, co.remoteHostId);- if (!okLazy) {- throwIpcError('NOT_FOUND', `Working directory is missing for session ${sessionId}`);- }- await synthesizeOrcaVendorOptionsFromDb(sessionId, co);- if (co.extraDirs === undefined) {+ ipcMain.handle(+ MAKER_INVOKE.STEER,+ async (_e, sessionId: unknown, message: unknown, sendOpts?: unknown) => {+ // **wire sendOpts 必须消毒**(review P1/P2,两个 bot 各报一次):这个 channel 在+ // device-link allowlist 里开放,`sendOpts` 是调用方可控输入。不剥的话,桌面 renderer+ // 或任意获准远控的非手机客户端只要传 `{ fromMobileClient: true }`,就能让本轮拿到伪造+ // 的手机环境说明、按错误的来源调整产物形态。+ //+ // 契约与 maker:send 一致(sessionSendHandler 同样在 IPC 边界剥):**该字段只由 main+ // 盖章**。coordinator 的内部 steerToAgent 调用不经过这里,透传值不受影响。+ if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');+ const boundaryStamp = await assertRemoteInputControlBoundary(+ sessionId,+ isDeviceLinkInvoke(),+ sendOpts,+ );+ await steerToAgentAccepted(+ sessionId,+ message,+ attachMainOwnedInputBoundary(stripMainOnlySendOpts(sendOpts), boundaryStamp),+ );+ },+ );++ ipcMain.handle(+ MAKER_INVOKE.GET_CONTEXT_USAGE,+ async (_e, sessionId: unknown, createOpts?: unknown): Promise<ContextUsageData> => {+ if (typeof sessionId !== 'string' || sessionId.length === 0) {+ throwIpcError('INVALID_PARAMS', 'sessionId required');+ }+ let sess = maker.getSession(sessionId);+ if (!sess) {+ if (!createOpts) {+ throwIpcError('NOT_FOUND', `Session ${sessionId} is not running`);+ }+ const co = buildCreateOptsWithStderr({ ...(createOpts as CreateOpts), id: sessionId });+ // session-agent-switch:先按 DB 行校正再判 claude-only——否则切到 codex 后+ // 残留的 claude createOpts 会在这里 spawn 出旧引擎的 live session 并被后续+ // send 复用(会话被劫持回旧引擎,2026-07-20 审计实锤)。+ await reconcileCreateOptsAgainstDb(sessionId, co);+ if (co.agentKind !== 'claude-code') {+ throwIpcError(+ 'UNSUPPORTED_CAPABILITY',+ `Agent ${co.agentKind} does not support context usage`,+ );+ }+ const okLazy = await checkWorkDirExists(+ sessionId,+ co.workingDir,+ co.agentKind,+ co.remoteHostId,+ );+ if (!okLazy) {+ throwIpcError('NOT_FOUND', `Working directory is missing for session ${sessionId}`);+ }+ await synthesizeOrcaVendorOptionsFromDb(sessionId, co);+ if (co.extraDirs === undefined) {+ try {+ const row = await readSessionExtraDirsFromDb(sessionId);+ if (row.length > 0) co.extraDirs = row;+ } catch (err) {+ log.warn('context-usage lazy-create: read extra_dirs from DB failed (non-fatal)', {+ sessionId,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ }try {- const row = await readSessionExtraDirsFromDb(sessionId);- if (row.length > 0) co.extraDirs = row;- } catch (err) {- log.warn('context-usage lazy-create: read extra_dirs from DB failed (non-fatal)', {+ await ensureRemoteReadyForSessionStart({ createOpts: co });+ const {+ session: lazySess,+ didInjectOrcaInstructions,+ didInjectProjectContext,+ } = await bootstrapSession(co);+ await markOrcaRoleIfNeeded(lazySess.id, co.orcaRole);+ log.info('context-usage: lazy create-session', {sessionId,- err: err instanceof Error ? err.message : String(err),+ agentKind: co.agentKind,+ model: co.model,+ usedOrcaInstructions: didInjectOrcaInstructions,+ usedProjectContext: didInjectProjectContext,+ extraDirsCount: co.extraDirs?.length ?? 0,});+ sess = lazySess;+ } catch (err) {+ throwIpcError(+ 'INTERNAL',+ err instanceof Error ? err.message : 'context usage lazy create failed',+ );}}+ if (sess.agentKind !== 'claude-code' && sess.agentKind !== 'pi') {+ throwIpcError(+ 'UNSUPPORTED_CAPABILITY',+ `Agent ${sess.agentKind} does not support context usage`,+ );+ }try {- await ensureRemoteReadyForSessionStart({ createOpts: co });- const { session: lazySess, didInjectOrcaInstructions, didInjectProjectContext } = await bootstrapSession(co);- await markOrcaRoleIfNeeded(lazySess.id, co.orcaRole);- log.info('context-usage: lazy create-session', {- sessionId,- agentKind: co.agentKind,- model: co.model,- usedOrcaInstructions: didInjectOrcaInstructions,- usedProjectContext: didInjectProjectContext,- extraDirsCount: co.extraDirs?.length ?? 0,- });- sess = lazySess;+ return await sess.getContextUsage();} catch (err) {- throwIpcError('INTERNAL', err instanceof Error ? err.message : 'context usage lazy create failed');- }- }- if (sess.agentKind !== 'claude-code' && sess.agentKind !== 'pi') {- throwIpcError('UNSUPPORTED_CAPABILITY', `Agent ${sess.agentKind} does not support context usage`);- }- try {- return await sess.getContextUsage();- } catch (err) {- if (err instanceof Error && err.name === 'NotSupportedError') {- throwIpcError('UNSUPPORTED_CAPABILITY', err.message);+ if (err instanceof Error && err.name === 'NotSupportedError') {+ throwIpcError('UNSUPPORTED_CAPABILITY', err.message);+ }+ throwIpcError(+ 'INTERNAL',+ err instanceof Error ? err.message : 'context usage query failed',+ );}- throwIpcError('INTERNAL', err instanceof Error ? err.message : 'context usage query failed');- }- });+ },+ );/*** Reconcile the in-memory turn boundary after a vendor abort/close when the@@ -8343,7 +8803,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (abortedBoundaryAssistantPersistId) {void markAssistantTurnFailed(sessionId, abortedBoundaryAssistantPersistId);}- const trackerStale = sessionTurnActivityTracker.isSessionInTurn(sessionId) ||+ const trackerStale =+ sessionTurnActivityTracker.isSessionInTurn(sessionId) ||sessionTurnActivityTracker.isSessionTurnDispatchBoundaryBusy(sessionId);const hadZombieInteraction = hasPendingAgentInteractionForSession(sessionId);if (trackerStale || hadZombieInteraction) {@@ -8487,11 +8948,157 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return boundary;};+ /**+ * /clear replaces the coordinator state synchronously but seals the DB+ * visibility boundary after an await. Remote input must not enter that+ * window: it could capture the new generation while still reading the old+ * clearedAt value and then dispatch into the pre-clear context.+ */+ // A clear seals the DB visibility boundary after an await. Keep a small+ // per-session refcount rather than a bare Set so two user clear requests+ // cannot let the first finally block release the gate while the second one+ // is still sealing.+ const inputClearInFlightSessions = new Map<string, number>();+ const beginRemoteInputClearGate = (sessionId: string): void => {+ inputClearInFlightSessions.set(sessionId, (inputClearInFlightSessions.get(sessionId) ?? 0) + 1);+ };+ const endRemoteInputClearGate = (sessionId: string): void => {+ const count = inputClearInFlightSessions.get(sessionId) ?? 0;+ if (count <= 1) inputClearInFlightSessions.delete(sessionId);+ else inputClearInFlightSessions.set(sessionId, count - 1);+ };+ const assertRemoteInputClearNotInFlight = (sessionId: string, remote: boolean): void => {+ if (!remote || !inputClearInFlightSessions.has(sessionId)) return;+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'REMOTE_OPTIMISTIC_INPUT_CLEARED: session clear is still sealing',+ );+ };++ const getPersistedInputClientIds = async (+ sessionId: string,+ clientIds: string[],+ ): Promise<Set<string>> => {+ if (clientIds.length === 0) return new Set<string>();+ const db = getDbClient().drizzle;+ const rows = await db+ .select({ clientId: messages.clientId })+ .from(messages)+ .where(and(eq(messages.sessionId, sessionId), inArray(messages.clientId, clientIds)));+ return new Set(rows.map((row) => row.clientId));+ };++ /**+ * Deferred queue materialisation creates local media before the coordinator+ * knows whether the item will ever reach the durable messages row. Keep that+ * ownership outside the persisted queue payload and settle it at the same+ * lifecycle boundaries as the coordinator item.+ */+ const queuedAttachmentOwnership = new QueuedAttachmentOwnershipRegistry((failure) => {+ log.warn('queued attachment cleanup failed', {+ sessionId: failure.sessionId,+ clientId: failure.clientId,+ error: failure.error instanceof Error ? failure.error.message : String(failure.error),+ });+ });+ const registerQueuedAttachmentOwnership =+ queuedAttachmentOwnership.register.bind(queuedAttachmentOwnership);+ const markQueuedAttachmentDurableAfterSnapshot = (+ sessionId: string,+ clientId: string,+ ownerId: string | null,+ ): void => {+ if (!ownerId) return;+ void (async () => {+ try {+ await awaitAgentInputQueueSnapshotPersistence(sessionId);+ await queuedAttachmentOwnership.markDurable(sessionId, clientId, ownerId);+ } catch (error) {+ // Keep the remote source alive when the snapshot did not cross the+ // durable boundary. A later retry, DB persistence callback, or explicit+ // discard will settle the ownership; deleting it here would recreate+ // the crash window this registry is meant to close.+ log.warn('queued attachment durable snapshot not available', {+ sessionId,+ clientId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ })();+ };+ const discardQueuedAttachmentOwnership = (+ sessionId: string,+ clientId: string,+ keepOwnerId?: string,+ ): void => {+ // Coordinator discard callbacks can run before the state mutation that+ // removes the item emits its replacement snapshot (remove/stop/clear do+ // exactly that). Defer one microtask so the current synchronous lifecycle+ // transition has queued that snapshot; otherwise a crash between the old+ // snapshot and the pending deletion could resurrect an item whose local+ // materialisation was already deleted.+ queueMicrotask(() => {+ void (async () => {+ try {+ await awaitAgentInputQueueSnapshotPersistence(sessionId);+ await queuedAttachmentOwnership.discardClient(sessionId, clientId, keepOwnerId);+ } catch (error) {+ // A failed snapshot must keep the ownership callbacks alive. The+ // recycler/next lifecycle boundary can retry without losing data.+ log.warn('queued attachment discard deferred until snapshot persistence', {+ sessionId,+ clientId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ })();+ });+ };+ const discardSpecificQueuedAttachmentOwnership = (+ sessionId: string,+ clientId: string,+ ownerId: string,+ ): Promise<void> => {+ return queuedAttachmentOwnership.discardSpecific(sessionId, clientId, ownerId);+ };+ const markQueuedAttachmentPersistenceStarted = (sessionId: string, clientId: string): void => {+ queuedAttachmentOwnership.markPersistenceStarted(sessionId, clientId);+ };+ const settleQueuedAttachmentPersistenceFailure = (+ sessionId: string,+ clientId: string,+ retainForRetry: boolean,+ ): void => {+ // The coordinator invokes this callback before its failure projection emits+ // the replacement queue snapshot. Wait one microtask so cleanup cannot+ // race the stale crash snapshot and delete media that recovery still needs.+ queueMicrotask(() => {+ void (async () => {+ try {+ await awaitAgentInputQueueSnapshotPersistence(sessionId);+ await queuedAttachmentOwnership.markPersistenceFailed(sessionId, clientId, {+ retainForRetry,+ });+ } catch (error) {+ log.warn('queued attachment persistence failure settlement deferred', {+ sessionId,+ clientId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ })();+ });+ };+const inputCoordinator: AgentInputCoordinator = new AgentInputCoordinator({sendToAgent: async (sessionId, message, createOpts, sendOpts) => {try {const result = await sendToAgentAccepted(sessionId, message, createOpts, sendOpts);- await orcaInterAgentDispatcher.settleQueuedOrcaInterAgentAcceptedCallback(sessionId, sendOpts, result.outcome);+ await orcaInterAgentDispatcher.settleQueuedOrcaInterAgentAcceptedCallback(+ sessionId,+ sendOpts,+ result.outcome,+ );return result.outcome;} catch (err) {await orcaInterAgentDispatcher.rollbackQueuedOrcaInterAgentAcceptedCallback(@@ -8601,13 +9208,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// superseded = 用户自己接手了,别再弹横幅打扰(但中断要补进历史);// no-progress = 零产出、按设计不自动续跑,这是一次没人接手的真失败,// 必须把横幅还给用户,否则被静默吞掉(copilot review)。- autoResumeBookkeeping.finalizeSuppressedError(- sessionId,- decision.attemptToken,- {- surfaceBanner: outcome === 'no-progress',- },- );+ autoResumeBookkeeping.finalizeSuppressedError(sessionId, decision.attemptToken, {+ surfaceBanner: outcome === 'no-progress',+ });log.debug('interrupted-turn auto-resume not dispatched', { sessionId, outcome });return;}@@ -8620,16 +9223,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)log.debug('interrupted-turn auto-resume rejection superseded', { sessionId });return;}- interruptedTurnAutoResumeGuard.noteResumeSendFailed(- sessionId,- decision.attemptToken,- );- // 补发本身失败 → 回落成常规错误呈现,让用户能手点重试。- autoResumeBookkeeping.finalizeSuppressedError(- sessionId,- decision.attemptToken,- { surfaceBanner: true },- );+ interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId, decision.attemptToken);+ // 补发本身失败 → 回落成常规错误呈现,让用户能手点重试。+ autoResumeBookkeeping.finalizeSuppressedError(sessionId, decision.attemptToken, {+ surfaceBanner: true,+ });log.warn('interrupted-turn auto-resume failed', {sessionId,error: err instanceof Error ? err.message : String(err),@@ -8681,6 +9279,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const meta = await maker.getSessionMeta(sessionId).catch(() => null);return meta?.sdkSessionId;},+ // Coordinator steer/drain persistence must use the same FIFO writer and+ // auto-resume bookkeeping as direct maker sends. Keeping one writer also+ // preserves message ordering when a clear-race rewind follows the insert.+ createUserMessage: createUserMessageDurably,+ rewindPersistedUserMessageAfterClear: (sessionId, clientId) =>+ enqueueDurableWrite(`user-rewind:${sessionId}:${clientId}`, () =>+ rewindPersistedUserMessageAfterClear(sessionId, clientId),+ ),resolveSessionReferences,// interrupted-turn-resume:retry 续跑判定走 DB 持久化行(见 dep 注释)。// 先 drain 持久化写队列:terminal error 到达时 flushAssistantBlock 只是把@@ -8704,6 +9310,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// pending auto-bridge 副作用必须先于 turn 启动完成;失败仍吞错落日志,不拦派发。return orcaInterAgentDispatcher.runQueuedOrcaInterAgentAcceptedCallback(sessionId, item);},+ onUserMessagePersisting: (sessionId, item) => {+ markQueuedAttachmentPersistenceStarted(sessionId, item.clientId);+ },+ onUserMessagePersisted: (sessionId, item) => {+ // A messages row is a stronger durable boundary than the queue snapshot.+ // Release the controller-owned OSS source before dropping the ephemeral+ // ownership record; the local materialization itself now belongs to the+ // durable transcript row.+ void queuedAttachmentOwnership.settleDurable(sessionId, item.clientId);+ },+ onUserMessagePersistenceFailed: (sessionId, item, opts) => {+ settleQueuedAttachmentPersistenceFailure(sessionId, item.clientId, opts.retainForRetry);+ },onDispatchedUserTurn: async (sessionId, item, preVendorDispatchAt): Promise<void> => {const attemptToken = autoResumeAttemptToken(item);if (@@ -8750,11 +9369,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)onUiRetry: (sessionId, clientId, source, attemptToken) => {autoResumeBookkeeping.claimSuppressedErrorForRetry(sessionId, clientId, source);if (source === 'auto' && attemptToken !== undefined) {- autoResumeBookkeeping.bindSuppressedErrorToClient(- sessionId,- attemptToken,- clientId,- );+ autoResumeBookkeeping.bindSuppressedErrorToClient(sessionId, attemptToken, clientId);}if (source === 'manual') {// UI continuation can dispatch before the scheduler backoff callback.@@ -8795,6 +9410,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},// 队列项未派发即被丢弃(stop/remove/clearSession) → 释放暂存的 accepted 副作用, 防回调表泄漏。onDiscardedQueuedMessage: (sessionId, item) => {+ discardQueuedAttachmentOwnership(sessionId, item.clientId);orcaInterAgentDispatcher.discardQueuedOrcaInterAgentAcceptedCallback(item.clientId);// Auto-resume cleanup must run before generic claimed-retry release:// settleOutcome may drop the attempt lease, while finalizeSuppressedError@@ -8882,19 +9498,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 写链保序 + 失败落日志),读回由 IPC 入口的 ensureQueueRestored 懒触发。persistQueueSnapshot: (sessionId, items) => saveAgentInputQueueSnapshot(sessionId, items),loadQueueSnapshot: (sessionId) => loadAgentInputQueueSnapshot(sessionId),- getPersistedClientIds: async (sessionId, clientIds) => {- if (clientIds.length === 0) return new Set<string>();- const db = getDbClient().drizzle;- const rows = await db- .select({ clientId: messages.clientId })- .from(messages)- .where(and(eq(messages.sessionId, sessionId), inArray(messages.clientId, clientIds)));- return new Set(rows.map((r) => r.clientId));- },+ getPersistedClientIds: getPersistedInputClientIds,});agentInputCoordinatorHolder = inputCoordinator;getAgentIslandService()?.setCompletionDeferResolver((sessionId) =>- inputCoordinator.hasPendingQueuedWork(sessionId)+ inputCoordinator.hasPendingQueuedWork(sessionId),);// Scheduler 撞忙排队桥实现(导出薄封装见 isSchedulerTargetSessionBusy 一带注释)。@@ -8948,7 +9556,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (inputCoordinator.hasQueuedItemWhere(req.sessionId,- (item) => item.origin?.kind === 'scheduler' && item.origin.scheduleId === req.origin.scheduleId,+ (item) =>+ item.origin?.kind === 'scheduler' && item.origin.scheduleId === req.origin.scheduleId,{ includeRecovery: true },)) {@@ -9011,10 +9620,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (route.model) patch.model = route.model;if (route.effort) patch.effort = route.effort;if (route.fastMode !== undefined) patch.fastMode = route.fastMode;- await getDbClient()- .drizzle.update(sessions)- .set(patch)- .where(eq(sessions.id, sessionId));+ await getDbClient().drizzle.update(sessions).set(patch).where(eq(sessions.id, sessionId));broadcastSessionPatched(sessionId, patch);},logger: log,@@ -9070,7 +9676,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const requireSessionRefs = (value: unknown): AgentInputSessionRef[] | undefined => {if (value === undefined) return undefined;if (!Array.isArray(value) || value.length > MAX_SESSION_REFERENCES) {- throwIpcError('INVALID_PARAMS', `sessionRefs must contain at most ${MAX_SESSION_REFERENCES} items`);+ throwIpcError(+ 'INVALID_PARAMS',+ `sessionRefs must contain at most ${MAX_SESSION_REFERENCES} items`,+ );}const refs = value as AgentInputSessionRef[];const seen = new Set<string>();@@ -9080,10 +9689,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)typeof ref.sessionId !== 'string' ||ref.sessionId.length === 0 ||ref.sessionId.length > 256 ||- (ref.deviceId !== undefined && (typeof ref.deviceId !== 'string' || ref.deviceId.length === 0)) ||+ (ref.deviceId !== undefined &&+ (typeof ref.deviceId !== 'string' || ref.deviceId.length === 0)) ||(typeof ref.deviceId === 'string' && ref.deviceId.length > 256) ||(ref.messageClientId !== undefined &&- (typeof ref.messageClientId !== 'string' || ref.messageClientId.length === 0 || ref.messageClientId.length > 256))+ (typeof ref.messageClientId !== 'string' ||+ ref.messageClientId.length === 0 ||+ ref.messageClientId.length > 256))) {throwIpcError('INVALID_PARAMS', 'sessionRefs contains an invalid reference');}@@ -9098,8 +9710,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)value: unknown,): AgentInputSessionReferenceContext[] | undefined => {if (value === undefined) return undefined;- if (!Array.isArray(value) || value.length > MAX_SESSION_REFERENCES || value.length !== (refs?.length ?? 0)) {- throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session reference snapshot count is invalid');+ if (+ !Array.isArray(value) ||+ value.length > MAX_SESSION_REFERENCES ||+ value.length !== (refs?.length ?? 0)+ ) {+ throwIpcError(+ 'SESSION_REFERENCE_UNAVAILABLE',+ 'remote session reference snapshot count is invalid',+ );}const contexts = value as AgentInputSessionReferenceContext[];let totalMessages = 0;@@ -9111,10 +9730,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)!context ||typeof context.sessionId !== 'string' ||context.sessionId.length > 256 ||- (context.title !== undefined && (typeof context.title !== 'string' || context.title.length > 128)) ||+ (context.title !== undefined &&+ (typeof context.title !== 'string' || context.title.length > 128)) ||!Array.isArray(context.messages)) {- throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session reference snapshot is invalid');+ throwIpcError(+ 'SESSION_REFERENCE_UNAVAILABLE',+ 'remote session reference snapshot is invalid',+ );}if (!ref ||@@ -9128,7 +9751,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)context.messageCount !== context.messages.length ||typeof context.truncated !== 'boolean') {- throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session reference snapshot does not match the request');+ throwIpcError(+ 'SESSION_REFERENCE_UNAVAILABLE',+ 'remote session reference snapshot does not match the request',+ );}if (context.terminal !== undefined) {const terminal = context.terminal;@@ -9137,12 +9763,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)typeof terminal !== 'object' ||Array.isArray(terminal) ||terminal.status !== 'error' ||- (- terminal.createdAt !== undefined &&- (typeof terminal.createdAt !== 'number' || !Number.isFinite(terminal.createdAt))- )+ (terminal.createdAt !== undefined &&+ (typeof terminal.createdAt !== 'number' || !Number.isFinite(terminal.createdAt)))) {- throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session reference terminal status is invalid');+ throwIpcError(+ 'SESSION_REFERENCE_UNAVAILABLE',+ 'remote session reference terminal status is invalid',+ );}// Strip unknown fields at this trust boundary. The marker is// intentionally status-only; provider error details must not cross@@ -9154,8 +9781,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}totalMessages += context.messages.length;for (const message of context.messages) {- if (!message || (message.role !== 'user' && message.role !== 'assistant') || typeof message.content !== 'string') {- throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session reference message is invalid');+ if (+ !message ||+ (message.role !== 'user' && message.role !== 'assistant') ||+ typeof message.content !== 'string'+ ) {+ throwIpcError(+ 'SESSION_REFERENCE_UNAVAILABLE',+ 'remote session reference message is invalid',+ );}totalTokens += estimateReferenceTokens(message.content);}@@ -9166,7 +9800,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)totalTokens > MAX_REFERENCE_TOKENS ||serializedTokens > MAX_REFERENCE_TOKENS - 128) {- throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session reference snapshot exceeds the shared budget');+ throwIpcError(+ 'SESSION_REFERENCE_UNAVAILABLE',+ 'remote session reference snapshot exceeds the shared budget',+ );}return contexts;};@@ -9174,13 +9811,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)value: unknown,opts?: { allowMissingTrustedContexts?: boolean },): AgentInputQueuedMessage => {- if (!value || typeof value !== 'object') throwIpcError('INVALID_PARAMS', 'queued message required');+ if (!value || typeof value !== 'object')+ throwIpcError('INVALID_PARAMS', 'queued message required');const msg = value as AgentInputQueuedMessage;if (typeof msg.clientId !== 'string' || !msg.clientId) {throwIpcError('INVALID_PARAMS', 'queued.clientId required');}if (typeof msg.text !== 'string') throwIpcError('INVALID_PARAMS', 'queued.text required');- if (typeof msg.persistedContent !== 'string') throwIpcError('INVALID_PARAMS', 'queued.persistedContent required');+ if (typeof msg.persistedContent !== 'string')+ throwIpcError('INVALID_PARAMS', 'queued.persistedContent required');if (!msg.chatMessage || typeof msg.chatMessage !== 'object') {throwIpcError('INVALID_PARAMS', 'queued.chatMessage required');}@@ -9188,9 +9827,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)throwIpcError('INVALID_PARAMS', 'queued.createOpts required');}if (- msg.createOpts.agentKind !== 'claude-code'- && msg.createOpts.agentKind !== 'codex'- && msg.createOpts.agentKind !== 'pi'+ msg.createOpts.agentKind !== 'claude-code' &&+ msg.createOpts.agentKind !== 'codex' &&+ msg.createOpts.agentKind !== 'pi') {throwIpcError('INVALID_PARAMS', 'queued.createOpts.agentKind invalid');}@@ -9202,7 +9841,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)delete normalized.sessionReferencesRequireTrustedSnapshot;return normalized;}- const contexts = requireTrustedReferenceContexts(refs, normalized.trustedSessionReferenceContexts);+ const contexts = requireTrustedReferenceContexts(+ refs,+ normalized.trustedSessionReferenceContexts,+ );if ((refs?.length ?? 0) > 0) normalized.sessionReferencesRequireTrustedSnapshot = true;else delete normalized.sessionReferencesRequireTrustedSnapshot;if (@@ -9210,7 +9852,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)!contexts &&!opts?.allowMissingTrustedContexts) {- throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session references were not resolved by the controller');+ throwIpcError(+ 'SESSION_REFERENCE_UNAVAILABLE',+ 'remote session references were not resolved by the controller',+ );}return normalized;};@@ -9264,105 +9909,614 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)};};+ /**+ * INPUT_ENQUEUE / INPUT_STEER 的发送前状态闸门。+ *+ * 这里不能复用 swallow-error 的展示查询:数据库暂时不可读时要让 renderer+ * 保留本地草稿并稍后重试,只有明确不存在或已删除才返回终态 NOT_FOUND。+ * archived 有意放行,因为桌面发送会先乐观 auto-unarchive,而 coordinator 仍可+ * 接受这条输入。+ */+ const getInputSessionRow = async (sid: string) => {+ try {+ const row = await getSessionRowSnapshotStrict(sid);+ if (!row || row.status === 'deleted') {+ throwIpcError('NOT_FOUND', `Session ${sid} not found`);+ }+ return row;+ } catch (error) {+ if (error instanceof Error && (error as { code?: unknown }).code === 'NOT_FOUND') {+ throw error;+ }+ log.warn('[device-link] input session state unavailable', {+ sessionId: sid,+ err: error instanceof Error ? error.message : String(error),+ });+ throwIpcError(+ 'INTERNAL',+ 'REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE: session state unavailable',+ );+ }+ };++ const readRemoteInputClearBoundaryPrecondition = (+ opts: unknown,+ ): { present: false } | { present: true; expected: number | null } => {+ if (+ !opts ||+ typeof opts !== 'object' ||+ !Object.prototype.hasOwnProperty.call(opts, 'expectedClearBoundaryMs')+ ) {+ return { present: false };+ }+ const expected = normalizeAgentInputClearBoundaryMs(+ (opts as { expectedClearBoundaryMs?: unknown }).expectedClearBoundaryMs,+ );+ if (expected === undefined) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'expectedClearBoundaryMs must be null or a non-negative finite number',+ );+ }+ return { present: true, expected };+ };++ const readExpectedInputGeneration = (opts: unknown): number | undefined => {+ if (+ !opts ||+ typeof opts !== 'object' ||+ Array.isArray(opts) ||+ !Object.prototype.hasOwnProperty.call(opts, 'expectedInputGeneration')+ ) {+ return undefined;+ }+ const value = (opts as { expectedInputGeneration?: unknown }).expectedInputGeneration;+ if (value === undefined) return undefined;+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'expectedInputGeneration must be a non-negative safe integer',+ );+ }+ return value;+ };++ const assertCurrentInputGeneration = (sid: string, expected: number | undefined): void => {+ if (expected === undefined || inputCoordinator.isGenerationCurrent(sid, expected)) return;+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'REMOTE_OPTIMISTIC_INPUT_SUPERSEDED: input preparation was superseded',+ );+ };++ const assertExpectedRemoteInputClearBoundary = (+ sid: string,+ precondition: { present: false } | { present: true; expected: number | null },+ sessionRow?: { clearedAt?: unknown } | null,+ ): void => {+ const inMemory = inputCoordinator.getClearBoundaryMs(sid);+ const persisted = normalizeAgentInputClearBoundaryMs(sessionRow?.clearedAt);+ // A clear is applied to the in-memory coordinator before the DB await. If+ // that await failed, accepting another remote control would make the new+ // epoch usable only until a host restart resurrects the old DB boundary.+ // Fail closed until a later clear/session snapshot catches the durable row+ // up; local renderer operations remain available.+ if (typeof inMemory === 'number' && (typeof persisted !== 'number' || persisted < inMemory)) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ `REMOTE_OPTIMISTIC_INPUT_CLEARED: clear boundary persistence pending (currentClearBoundaryMs=${inMemory})`,+ );+ }+ if (!precondition.present) return;+ const current =+ inMemory === null+ ? (persisted ?? null)+ : persisted === null || persisted === undefined+ ? inMemory+ : Math.max(inMemory, persisted);+ if (precondition.expected === current) return;+ throwIpcError(+ 'PRECONDITION_FAILED',+ `REMOTE_OPTIMISTIC_INPUT_CLEARED: expectedClearBoundaryMs=${precondition.expected ?? 'null'}; currentClearBoundaryMs=${current ?? 'null'}`,+ );+ };++ // Final vendor/steer fences run synchronously and cannot perform another DB+ // read. The IPC entry already compared the durable row; here we only need+ // to prove that the main-owned in-memory epoch did not advance meanwhile.+ const assertCurrentInputClearBoundary = (sid: string, expected: number | null): void => {+ const current = inputCoordinator.getClearBoundaryMs(sid);+ if (current === expected) return;+ throwIpcError(+ 'PRECONDITION_FAILED',+ `REMOTE_OPTIMISTIC_INPUT_CLEARED: expectedClearBoundaryMs=${expected ?? 'null'}; currentClearBoundaryMs=${current ?? 'null'}`,+ );+ };++ /**+ * The coordinator advances its in-memory clear epoch before the DB write.+ * If that write transiently fails, retry it at the next input/projection+ * boundary instead of leaving remote sends permanently sealed until restart.+ * A failed retry remains fail-closed for remote callers; local renderer+ * callers keep their historical fail-soft read semantics.+ */+ const retryPendingInputClearBoundary = async (+ sid: string,+ remote: boolean,+ row: { clearedAt?: unknown } | null,+ ): Promise<{ clearedAt?: unknown } | null> => {+ const inMemory = inputCoordinator.getClearBoundaryMs(sid);+ const persisted = normalizeAgentInputClearBoundaryMs(row?.clearedAt);+ if (typeof inMemory !== 'number' || (typeof persisted === 'number' && persisted >= inMemory)) {+ return row;+ }+ try {+ await clearSessionContextInDb(sid, inMemory);+ return remote ? await getInputSessionRow(sid) : await getSessionRowSnapshot(sid);+ } catch (err) {+ log.warn('pending clear boundary persistence retry failed', {+ sessionId: sid,+ boundaryMs: inMemory,+ remote,+ err: err instanceof Error ? err.message : String(err),+ });+ return row;+ }+ };++ const observeLocalInputClearBoundary = async (sid: string): Promise<void> => {+ const row = await getSessionRowSnapshot(sid);+ const durableRow = await retryPendingInputClearBoundary(sid, false, row);+ inputCoordinator.observeClearBoundary(sid, durableRow?.clearedAt);+ };++ const remoteInputClientIdWasPersisted = async (+ sid: string,+ clientId: string,+ ): Promise<boolean> => {+ try {+ const persisted = await getPersistedInputClientIds(sid, [clientId]);+ return persisted.has(clientId);+ } catch (err) {+ log.warn('[device-link] durable input clientId lookup unavailable', {+ sessionId: sid,+ clientId,+ err: err instanceof Error ? err.message : String(err),+ });+ // A failed dedupe query is fail-closed: retrying the same optimistic+ // record is safer than dispatching it twice after a host restart.+ throwIpcError(+ 'INTERNAL',+ 'REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE: input dedupe state unavailable',+ );+ }+ };++ const assertRemoteInputControlBoundary = async (+ sid: string,+ remote: boolean,+ opts: unknown,+ ): Promise<MainOwnedInputBoundaryStamp> => {+ // Capture the coordinator generation before the first database await. A+ // concurrent /clear replaces the in-memory state; after that await we must+ // reject the old request rather than treating the new generation as its+ // baseline (same-ms clears are why the generation travels with the token).+ const expectedInputGeneration = inputCoordinator.getGeneration(sid);+ const precondition = readRemoteInputClearBoundaryPrecondition(opts);+ assertRemoteInputClearNotInFlight(sid, remote);+ if (remote) {+ const row = await getInputSessionRow(sid);+ const durableRow = await retryPendingInputClearBoundary(sid, true, row);+ if (!inputCoordinator.isGenerationCurrent(sid, expectedInputGeneration)) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'REMOTE_OPTIMISTIC_INPUT_SUPERSEDED: input preparation was superseded',+ );+ }+ if (!durableRow) throwIpcError('NOT_FOUND', `Session ${sid} not found`);+ inputCoordinator.observeClearBoundary(sid, durableRow.clearedAt);+ assertRemoteInputClearNotInFlight(sid, true);+ assertExpectedRemoteInputClearBoundary(sid, precondition, durableRow);+ }+ return {+ expectedClearBoundaryMs: inputCoordinator.getClearBoundaryMs(sid),+ expectedInputGeneration,+ inputAbortSignal: inputCoordinator.getInputAbortSignal(sid, expectedInputGeneration),+ };+ };+ipcMain.handle(MAKER_INVOKE.INPUT_GET_PROJECTION, async (_e, sessionId: unknown) => {const sid = requireSessionId(sessionId);+ const remote = isDeviceLinkInvoke();+ assertRemoteInputClearNotInFlight(sid, remote);+ // The queue snapshot is process-local, but the clear boundary is durable.+ // Hydrate it for both renderer and device-link callers before restoring the+ // snapshot; otherwise a restarted controlled Desktop can resurrect items+ // that were cleared before the process restart. Remote callers keep the+ // strict session lookup, while the local renderer keeps the historical+ // fail-soft projection semantics when the DB is still booting.+ const sessionRow = remote ? await getInputSessionRow(sid) : await getSessionRowSnapshot(sid);+ const durableSessionRow = await retryPendingInputClearBoundary(sid, remote, sessionRow);+ inputCoordinator.observeClearBoundary(sid, durableSessionRow?.clearedAt);// 崩溃恢复(issue #761):renderer 打开会话首次取 projection 前,先把持久化的// 排队输入读回内存态,返回值即含恢复后的队列,不依赖 push 补发。// 失败时仍返回当前内存态 projection(宁可漏恢复也不阻塞会话打开)。await inputCoordinator.ensureQueueRestored(sid).catch(() => undefined);+ assertRemoteInputClearNotInFlight(sid, remote);return inputCoordinator.getProjection(sid);});// device-link 出方向:远程入队消息的 OSS 引用(files[] + persistedContent)在入队前一次性物化成本地// 临时文件(共用下载、用后删 OSS),保证喂 agent 的 files[] 与落库的 persistedContent 都是本地路径。// 本机会话无 OSS 引用 → materializeQueuedOssAttachments 原样返回,零开销。- ipcMain.handle(MAKER_INVOKE.INPUT_ENQUEUE, async (_e, sessionId: unknown, item: unknown, opts?: unknown) => {- const sid = requireSessionId(sessionId);- // 恢复先于入队:普通新输入保持 FIFO;「继续任务」由 coordinator 在完整旧队列- // 恢复后再明确插到队首,避免恢复竞态把它重新压到后面。- await inputCoordinator.ensureQueueRestored(sid).catch(() => undefined);- const queuedWithAttachments = (await materializeQueuedOssAttachments(- sid,- requireQueuedMessage(item),- )) as AgentInputQueuedMessage;- // 手机来源在**入队这一刻**盖章:drain 派发时已脱离本 invoke 的 async context。- // 无条件覆盖 —— item 来自 wire,客户端自填的 fromMobileClient 一律不生效。- const queued = stampMobileClientOrigin(- await hydrateQueuedAgentReferences(queuedWithAttachments),- isMobileControllerInvoke(),- );- const commitAutoTitle = await prepareDeviceLinkAutoTitle(sid, queued);-- // 「继续任务」durable ack 延后到 vendor dispatch 成功(onDispatchedUserTurn):- // 排队可取消时旧中断提示必须能恢复;accepted 但仍可能 cancelled-before-dispatch- // 时也不能提前 ack。续跑项本身由 coordinator 插到队首(普通输入仍 FIFO)。- const projection = inputCoordinator.enqueue(sid, queued, {- ...(opts && typeof opts === 'object' ? opts as { sendAtMs?: number } : undefined),- // INPUT_ENQUEUE 只承载显式用户输入(composer 发送 / UI trigger / device-link- // 被控端转投的用户消息):崩溃恢复出的暂停队列遇到显式输入即放行,解开- // 「继续任务/新消息全部排队直到重启」的死锁。Orca 自动投递走 main 侧直调- // enqueue,不带此 flag,恢复暂停语义不变。- resumeRestorePausedQueue: true,- });- commitAutoTitle();- return projection;- });+ ipcMain.handle(+ MAKER_INVOKE.INPUT_ENQUEUE,+ async (_e, sessionId: unknown, item: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ const deviceLinkInvoke = isDeviceLinkInvoke();+ const parsed = requireQueuedMessage(item);+ assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);+ const clearBoundaryPrecondition = readRemoteInputClearBoundaryPrecondition(opts);+ if (!deviceLinkInvoke) await observeLocalInputClearBoundary(sid);+ const inputGeneration = inputCoordinator.getGeneration(sid);+ const isCurrentInputGeneration = () =>+ inputCoordinator.isGenerationCurrent(sid, inputGeneration);+ const assertCurrentInputGeneration = () => {+ if (isCurrentInputGeneration()) return;+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'REMOTE_OPTIMISTIC_INPUT_SUPERSEDED: input preparation was superseded',+ );+ };+ // 已删除的远控任务必须在恢复队列、附件下载、引用水合和自动起名预检之前终止。+ // 入队前仍会再读一次,覆盖准备期间发生的删除竞态。+ let inputSessionRow = deviceLinkInvoke ? await getInputSessionRow(sid) : undefined;+ if (deviceLinkInvoke) {+ inputCoordinator.observeClearBoundary(sid, inputSessionRow?.clearedAt);+ assertRemoteInputClearNotInFlight(sid, true);+ assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, inputSessionRow);+ }+ assertCurrentInputGeneration();+ // 恢复先于入队:普通新输入保持 FIFO;「继续任务」由 coordinator 在完整旧队列+ // 恢复后再明确插到队首,避免恢复竞态把它重新压到后面。+ const restoreQueue = inputCoordinator.ensureQueueRestored(sid);+ if (deviceLinkInvoke) {+ await restoreQueue.catch(() => {+ throwIpcError(+ 'INTERNAL',+ 'REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE: input queue state unavailable',+ );+ });+ assertRemoteInputClearNotInFlight(sid, true);+ if (await remoteInputClientIdWasPersisted(sid, parsed.clientId)) {+ inputSessionRow = await getInputSessionRow(sid);+ inputCoordinator.observeClearBoundary(sid, inputSessionRow.clearedAt);+ assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, inputSessionRow);+ return inputCoordinator.getProjection(sid);+ }+ } else {+ await restoreQueue.catch(() => undefined);+ }+ assertCurrentInputGeneration();+ // A concurrent weak-link resend may already own this clientId in the+ // coordinator. Return the current projection before materialising a new+ // copy of its attachments.+ if (inputCoordinator.hasKnownClientId(sid, parsed.clientId)) {+ return inputCoordinator.getProjection(sid);+ }+ const materialized = await materializeQueuedOssAttachmentsDeferred(sid, parsed);+ const attachmentOwnerId = registerQueuedAttachmentOwnership(+ sid,+ parsed.clientId,+ materialized.cleanupLocalMaterialization,+ { cleanupAfterDurable: materialized.cleanupAfterAcceptance },+ );+ let acceptedByCoordinator = false;+ try {+ const queuedWithAttachments = materialized.item as AgentInputQueuedMessage;+ assertCurrentInputGeneration();+ // 手机来源在**入队这一刻**盖章:drain 派发时已脱离本 invoke 的 async context。+ // 无条件覆盖 —— item 来自 wire,客户端自填的 fromMobileClient 一律不生效。+ const queued = stampMobileClientOrigin(+ await hydrateQueuedAgentReferences(queuedWithAttachments),+ isMobileControllerInvoke(),+ );+ assertCurrentInputGeneration();+ const commitAutoTitle = await prepareDeviceLinkAutoTitle(sid, queued);+ assertCurrentInputGeneration();+ if (deviceLinkInvoke) {+ assertRemoteInputClearNotInFlight(sid, true);+ inputSessionRow = await getInputSessionRow(sid);+ inputCoordinator.observeClearBoundary(sid, inputSessionRow.clearedAt);+ assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, inputSessionRow);+ }+ assertCurrentInputGeneration();+ assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);++ // 「继续任务」durable ack 延后到 vendor dispatch 成功(onDispatchedUserTurn):+ // 排队可取消时旧中断提示必须能恢复;accepted 但仍可能 cancelled-before-dispatch+ // 时也不能提前 ack。续跑项本身由 coordinator 插到队首(普通输入仍 FIFO)。+ let duplicate = false;+ const projection = inputCoordinator.enqueue(sid, queued, {+ ...(opts && typeof opts === 'object' ? (opts as { sendAtMs?: number }) : undefined),+ // INPUT_ENQUEUE 只承载显式用户输入(composer 发送 / UI trigger / device-link+ // 被控端转投的用户消息):崩溃恢复出的暂停队列遇到显式输入即放行,解开+ // 「继续任务/新消息全部排队直到重启」的死锁。Orca 自动投递走 main 侧直调+ // enqueue,不带此 flag,恢复暂停语义不变。+ resumeRestorePausedQueue: true,+ onDuplicate: () => {+ duplicate = true;+ },+ });+ if (duplicate) {+ if (attachmentOwnerId) {+ await materialized.cleanupBeforeAcceptance?.();+ await discardSpecificQueuedAttachmentOwnership(sid, parsed.clientId, attachmentOwnerId);+ }+ return projection;+ }+ acceptedByCoordinator = true;+ if (attachmentOwnerId) {+ queuedAttachmentOwnership.activateCurrentOwner(sid, parsed.clientId, attachmentOwnerId);+ }+ markQueuedAttachmentDurableAfterSnapshot(sid, parsed.clientId, attachmentOwnerId);+ commitAutoTitle();+ return projection;+ } catch (err) {+ if (!acceptedByCoordinator) {+ await materialized.cleanupBeforeAcceptance?.();+ if (attachmentOwnerId) {+ await discardSpecificQueuedAttachmentOwnership(sid, parsed.clientId, attachmentOwnerId);+ }+ } else markQueuedAttachmentDurableAfterSnapshot(sid, parsed.clientId, attachmentOwnerId);+ throw err;+ }+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_COMPACT, async (_e, sessionId: unknown, createOpts: unknown, opts?: unknown) => {- const sid = requireSessionId(sessionId);- await inputCoordinator.ensureQueueRestored(sid).catch(() => undefined);- if (!createOpts || typeof createOpts !== 'object') {- throwIpcError('INVALID_PARAMS', 'createOpts required');- }- const typedCreateOpts = createOpts as AgentInputCreateOpts;- if (typedCreateOpts.agentKind !== 'claude-code') {- throwIpcError('INVALID_PARAMS', 'compact only supports claude-code sessions');- }- return inputCoordinator.compact(- sid,- typedCreateOpts,- opts && typeof opts === 'object' ? opts as { userName?: string } : undefined,- );- });+ ipcMain.handle(+ MAKER_INVOKE.INPUT_COMPACT,+ async (_e, sessionId: unknown, createOpts: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ const remote = isDeviceLinkInvoke();+ await assertRemoteInputControlBoundary(sid, remote, opts);+ if (!remote) await observeLocalInputClearBoundary(sid);+ await inputCoordinator.ensureQueueRestored(sid).catch(() => undefined);+ await assertRemoteInputControlBoundary(sid, remote, opts);+ if (!createOpts || typeof createOpts !== 'object') {+ throwIpcError('INVALID_PARAMS', 'createOpts required');+ }+ const typedCreateOpts = createOpts as AgentInputCreateOpts;+ if (typedCreateOpts.agentKind !== 'claude-code') {+ throwIpcError('INVALID_PARAMS', 'compact only supports claude-code sessions');+ }+ return inputCoordinator.compact(+ sid,+ typedCreateOpts,+ opts && typeof opts === 'object' ? (opts as { userName?: string }) : undefined,+ );+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_STEER, async (_e, sessionId: unknown, item: unknown, opts?: unknown) => {- const sid = requireSessionId(sessionId);- await inputCoordinator.ensureQueueRestored(sid).catch(() => undefined);- const steerOpts = opts && typeof opts === 'object'- ? opts as { removeFromQueue?: boolean; touchUserSend?: boolean }- : undefined;- const queuedWithAttachments = (await materializeQueuedOssAttachments(- sid,- requireQueuedMessage(item, {- // A device-link projection intentionally omits the trusted snapshot.+ ipcMain.handle(+ MAKER_INVOKE.INPUT_STEER,+ async (_e, sessionId: unknown, item: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ const deviceLinkInvoke = isDeviceLinkInvoke();+ const steerOpts =+ opts && typeof opts === 'object'+ ? (opts as {+ removeFromQueue?: boolean;+ touchUserSend?: boolean;+ } & AgentInputClearBoundaryOpts)+ : undefined;+ const parsed = requireQueuedMessage(item, {+ // A device-link projection intentionally omits the trusted snapshot;// Only the explicit remove-from-queue steer path may reattach it from// the main-owned row; all other IPC paths remain fail-closed here.- allowMissingTrustedContexts: isDeviceLinkInvoke() && steerOpts?.removeFromQueue === true,- }),- )) as AgentInputQueuedMessage;- // 与 enqueue 同:steer 投递也在本 invoke 的 async context 之外发生。- const queued = stampMobileClientOrigin(- await hydrateQueuedAgentReferences(queuedWithAttachments),- isMobileControllerInvoke(),- );- // 插话也补起名:远控用户完全可能趁这一轮还在跑就写下第一句话,只认入队的话- // 标题会一直停在首条纯附件消息的合成占位上(PR #510 review P1)。是否真的该- // 改名由 runSessionAutoTitle 权威判定。- const commitAutoTitle = await prepareDeviceLinkAutoTitle(sid, queued);- // steer 与 enqueue 不同:它会因同会话已有在飞 steer / Stop 边界 / 输入锁而- // 返回 false。必须等它落定、受理了才改名 —— 被拒的文本改掉默认名 / 合成占位 /- // fork 占位就是凭空改名(review P1)。- const accepted = await inputCoordinator.steer(- sid,- queued,- steerOpts,- );- if (accepted) commitAutoTitle();- return accepted;- });+ allowMissingTrustedContexts: deviceLinkInvoke && steerOpts?.removeFromQueue === true,+ });+ assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);+ const clearBoundaryPrecondition = readRemoteInputClearBoundaryPrecondition(opts);+ if (!deviceLinkInvoke) await observeLocalInputClearBoundary(sid);+ const inputGeneration = inputCoordinator.getGeneration(sid);+ const isCurrentInputGeneration = () =>+ inputCoordinator.isGenerationCurrent(sid, inputGeneration);+ const assertCurrentInputGeneration = () => {+ if (isCurrentInputGeneration()) return;+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'REMOTE_OPTIMISTIC_INPUT_SUPERSEDED: input preparation was superseded',+ );+ };+ // 与 enqueue 对称:先挡掉已经终态的远控任务,避免为必然失败的 steer+ // 恢复队列、下载附件或水合引用;真正 steer 前仍复核一次覆盖中途删除。+ let inputSessionRow = deviceLinkInvoke ? await getInputSessionRow(sid) : undefined;+ if (deviceLinkInvoke) {+ inputCoordinator.observeClearBoundary(sid, inputSessionRow?.clearedAt);+ assertRemoteInputClearNotInFlight(sid, true);+ assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, inputSessionRow);+ }+ assertCurrentInputGeneration();+ const restoreQueue = inputCoordinator.ensureQueueRestored(sid);+ if (deviceLinkInvoke) {+ await restoreQueue.catch(() => {+ throwIpcError(+ 'INTERNAL',+ 'REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE: input queue state unavailable',+ );+ });+ } else {+ await restoreQueue.catch(() => undefined);+ }+ assertCurrentInputGeneration();+ const isKnownSteerDuplicate = (): boolean => {+ const projection = inputCoordinator.getProjection(sid);+ const steeringStoredQueueItem =+ steerOpts?.removeFromQueue === true &&+ projection.pendingQueue.some((queued) => queued.clientId === parsed.clientId);+ return (+ projection.steeringQueueClientIds.includes(parsed.clientId) ||+ (!steeringStoredQueueItem && inputCoordinator.hasKnownClientId(sid, parsed.clientId))+ );+ };+ if (isKnownSteerDuplicate()) {+ // Only a still-present main-owned queue row may pass through the+ // remove-from-queue path. An in-flight promotion or any other known+ // clientId is a resend and must stop before attachment materialisation.+ return true;+ }+ if (deviceLinkInvoke && (await remoteInputClientIdWasPersisted(sid, parsed.clientId))) {+ // In-memory markers and the accepted-clientId window do not survive a+ // host restart, so the durable user row is the final idempotency boundary+ // for every remote steer variant, including a stale queue projection.+ inputSessionRow = await getInputSessionRow(sid);+ inputCoordinator.observeClearBoundary(sid, inputSessionRow.clearedAt);+ assertCurrentInputGeneration();+ assertRemoteInputClearNotInFlight(sid, true);+ assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, inputSessionRow);+ return true;+ }+ // The durable lookup above is an await boundary. Recheck coordinator+ // ownership before materialising so a concurrent first delivery cannot+ // make this retry create an unnecessary second local copy.+ if (isKnownSteerDuplicate()) return true;+ const steeringStoredQueueItem =+ steerOpts?.removeFromQueue === true &&+ inputCoordinator.hasPendingQueueItem(sid, parsed.clientId);+ // INPUT_STEER with removeFromQueue lets the coordinator replace the+ // projected row with its main-owned item. Do not materialise the+ // controller's copy first: it would register a second attachment owner+ // for a row whose local files already exist on the host.+ const materialized = steeringStoredQueueItem+ ? {+ item: parsed,+ cleanupAfterAcceptance: undefined,+ cleanupBeforeAcceptance: undefined,+ cleanupLocalMaterialization: undefined,+ }+ : await materializeQueuedOssAttachmentsDeferred(sid, parsed);+ const attachmentOwnerId = steeringStoredQueueItem+ ? null+ : registerQueuedAttachmentOwnership(+ sid,+ parsed.clientId,+ materialized.cleanupLocalMaterialization,+ { cleanupAfterDurable: materialized.cleanupAfterAcceptance },+ );+ let acceptedByCoordinator = false;+ let previousAttachmentOwnerId: string | null = null;+ const coordinatorRetainsClientId = (clientId: string): boolean => {+ const projection = inputCoordinator.getProjection(sid);+ return (+ projection.pendingQueue.some((item) => item.clientId === clientId) ||+ projection.steeringQueueClientIds.includes(clientId) ||+ (projection.recovery?.kind === 'queue-head' &&+ projection.recovery.clientId === clientId) ||+ (projection.recovery?.kind === 'active-turn' &&+ projection.recovery.item.clientId === clientId)+ );+ };+ try {+ const queuedWithAttachments = materialized.item as AgentInputQueuedMessage;+ assertCurrentInputGeneration();+ // 与 enqueue 同:steer 投递也在本 invoke 的 async context 之外发生。+ const queued = stampMobileClientOrigin(+ await hydrateQueuedAgentReferences(queuedWithAttachments),+ isMobileControllerInvoke(),+ );+ assertCurrentInputGeneration();+ // 插话也补起名:远控用户完全可能趁这一轮还在跑就写下第一句话,只认入队的话+ // 标题会一直停在首条纯附件消息的合成占位上(PR #510 review P1)。是否真的该+ // 改名由 runSessionAutoTitle 权威判定。+ const commitAutoTitle = await prepareDeviceLinkAutoTitle(sid, queued);+ assertCurrentInputGeneration();+ if (deviceLinkInvoke) {+ assertRemoteInputClearNotInFlight(sid, true);+ inputSessionRow = await getInputSessionRow(sid);+ inputCoordinator.observeClearBoundary(sid, inputSessionRow.clearedAt);+ assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, inputSessionRow);+ }+ assertCurrentInputGeneration();+ assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);+ // Attachment hydration, auto-title preparation and the final session+ // lookup all yield. Close the last race before activating ownership:+ // coordinator.steer sets its marker synchronously, so after this check+ // only one request can become the current owner for this clientId.+ if (isKnownSteerDuplicate()) {+ await materialized.cleanupBeforeAcceptance?.();+ if (attachmentOwnerId) {+ await discardSpecificQueuedAttachmentOwnership(+ sid,+ parsed.clientId,+ attachmentOwnerId,+ );+ }+ return true;+ }+ // steer 与 enqueue 不同:它会因同会话已有在飞 steer / Stop 边界 / 输入锁而+ // 返回 false。必须等它落定、受理了才改名 —— 被拒的文本改掉默认名 / 合成占位 /+ // fork 占位就是凭空改名(review P1)。+ if (attachmentOwnerId) {+ previousAttachmentOwnerId = queuedAttachmentOwnership.activateCurrentOwner(+ sid,+ parsed.clientId,+ attachmentOwnerId,+ );+ }+ const accepted = await inputCoordinator.steer(sid, queued, steerOpts);+ acceptedByCoordinator = accepted;+ assertCurrentInputGeneration();+ if (accepted) {+ markQueuedAttachmentDurableAfterSnapshot(sid, parsed.clientId, attachmentOwnerId);+ commitAutoTitle();+ } else {+ const retained = coordinatorRetainsClientId(queued.clientId);+ if (retained) {+ markQueuedAttachmentDurableAfterSnapshot(sid, parsed.clientId, attachmentOwnerId);+ } else {+ if (attachmentOwnerId) {+ queuedAttachmentOwnership.restoreCurrentOwner(+ sid,+ parsed.clientId,+ previousAttachmentOwnerId,+ );+ }+ await materialized.cleanupBeforeAcceptance?.();+ if (attachmentOwnerId) {+ await discardSpecificQueuedAttachmentOwnership(+ sid,+ parsed.clientId,+ attachmentOwnerId,+ );+ }+ }+ }+ return accepted;+ } catch (err) {+ if (acceptedByCoordinator || coordinatorRetainsClientId(parsed.clientId)) {+ markQueuedAttachmentDurableAfterSnapshot(sid, parsed.clientId, attachmentOwnerId);+ } else {+ if (attachmentOwnerId) {+ queuedAttachmentOwnership.restoreCurrentOwner(+ sid,+ parsed.clientId,+ previousAttachmentOwnerId,+ );+ }+ await materialized.cleanupBeforeAcceptance?.();+ if (attachmentOwnerId) {+ await discardSpecificQueuedAttachmentOwnership(sid, parsed.clientId, attachmentOwnerId);+ }+ }+ throw err;+ }+ },+ );ipcMain.handle(MAKER_INVOKE.INPUT_STOP, async (_e, sessionId: unknown, opts?: unknown) => {const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);// 这三类续跑撤销都是同步操作,必须早于 goal/DB await;// 否则退避 timer 能在用户已点 Stop 后抢先发出下一轮。resetAutomaticRecoveryForExplicitStop(sid);@@ -9372,7 +10526,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const result = inputCoordinator.stop(sid,opts && typeof opts === 'object'- ? opts as { keepQueue?: boolean; pauseQueue?: boolean }+ ? (opts as {+ keepQueue?: boolean;+ pauseQueue?: boolean;+ expectedClearBoundaryMs?: number | null;+ }): undefined,);// Thread 1 fix: stop() clears pendingCompacts (and optionally pendingQueue)@@ -9385,156 +10543,290 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return result;});- ipcMain.handle(MAKER_INVOKE.INPUT_RESUME, (_e, sessionId: unknown) =>- inputCoordinator.resume(requireSessionId(sessionId)));+ ipcMain.handle(MAKER_INVOKE.INPUT_RESUME, async (_e, sessionId: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);+ return inputCoordinator.resume(sid);+ });- ipcMain.handle(MAKER_INVOKE.INPUT_RETRY_LAST_ERROR, (_e, sessionId: unknown) =>- inputCoordinator.retryLastError(requireSessionId(sessionId)));+ ipcMain.handle(+ MAKER_INVOKE.INPUT_RETRY_LAST_ERROR,+ async (_e, sessionId: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);+ return inputCoordinator.retryLastError(sid);+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_CLEAR_ERROR, (_e, sessionId: unknown) =>- inputCoordinator.clearError(requireSessionId(sessionId)));+ ipcMain.handle(MAKER_INVOKE.INPUT_CLEAR_ERROR, async (_e, sessionId: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);+ return inputCoordinator.clearError(sid);+ });// renderer auth-retry 放弃时(catch / guard fall-through)调回 main 补落持久化。// main 侧在 isRemoteAuthRetry 条件下跳过了 onTurnErrorEvent;此处覆盖"重试失败/不能重试"两路。// agentMetaRaw:renderer 传来的 event.agentMeta(可选),用于 flushAssistantBlock 边界 meta 兜底// 与 dedup key(requestId/uuid),与 register.ts 主路径 onTurnErrorEvent(sid, errData, event.agentMeta) 对称。- ipcMain.handle(MAKER_INVOKE.PERSIST_TURN_ERROR_DEFERRED, (_e, sessionId: unknown, errDataRaw: unknown, agentMetaRaw: unknown) => {- const sid = requireSessionId(sessionId);- const errData = errDataRaw != null && typeof errDataRaw === 'object'- ? errDataRaw as { message?: unknown; reason?: unknown; sdkError?: unknown }- : null;- const agentMeta = agentMetaRaw != null && typeof agentMetaRaw === 'object'- ? agentMetaRaw as AgentMeta- : null;- onTurnErrorEvent(sid, errData, agentMeta);- getAgentIslandService()?.resolveDeferredRemoteAuthRetryError(sid);- });+ ipcMain.handle(+ MAKER_INVOKE.PERSIST_TURN_ERROR_DEFERRED,+ (_e, sessionId: unknown, errDataRaw: unknown, agentMetaRaw: unknown) => {+ const sid = requireSessionId(sessionId);+ const errData =+ errDataRaw != null && typeof errDataRaw === 'object'+ ? (errDataRaw as { message?: unknown; reason?: unknown; sdkError?: unknown })+ : null;+ const agentMeta =+ agentMetaRaw != null && typeof agentMetaRaw === 'object'+ ? (agentMetaRaw as AgentMeta)+ : null;+ onTurnErrorEvent(sid, errData, agentMeta);+ getAgentIslandService()?.resolveDeferredRemoteAuthRetryError(sid);+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_REMOVE, (_e, sessionId: unknown, clientId: unknown) => {- const sid = requireSessionId(sessionId);- const cid = requireClientId(clientId);- const result = inputCoordinator.remove(sid, cid);- if (!inputCoordinator.hasPendingQueuedWork(sid)) {- getAgentIslandService()?.notifyQueueEmptied(sid);- }- return result;- });+ ipcMain.handle(+ MAKER_INVOKE.INPUT_REMOVE,+ async (_e, sessionId: unknown, clientId: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);+ const cid = requireClientId(clientId);+ const result = inputCoordinator.remove(sid, cid);+ if (!inputCoordinator.hasPendingQueuedWork(sid)) {+ getAgentIslandService()?.notifyQueueEmptied(sid);+ }+ return result;+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_UPDATE_TEXT, (- _e,- sessionId: unknown,- clientId: unknown,- newText: unknown,- sessionRefs?: unknown,- trustedContexts?: unknown,- ) => {- if (typeof newText !== 'string') throwIpcError('INVALID_PARAMS', 'newText required');- const refs = requireSessionRefs(sessionRefs);- const remote = isDeviceLinkInvoke();- const contexts = remote ? requireTrustedReferenceContexts(refs, trustedContexts) : undefined;- if (remote && (refs?.length ?? 0) > 0 && !contexts) {- throwIpcError('SESSION_REFERENCE_UNAVAILABLE', 'remote session references were not resolved by the controller');- }- return inputCoordinator.updateText(- requireSessionId(sessionId),- requireClientId(clientId),- newText,- refs,- contexts,- remote,- );- });+ ipcMain.handle(+ MAKER_INVOKE.INPUT_UPDATE_TEXT,+ async (+ _e,+ sessionId: unknown,+ clientId: unknown,+ newText: unknown,+ sessionRefs?: unknown,+ trustedContexts?: unknown,+ opts?: unknown,+ ) => {+ if (typeof newText !== 'string') throwIpcError('INVALID_PARAMS', 'newText required');+ const refs = requireSessionRefs(sessionRefs);+ const remote = isDeviceLinkInvoke();+ const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, remote, opts);+ const contexts = remote ? requireTrustedReferenceContexts(refs, trustedContexts) : undefined;+ if (remote && (refs?.length ?? 0) > 0 && !contexts) {+ throwIpcError(+ 'SESSION_REFERENCE_UNAVAILABLE',+ 'remote session references were not resolved by the controller',+ );+ }+ return inputCoordinator.updateText(+ sid,+ requireClientId(clientId),+ newText,+ refs,+ contexts,+ remote,+ );+ },+ );// 与 enqueue/steer 同一套物化:远程编辑保存的新附件可能是 OSS 引用,入队前物化成本地文件。- ipcMain.handle(MAKER_INVOKE.INPUT_UPDATE_CONTENT, async (_e, sessionId: unknown, clientId: unknown, item: unknown) => {- const sid = requireSessionId(sessionId);- const cid = requireClientId(clientId);- const remote = isDeviceLinkInvoke();- const parsed = requireQueuedMessage(item);- const queuedWithAttachments = (await materializeQueuedOssAttachments(- sid,- parsed,- )) as AgentInputQueuedMessage;- const queued = await hydrateQueuedAgentReferences(queuedWithAttachments);- // 旧 device-link update-content 调用没有 side-channel sessionRefs;显式- // 传空数组,避免 updateQueuedMessageContent 从完整文本重新解析控制端坐标。- const update = remote && parsed.sessionRefs === undefined- ? { ...queued, sessionRefs: [] }- : queued;- return inputCoordinator.updateContent(sid, cid, update);- });+ ipcMain.handle(+ MAKER_INVOKE.INPUT_UPDATE_CONTENT,+ async (_e, sessionId: unknown, clientId: unknown, item: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ const cid = requireClientId(clientId);+ const remote = isDeviceLinkInvoke();+ const clearBoundaryPrecondition = readRemoteInputClearBoundaryPrecondition(opts);+ await assertRemoteInputControlBoundary(sid, remote, opts);+ const inputGeneration = inputCoordinator.getGeneration(sid);+ const isCurrentInputGeneration = () =>+ inputCoordinator.isGenerationCurrent(sid, inputGeneration);+ const assertCurrentInputGeneration = () => {+ if (isCurrentInputGeneration()) return;+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'REMOTE_OPTIMISTIC_INPUT_SUPERSEDED: input preparation was superseded',+ );+ };+ // 与 enqueue/steer 对称:附件物化和引用水合都会跨 await。clear 期间启动的+ // 编辑必须只返回新投影,不能把旧 clientId 的内容写进清空后的队列。+ if (remote) {+ const row = await getInputSessionRow(sid);+ inputCoordinator.observeClearBoundary(sid, row.clearedAt);+ assertRemoteInputClearNotInFlight(sid, true);+ assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, row);+ }+ if (!isCurrentInputGeneration()) return inputCoordinator.getProjection(sid);+ const parsed = requireQueuedMessage(item);+ if (parsed.clientId !== cid) {+ throwIpcError('INVALID_PARAMS', 'queued.clientId must match clientId');+ }+ // Do not download/materialise an edit for a row that has already left the+ // pending queue. The row can disappear while the async preparation is in+ // flight as well; updateContentWithResult below handles that second race.+ if (!inputCoordinator.hasPendingQueueItem(sid, cid)) {+ return inputCoordinator.getProjection(sid);+ }+ const materialized = await materializeQueuedOssAttachmentsDeferred(sid, parsed);+ const attachmentOwnerId = registerQueuedAttachmentOwnership(+ sid,+ cid,+ materialized.cleanupLocalMaterialization,+ { cleanupAfterDurable: materialized.cleanupAfterAcceptance },+ );+ let acceptedByCoordinator = false;+ try {+ const queuedWithAttachments = materialized.item as AgentInputQueuedMessage;+ assertCurrentInputGeneration();+ const queued = await hydrateQueuedAgentReferences(queuedWithAttachments);+ assertCurrentInputGeneration();+ // 旧 device-link update-content 调用没有 side-channel sessionRefs;显式+ // 传空数组,避免 updateQueuedMessageContent 从完整文本重新解析控制端坐标。+ const update =+ remote && parsed.sessionRefs === undefined ? { ...queued, sessionRefs: [] } : queued;+ if (remote) {+ const row = await getInputSessionRow(sid);+ inputCoordinator.observeClearBoundary(sid, row.clearedAt);+ assertRemoteInputClearNotInFlight(sid, true);+ assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, row);+ }+ assertCurrentInputGeneration();+ const result = inputCoordinator.updateContentWithResult(sid, cid, update);+ acceptedByCoordinator = result.updated;+ if (result.updated) {+ // The replacement supersedes any older local materialisation owned by+ // this clientId. Keep the new owner alive for the queue item's later+ // persistence/discard boundary, but release old refs now.+ if (attachmentOwnerId) {+ queuedAttachmentOwnership.activateCurrentOwner(sid, cid, attachmentOwnerId);+ }+ discardQueuedAttachmentOwnership(sid, cid, attachmentOwnerId ?? undefined);+ markQueuedAttachmentDurableAfterSnapshot(sid, cid, attachmentOwnerId);+ } else {+ await materialized.cleanupBeforeAcceptance?.();+ if (attachmentOwnerId) {+ await discardSpecificQueuedAttachmentOwnership(sid, cid, attachmentOwnerId);+ }+ }+ return result.projection;+ } catch (err) {+ if (!acceptedByCoordinator) await materialized.cleanupBeforeAcceptance?.();+ else markQueuedAttachmentDurableAfterSnapshot(sid, cid, attachmentOwnerId);+ if (attachmentOwnerId && !acceptedByCoordinator) {+ await discardSpecificQueuedAttachmentOwnership(sid, cid, attachmentOwnerId);+ }+ throw err;+ }+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_MOVE, (_e, sessionId: unknown, clientId: unknown, targetIndex: unknown) => {- if (typeof targetIndex !== 'number' || !Number.isFinite(targetIndex)) {- throwIpcError('INVALID_PARAMS', 'targetIndex required');- }- return inputCoordinator.move(requireSessionId(sessionId), requireClientId(clientId), targetIndex);- });+ ipcMain.handle(+ MAKER_INVOKE.INPUT_MOVE,+ async (_e, sessionId: unknown, clientId: unknown, targetIndex: unknown, opts?: unknown) => {+ if (typeof targetIndex !== 'number' || !Number.isFinite(targetIndex)) {+ throwIpcError('INVALID_PARAMS', 'targetIndex required');+ }+ const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);+ return inputCoordinator.move(sid, requireClientId(clientId), targetIndex);+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_SET_EXPANDED, (_e, sessionId: unknown, expanded: unknown) =>- inputCoordinator.setExpanded(requireSessionId(sessionId), expanded === true));+ ipcMain.handle(+ MAKER_INVOKE.INPUT_SET_EXPANDED,+ async (_e, sessionId: unknown, expanded: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);+ return inputCoordinator.setExpanded(sid, expanded === true);+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_SET_INTERACTION_LOCK, (_e, sessionId: unknown, lockId: unknown, locked: unknown) =>- inputCoordinator.setInteractionLock(requireSessionId(sessionId), requireClientId(lockId), locked === true));+ ipcMain.handle(+ MAKER_INVOKE.INPUT_SET_INTERACTION_LOCK,+ async (_e, sessionId: unknown, lockId: unknown, locked: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);+ return inputCoordinator.setInteractionLock(sid, requireClientId(lockId), locked === true);+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_SET_EDIT_LOCK, (_e, sessionId: unknown, clientId: unknown, locked: unknown) =>- inputCoordinator.setEditLock(requireSessionId(sessionId), requireClientId(clientId), locked === true));+ ipcMain.handle(+ MAKER_INVOKE.INPUT_SET_EDIT_LOCK,+ async (_e, sessionId: unknown, clientId: unknown, locked: unknown, opts?: unknown) => {+ const sid = requireSessionId(sessionId);+ await assertRemoteInputControlBoundary(sid, isDeviceLinkInvoke(), opts);+ return inputCoordinator.setEditLock(sid, requireClientId(clientId), locked === true);+ },+ );- ipcMain.handle(MAKER_INVOKE.INPUT_CLEAR_SESSION, async (_e, sessionId: unknown, clearedAt: unknown) => {- if (- clearedAt !== undefined- && (typeof clearedAt !== 'string' || !Number.isFinite(new Date(clearedAt).getTime()))- ) {- throwIpcError('INVALID_PARAMS', 'clearedAt must be an ISO timestamp');- }- const sid = requireSessionId(sessionId);- const remoteInvoke = isDeviceLinkInvoke();- const clearBoundary = resolveClearSessionBoundary({- clearedAt: typeof clearedAt === 'string' ? clearedAt : undefined,- isRemoteInvoke: remoteInvoke,- });- const projection = inputCoordinator.clearSession(sid, clearBoundary);- resetAutomaticRecoveryForExplicitStop(sid);- // 丢弃缓存的待注入交接 / fork 来源标记:它们是按 clear 之前的历史算出来的,- // DB 侧的 cleared_at 抑制拦不住已经落进 registry 内存的那一份(首发被拒后- // 缓存仍在),下次 send 会把旧血缘灌进用户刚显式清空的上下文。- //- // 用 invalidate(留 null 墓碑)而不是 clear(删条目):删条目会让后续 send 回落到- // DB 重建,把旧交接捞回来再缓存住。墓碑同步生效,窗口内的 send 立刻拿到 null;- // clear 纪元则要等下面 cleared_at 落库之后才推进。- agentHandoffPending.invalidate(sid);- getAgentIslandService()?.notifyQueueEmptied(sid);- // 清上下文后,active 目标失去其依据(objective 引用的内容已被抹掉)→ 一并清除目标。- goalClearObserver?.(sid);- // 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;- });+ ipcMain.handle(+ MAKER_INVOKE.INPUT_CLEAR_SESSION,+ async (_e, sessionId: unknown, clearedAt: unknown) => {+ if (+ clearedAt !== undefined &&+ (typeof clearedAt !== 'string' || !Number.isFinite(new Date(clearedAt).getTime()))+ ) {+ throwIpcError('INVALID_PARAMS', 'clearedAt must be an ISO timestamp');+ }+ const sid = requireSessionId(sessionId);+ // Fence remote content-bearing controls for the whole clear lifecycle,+ // including the DB await below. Local clear is gated too so a remote+ // controller cannot enter the same sealing window through another peer.+ beginRemoteInputClearGate(sid);+ try {+ const remoteInvoke = isDeviceLinkInvoke();+ const clearBoundary = resolveClearSessionBoundary({+ clearedAt: typeof clearedAt === 'string' ? clearedAt : undefined,+ isRemoteInvoke: remoteInvoke,+ });+ const projection = inputCoordinator.clearSession(sid, clearBoundary);+ resetAutomaticRecoveryForExplicitStop(sid);+ // 丢弃缓存的待注入交接 / fork 来源标记:它们是按 clear 之前的历史算出来的,+ // DB 侧的 cleared_at 抑制拦不住已经落进 registry 内存的那一份(首发被拒后+ // 缓存仍在),下次 send 会把旧血缘灌进用户刚显式清空的上下文。+ //+ // 用 invalidate(留 null 墓碑)而不是 clear(删条目):删条目会让后续 send 回落到+ // DB 重建,把旧交接捞回来再缓存住。墓碑同步生效,窗口内的 send 立刻拿到 null;+ // clear 纪元则要等下面 cleared_at 落库之后才推进。+ agentHandoffPending.invalidate(sid);+ getAgentIslandService()?.notifyQueueEmptied(sid);+ // 清上下文后,active 目标失去其依据(objective 引用的内容已被抹掉)→ 一并清除目标。+ goalClearObserver?.(sid);+ // 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) {+ // The in-memory fence is still authoritative for this process. Keep+ // /clear remains a local cleanup action even when persistence fails;+ // surface the failure in logs, and+ // let the next input/projection boundary retry the durable token.+ log.error('clear session context persist failed', {+ sessionId: sid,+ remoteInvoke,+ err: err instanceof Error ? err.message : String(err),+ });+ }+ return projection;+ } finally {+ // 落库尝试结束后封边界:重立墓碑(清掉这段 await 里用 clear 前纪元挤进来的那份)+ // + 推进纪元(挡住后面才写回的那批)。顺序不可颠倒,理由见 sealClearBoundary 注释。+ agentHandoffPending.sealClearBoundary(sid);+ endRemoteInputClearGate(sid);+ }+ },+ );ipcMain.handle(MAKER_INVOKE.ABORT_SESSION, async (_e, sessionId: unknown) => {if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');@@ -9619,46 +10911,48 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}));});- ipcMain.handle(MAKER_INVOKE.RESOLVE_INTERACTION, (event, requestId: unknown, decision: unknown) => {- if (typeof requestId !== 'string') throwIpcError('INVALID_PARAMS', 'requestId required');- if (- isPluginSetupInteractionDecision(decision) &&- !parseGhostSetupInteractionCommand(decision)- ) {- throwIpcError('INVALID_PARAMS', 'invalid plugin setup decision');- }- // permission / ask / plan and setup cancellation remain remotely- // resolvable. Host-owned setup side effects and Desktop-only confirmations- // may only originate from the trusted local Desktop.- assertResolveInteractionOrigin(- decision,- isPendingDesktopOnlyConfirmation(requestId),- );- let pluginSetupResponseTarget: GhostSetupInteractionResponseTarget | undefined;- if (isPluginSetupInteractionDecision(decision) && !isDeviceLinkInvoke()) {- assertTrustedAppRendererEvent(event);- if (decision.action === 'run_action') {- // Electron's real sender identity stays outside the untrusted command- // payload and is carried only through the Host-owned action path.- pluginSetupResponseTarget = event.sender;- }- }- if (!resolvePendingInteraction(requestId, decision as InteractionDecision)) {- if (isPermissionInteractionDecision(decision)) {- handleAgentIslandInteractionDismissedByRequestId(requestId);- }- // agent interaction 没命中 → 可能是 issue 确认卡(kind='issue_confirm',- // pending 在 issueConfirmBridge 自己的 map 里)或批量改名确认卡。- // 三边都 miss 才告警。- if (issueConfirmBridge.resolve(requestId, decision)) return;- if (renameSessionsConfirmBridge.resolve(requestId, decision)) return;- if (ghostGrantConfirmBridge.resolve(requestId, decision)) return;- if (ghostSetupInteractionBridge.resolve(requestId, decision, pluginSetupResponseTarget)) {- return;+ ipcMain.handle(+ MAKER_INVOKE.RESOLVE_INTERACTION,+ (event, requestId: unknown, decision: unknown) => {+ if (typeof requestId !== 'string') throwIpcError('INVALID_PARAMS', 'requestId required');+ if (+ isPluginSetupInteractionDecision(decision) &&+ !parseGhostSetupInteractionCommand(decision)+ ) {+ throwIpcError('INVALID_PARAMS', 'invalid plugin setup decision');+ }+ // permission / ask / plan and setup cancellation remain remotely+ // resolvable. Host-owned setup side effects and Desktop-only confirmations+ // may only originate from the trusted local Desktop.+ assertResolveInteractionOrigin(decision, isPendingDesktopOnlyConfirmation(requestId));+ let pluginSetupResponseTarget: GhostSetupInteractionResponseTarget | undefined;+ if (isPluginSetupInteractionDecision(decision) && !isDeviceLinkInvoke()) {+ assertTrustedAppRendererEvent(event);+ if (decision.action === 'run_action') {+ // Electron's real sender identity stays outside the untrusted command+ // payload and is carried only through the Host-owned action path.+ pluginSetupResponseTarget = event.sender;+ }}- log.warn('resolve-interaction: no pending resolver (likely already dismissed/timed out)', { requestId });- }- });+ if (!resolvePendingInteraction(requestId, decision as InteractionDecision)) {+ if (isPermissionInteractionDecision(decision)) {+ handleAgentIslandInteractionDismissedByRequestId(requestId);+ }+ // agent interaction 没命中 → 可能是 issue 确认卡(kind='issue_confirm',+ // pending 在 issueConfirmBridge 自己的 map 里)或批量改名确认卡。+ // 三边都 miss 才告警。+ if (issueConfirmBridge.resolve(requestId, decision)) return;+ if (renameSessionsConfirmBridge.resolve(requestId, decision)) return;+ if (ghostGrantConfirmBridge.resolve(requestId, decision)) return;+ if (ghostSetupInteractionBridge.resolve(requestId, decision, pluginSetupResponseTarget)) {+ return;+ }+ log.warn('resolve-interaction: no pending resolver (likely already dismissed/timed out)', {+ requestId,+ });+ }+ },+ );ipcMain.handle(MAKER_INVOKE.PLUGIN_SETUP_SUBMIT_INLINE, (event, raw: unknown) => {assertTrustedAppRendererEvent(event);@@ -9681,189 +10975,177 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// session 不存在(被 close / 还没 send 创建出来)就 no-op 不报错, 让 renderer// 可以乐观调用 (UI 更新先行, IPC 失败也不会回滚 UI, 老 agentManager 同语义)。- ipcMain.handle(MAKER_INVOKE.SET_MODEL, async (- _e,- sessionId: unknown,- model: unknown,- providerId?: unknown,- expectedAgentSwitchRevision?: unknown,- selection?: unknown,- ) => {- if (typeof sessionId !== 'string' || typeof model !== 'string') {- throwIpcError('INVALID_PARAMS', 'sessionId + model required');- }- const normalizedWireArgs = normalizeDeviceLinkSetModelWireArgs(- isDeviceLinkInvoke(),- deviceLinkInvokeControllerSupports(- CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,- ),- providerId,- expectedAgentSwitchRevision,- selection,- );- providerId = normalizedWireArgs.providerId;- expectedAgentSwitchRevision = normalizedWireArgs.expectedAgentSwitchRevision;- selection = normalizedWireArgs.selection;- if (- providerId !== undefined &&- providerId !== null &&- typeof providerId !== 'string'- ) {- throwIpcError('INVALID_PARAMS', 'providerId must be string, null, or undefined');- }- if (- expectedAgentSwitchRevision !== undefined &&- (typeof expectedAgentSwitchRevision !== 'number' ||- !Number.isSafeInteger(expectedAgentSwitchRevision) ||- expectedAgentSwitchRevision < 0)- ) {- throwIpcError('INVALID_PARAMS', 'expectedAgentSwitchRevision must be a non-negative integer');- }- if (- selection !== undefined &&- (- selection === null ||- typeof selection !== 'object' ||- Array.isArray(selection) ||- typeof (selection as { effort?: unknown }).effort !== 'string' ||- typeof (selection as { fastMode?: unknown }).fastMode !== 'boolean'- )- ) {- throwIpcError('INVALID_PARAMS', 'selection must contain effort + fastMode');- }- const atomicSelection = selection as- | { effort: string; fastMode: boolean }- | undefined;- // 与 send 事务共用 session 锁:发送时刻执行的跨引擎切换必须先落定,- // 后到的 SET_MODEL 才能写 route。否则切换 DB await 恢复后会用旧 provider- // 覆盖用户刚选的新 route,形成 DB 与进程内路由分叉。- return withSendToSessionLock(sessionId, async () => {- // 同引擎重选是 switch ack 后的第二段写入。另一控制端若在两段之间更新(含- // set→clear ABA),修订号已变化:旧 SET_MODEL 必须在任何 route/DB 副作用前让位。+ ipcMain.handle(+ MAKER_INVOKE.SET_MODEL,+ async (+ _e,+ sessionId: unknown,+ model: unknown,+ providerId?: unknown,+ expectedAgentSwitchRevision?: unknown,+ selection?: unknown,+ ) => {+ if (typeof sessionId !== 'string' || typeof model !== 'string') {+ throwIpcError('INVALID_PARAMS', 'sessionId + model required');+ }+ const normalizedWireArgs = normalizeDeviceLinkSetModelWireArgs(+ isDeviceLinkInvoke(),+ deviceLinkInvokeControllerSupports(+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,+ ),+ providerId,+ expectedAgentSwitchRevision,+ selection,+ );+ providerId = normalizedWireArgs.providerId;+ expectedAgentSwitchRevision = normalizedWireArgs.expectedAgentSwitchRevision;+ selection = normalizedWireArgs.selection;+ if (providerId !== undefined && providerId !== null && typeof providerId !== 'string') {+ throwIpcError('INVALID_PARAMS', 'providerId must be string, null, or undefined');+ }if (- typeof expectedAgentSwitchRevision === 'number' &&- agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision+ expectedAgentSwitchRevision !== undefined &&+ (typeof expectedAgentSwitchRevision !== 'number' ||+ !Number.isSafeInteger(expectedAgentSwitchRevision) ||+ expectedAgentSwitchRevision < 0)) {- return { deferred: false, superseded: true };- }- // 停用轴准入(PR #744 review;第十二轮移入锁内):切换模型是一次新的路由选择,- // 不得切到用户停用的模型 / 来源(本机选择器已过滤,但本 channel 在 device-link- // allowlist 内,老控制端可直接点名)。裁决必须在拿到会话锁**之后**执行 ——- // 排队等待期间目标可能刚被停用,而同凭证族的变更即时生效、不经 deferred 收口- // 的重裁决,锁前裁决结果可能已过期。会话当前正用着的停用模型不受影响,这里只- // 拦「切过去」;隐式来源的原生默认落点被停用而有启用替代拷贝时,以显式来源- // 落地(与 bootstrapSession 同语义)。agentKind 读不到(会话行缺失等)时不拦。- // DB 存的是 'cc' | 'codex'(messages.agent_kind 口径),目录侧是 AgentKind。- let effectiveProviderId = providerId;- {- const dbAgentKind = getSessionDbAgentKind(sessionId);- if (dbAgentKind) {- const reroute = await assertModelRouteUsable(- dbToMakerAgentKind(dbAgentKind),- model,- typeof providerId === 'string' ? providerId : null,- );- if (reroute && typeof providerId !== 'string') effectiveProviderId = reroute;- }- }- try {- const result = await applySetModelThenCancelAgentSwitchIntent(- agentSwitchPending,- sessionId,- () => applyRuntimeSetModelChange({- maker,- sessionId,- model,- providerId: effectiveProviderId,- ...(atomicSelection- ? {- effort: atomicSelection.effort as- | 'minimal'- | 'low'- | 'medium'- | 'high'- | 'xhigh'- | 'max'- | 'ultra',- }- : {}),- isSessionInTurn,- registerPendingCredentialSwitch: registerPendingCredentialSwitchForSession,- clearPendingCredentialSwitch: clearPendingCredentialSwitchForSession,- wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch,- getPendingCredentialSwitch: getPendingCredentialSwitchTarget,- // 解析隐式来源的凭证家族,精确判定是否跨远端压缩身份边界(见- // shouldCloseSessionForCredentialSwitch.codexAuthInjection)。- codexAuthInjection: getCodexProxyAuthInjectionState(),- logger: log,- }),- (id) => broadcastSessionPatched(id, {- agentSwitchIntent: null,- agentSwitchIntentCanceled: true,- }),+ throwIpcError(+ 'INVALID_PARAMS',+ 'expectedAgentSwitchRevision must be a non-negative integer',);- // deferred = 会话自己在跑,选择已登记、turn 结束自动生效。renderer 据此提示- // "任务结束后生效"而不是当成已即时切换。- const response = { deferred: result.status === 'deferred', superseded: false };- if (atomicSelection) {- // model/provider/effort/fast 是一次选择快照,必须在同一把 session 锁内收敛。- // applyRuntimeSetModelChange 可能 close + wake;若 effort/fast 留给 renderer- // 后续独立调用,queue drain 会用新 model + 旧偏好重建,跨控制端时还会发生- // 旧请求尾写覆盖新选择。- setSessionEffort(sessionId, atomicSelection.effort);- setSessionFastMode(sessionId, atomicSelection.fastMode);- const sess = maker.getSession(sessionId);- if (- sess &&- result.status !== 'deferred' &&- !pendingCredentialSwitchHolder?.has(sessionId)- ) {- await sess.setEffort(- atomicSelection.effort as- | 'minimal'- | 'low'- | 'medium'- | 'high'- | 'xhigh'- | 'max'- | 'ultra',- );- if (sess.agentKind === 'codex') {- await sess.setFastMode(atomicSelection.fastMode);- }- }+ }+ if (+ selection !== undefined &&+ (selection === null ||+ typeof selection !== 'object' ||+ Array.isArray(selection) ||+ typeof (selection as { effort?: unknown }).effort !== 'string' ||+ typeof (selection as { fastMode?: unknown }).fastMode !== 'boolean')+ ) {+ throwIpcError('INVALID_PARAMS', 'selection must contain effort + fastMode');+ }+ const atomicSelection = selection as { effort: string; fastMode: boolean } | undefined;+ // 与 send 事务共用 session 锁:发送时刻执行的跨引擎切换必须先落定,+ // 后到的 SET_MODEL 才能写 route。否则切换 DB await 恢复后会用旧 provider+ // 覆盖用户刚选的新 route,形成 DB 与进程内路由分叉。+ return withSendToSessionLock(sessionId, async () => {+ // 同引擎重选是 switch ack 后的第二段写入。另一控制端若在两段之间更新(含+ // set→clear ABA),修订号已变化:旧 SET_MODEL 必须在任何 route/DB 副作用前让位。+ if (+ typeof expectedAgentSwitchRevision === 'number' &&+ agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision+ ) {+ return { deferred: false, superseded: true };}- if (isDeviceLinkInvoke() || atomicSelection) {- // device-link 的通用持久化原本发生在 handler 返回、session 锁释放之后;- // 本地 renderer 的 sessionService.update 也有同一窗口。凡携带 selection 的- // 新调用都由 host 在解锁前一次落定全部字段。- const patch: Record<string, unknown> = { model };- if (effectiveProviderId !== undefined) {- patch.providerId = normalizeSessionProviderId(- typeof effectiveProviderId === 'string' ? effectiveProviderId : null,+ // 停用轴准入(PR #744 review;第十二轮移入锁内):切换模型是一次新的路由选择,+ // 不得切到用户停用的模型 / 来源(本机选择器已过滤,但本 channel 在 device-link+ // allowlist 内,老控制端可直接点名)。裁决必须在拿到会话锁**之后**执行 ——+ // 排队等待期间目标可能刚被停用,而同凭证族的变更即时生效、不经 deferred 收口+ // 的重裁决,锁前裁决结果可能已过期。会话当前正用着的停用模型不受影响,这里只+ // 拦「切过去」;隐式来源的原生默认落点被停用而有启用替代拷贝时,以显式来源+ // 落地(与 bootstrapSession 同语义)。agentKind 读不到(会话行缺失等)时不拦。+ // DB 存的是 'cc' | 'codex'(messages.agent_kind 口径),目录侧是 AgentKind。+ let effectiveProviderId = providerId;+ {+ const dbAgentKind = getSessionDbAgentKind(sessionId);+ if (dbAgentKind) {+ const reroute = await assertModelRouteUsable(+ dbToMakerAgentKind(dbAgentKind),+ model,+ typeof providerId === 'string' ? providerId : null,);+ if (reroute && typeof providerId !== 'string') effectiveProviderId = reroute;}+ }+ try {+ const result = await applySetModelThenCancelAgentSwitchIntent(+ agentSwitchPending,+ sessionId,+ () =>+ applyRuntimeSetModelChange({+ maker,+ sessionId,+ model,+ providerId: effectiveProviderId,+ ...(atomicSelection+ ? {+ effort: atomicSelection.effort as+ 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',+ }+ : {}),+ isSessionInTurn,+ registerPendingCredentialSwitch: registerPendingCredentialSwitchForSession,+ clearPendingCredentialSwitch: clearPendingCredentialSwitchForSession,+ wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch,+ getPendingCredentialSwitch: getPendingCredentialSwitchTarget,+ // 解析隐式来源的凭证家族,精确判定是否跨远端压缩身份边界(见+ // shouldCloseSessionForCredentialSwitch.codexAuthInjection)。+ codexAuthInjection: getCodexProxyAuthInjectionState(),+ logger: log,+ }),+ (id) =>+ broadcastSessionPatched(id, {+ agentSwitchIntent: null,+ agentSwitchIntentCanceled: true,+ }),+ );+ // deferred = 会话自己在跑,选择已登记、turn 结束自动生效。renderer 据此提示+ // "任务结束后生效"而不是当成已即时切换。+ const response = { deferred: result.status === 'deferred', superseded: false };if (atomicSelection) {- patch.effort = atomicSelection.effort;- patch.fastMode = atomicSelection.fastMode;+ // model/provider/effort/fast 是一次选择快照,必须在同一把 session 锁内收敛。+ // applyRuntimeSetModelChange 可能 close + wake;若 effort/fast 留给 renderer+ // 后续独立调用,queue drain 会用新 model + 旧偏好重建,跨控制端时还会发生+ // 旧请求尾写覆盖新选择。+ setSessionEffort(sessionId, atomicSelection.effort);+ setSessionFastMode(sessionId, atomicSelection.fastMode);+ const sess = maker.getSession(sessionId);+ if (+ sess &&+ result.status !== 'deferred' &&+ !pendingCredentialSwitchHolder?.has(sessionId)+ ) {+ await sess.setEffort(+ atomicSelection.effort as+ 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',+ );+ if (sess.agentKind === 'codex') {+ await sess.setFastMode(atomicSelection.fastMode);+ }+ }+ }+ if (isDeviceLinkInvoke() || atomicSelection) {+ // device-link 的通用持久化原本发生在 handler 返回、session 锁释放之后;+ // 本地 renderer 的 sessionService.update 也有同一窗口。凡携带 selection 的+ // 新调用都由 host 在解锁前一次落定全部字段。+ const patch: Record<string, unknown> = { model };+ if (effectiveProviderId !== undefined) {+ patch.providerId = normalizeSessionProviderId(+ typeof effectiveProviderId === 'string' ? effectiveProviderId : null,+ );+ }+ if (atomicSelection) {+ patch.effort = atomicSelection.effort;+ patch.fastMode = atomicSelection.fastMode;+ }+ await persistSessionFields(sessionId, patch);+ if (isDeviceLinkInvoke()) {+ // dispatch 继续兼容最小/旧 handler 的锁外回流;标记本结果避免重复写。+ markRemoteSettingPersistedInsideHandler(response);+ }}- await persistSessionFields(sessionId, patch);- if (isDeviceLinkInvoke()) {- // dispatch 继续兼容最小/旧 handler 的锁外回流;标记本结果避免重复写。- markRemoteSettingPersistedInsideHandler(response);+ return response;+ } catch (err) {+ if (err instanceof CredentialModeSwitchBusyError) {+ // 兜底(正常路径 busy 已转 deferred):切模型撞上凭证切换忙,独立 code,+ // renderer toast 走 ipcError.CREDENTIAL_SWITCH_BUSY 专属文案。+ throwIpcError('CREDENTIAL_SWITCH_BUSY', err.message);}+ throw err;}- return response;- } catch (err) {- if (err instanceof CredentialModeSwitchBusyError) {- // 兜底(正常路径 busy 已转 deferred):切模型撞上凭证切换忙,独立 code,- // renderer toast 走 ipcError.CREDENTIAL_SWITCH_BUSY 专属文案。- throwIpcError('CREDENTIAL_SWITCH_BUSY', err.message);- }- throw err;- }- });- });+ });+ },+ );ipcMain.handle(MAKER_INVOKE.SET_EFFORT, async (_e, sessionId: unknown, effort: unknown) => {if (typeof sessionId !== 'string' || typeof effort !== 'string') {@@ -9908,17 +11190,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}});- ipcMain.handle(MAKER_INVOKE.SET_PERMISSION_MODE, async (_e, sessionId: unknown, mode: unknown) => {- if (typeof sessionId !== 'string' || typeof mode !== 'string') {- throwIpcError('INVALID_PARAMS', 'sessionId + mode required');- }- const sess = maker.getSession(sessionId);- if (!sess) {- log.debug('set-permission-mode: session not found, no-op', { sessionId });- return;- }- await sess.setPermissionMode(mode as 'ask' | 'default' | 'acceptEdits' | 'plan' | 'auto' | 'bypassPermissions');- });+ ipcMain.handle(+ MAKER_INVOKE.SET_PERMISSION_MODE,+ async (_e, sessionId: unknown, mode: unknown) => {+ if (typeof sessionId !== 'string' || typeof mode !== 'string') {+ throwIpcError('INVALID_PARAMS', 'sessionId + mode required');+ }+ const sess = maker.getSession(sessionId);+ if (!sess) {+ log.debug('set-permission-mode: session not found, no-op', { sessionId });+ return;+ }+ await sess.setPermissionMode(+ mode as 'ask' | 'default' | 'acceptEdits' | 'plan' | 'auto' | 'bypassPermissions',+ );+ },+ );ipcMain.handle(MAKER_INVOKE.SET_PLAN_MODE, async (_e, sessionId: unknown, enabled: unknown) => {if (typeof sessionId !== 'string' || typeof enabled !== 'boolean') {@@ -9954,7 +11241,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return null;}// 主进程弹原生保存对话框选落盘位置(renderer 只发起,不碰文件系统)。- const parent = BrowserWindow.fromWebContents(e.sender) ?? BrowserWindow.getFocusedWindow() ?? undefined;+ const parent =+ BrowserWindow.fromWebContents(e.sender) ?? BrowserWindow.getFocusedWindow() ?? undefined;const defaultPath = path.join(app.getPath('documents'), 'cindy-session.html');const picked = await dialog.showSaveDialog(parent!, {title: 'Export session to HTML',@@ -9968,34 +11256,37 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return written;});- ipcMain.handle(MAKER_INVOKE.COMPACT_SESSION, async (event, sessionId: unknown, instructions: unknown) => {- // 会启动 Agent turn、产生模型费用:非 device-link 的本机调用必须来自受信顶层页面,- // 不能让辅助窗口 / WebView / 子 frame 经隐藏入口触发(codex review)。device-link- // 走独立鉴权通道,按既有 dual 模式放行。- if (!isDeviceLinkInvoke()) {- assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);- }- if (typeof sessionId !== 'string' || sessionId.length === 0) {- throwIpcError('INVALID_PARAMS', 'sessionId required');- }- if (instructions !== undefined && typeof instructions !== 'string') {- throwIpcError('INVALID_PARAMS', 'instructions must be a string when provided');- }- const sess = maker.getSession(sessionId);- if (!sess) {- log.debug('compact-session: session not found, no-op', { sessionId });- return null;- }- if (!sess.capabilities.manualCompact?.supported) {- // 调用方应先按 capabilities 隐藏入口,这里兜底 no-op。- log.debug('compact-session: agent does not support manual compact, no-op', {- sessionId,- agentKind: sess.agentKind,- });- return null;- }- return sess.compactSession(instructions);- });+ ipcMain.handle(+ MAKER_INVOKE.COMPACT_SESSION,+ async (event, sessionId: unknown, instructions: unknown) => {+ // 会启动 Agent turn、产生模型费用:非 device-link 的本机调用必须来自受信顶层页面,+ // 不能让辅助窗口 / WebView / 子 frame 经隐藏入口触发(codex review)。device-link+ // 走独立鉴权通道,按既有 dual 模式放行。+ if (!isDeviceLinkInvoke()) {+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]);+ }+ if (typeof sessionId !== 'string' || sessionId.length === 0) {+ throwIpcError('INVALID_PARAMS', 'sessionId required');+ }+ if (instructions !== undefined && typeof instructions !== 'string') {+ throwIpcError('INVALID_PARAMS', 'instructions must be a string when provided');+ }+ const sess = maker.getSession(sessionId);+ if (!sess) {+ log.debug('compact-session: session not found, no-op', { sessionId });+ return null;+ }+ if (!sess.capabilities.manualCompact?.supported) {+ // 调用方应先按 capabilities 隐藏入口,这里兜底 no-op。+ log.debug('compact-session: agent does not support manual compact, no-op', {+ sessionId,+ agentKind: sess.agentKind,+ });+ return null;+ }+ return sess.compactSession(instructions);+ },+ );/*** 会话树是历史浏览入口,不能要求用户先发一条消息把旧 Pi 会话唤醒。@@ -10089,7 +11380,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (parsed.summarize !== undefined && typeof parsed.summarize !== 'boolean') {throwIpcError('INVALID_PARAMS', 'summarize must be boolean');}- if (parsed.customInstructions !== undefined && typeof parsed.customInstructions !== 'string') {+ if (+ parsed.customInstructions !== undefined &&+ typeof parsed.customInstructions !== 'string'+ ) {throwIpcError('INVALID_PARAMS', 'customInstructions must be string');}const sess = await getOrResumeSessionTreeSession(sessionId);@@ -10138,8 +11432,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)clientIds: hiddenClientIds,});}- const visibleRows = await getDbClient().drizzle- .select()+ const visibleRows = await getDbClient()+ .drizzle.select().from(messages).where(and(eq(messages.sessionId, sessionId), isNull(messages.rewindAt))).orderBy(messages.createdAt);@@ -10243,14 +11537,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// "新会话生效"; reset 前必走 confirm dialog (UI 层负责)。ipcMain.handle(MAKER_INVOKE.MEMORY_GET, async (_e, agentKind: unknown) => {if (agentKind !== 'claude-code' && agentKind !== 'codex' && agentKind !== 'pi') {- throwIpcError('INVALID_PARAMS', `agentKind required (claude-code | codex | pi), got ${String(agentKind)}`);+ throwIpcError(+ 'INVALID_PARAMS',+ `agentKind required (claude-code | codex | pi), got ${String(agentKind)}`,+ );}return maker.getAgentMemoryStatus(agentKind);});ipcMain.handle(MAKER_INVOKE.MEMORY_SET, async (_e, agentKind: unknown, enabled: unknown) => {if (agentKind !== 'claude-code' && agentKind !== 'codex' && agentKind !== 'pi') {- throwIpcError('INVALID_PARAMS', `agentKind required (claude-code | codex | pi), got ${String(agentKind)}`);+ throwIpcError(+ 'INVALID_PARAMS',+ `agentKind required (claude-code | codex | pi), got ${String(agentKind)}`,+ );}if (typeof enabled !== 'boolean') {throwIpcError('INVALID_PARAMS', 'enabled required (boolean)');@@ -10280,7 +11580,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)ipcMain.handle(MAKER_INVOKE.MEMORY_RESET, async (_e, agentKind: unknown) => {if (agentKind !== 'claude-code' && agentKind !== 'codex' && agentKind !== 'pi') {- throwIpcError('INVALID_PARAMS', `agentKind required (claude-code | codex | pi), got ${String(agentKind)}`);+ throwIpcError(+ 'INVALID_PARAMS',+ `agentKind required (claude-code | codex | pi), got ${String(agentKind)}`,+ );}log.info('memory:reset', { agentKind });return maker.resetAgentMemory(agentKind);@@ -10408,40 +11711,38 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// Read one plugin's enable state by id. Unlike PLUGINS_LIST this does NOT skip// hidden (HOSTED_ELSEWHERE) plugins, so a dedicated Settings section (e.g.// 「电脑使用」for `browser`) can read its real project-override state.- ipcMain.handle(MAKER_INVOKE.PLUGINS_GET_STATE, async (- _e,- id: unknown,- workingDir: unknown,- workspaceKind: unknown,- ) => {- if (typeof id !== 'string') {- throwIpcError('INVALID_PARAMS', 'id (string) required');- }- const wd = typeof workingDir === 'string' ? workingDir : undefined;- // collab 的 app 托管 dialogue cwd 只读取用户/全局级;显式真实目录仍读取项目覆盖。- // 这里与 mutation 最终授权共用「dialogue kind + Main 可信路径」判据,device-link- // 隧道到被控端后也由被控端自己的 dialogue root 解析,Renderer 无需知道或猜 userData。- const policyWorkingDir =- id === 'collab' && wd !== undefined- ? resolveLocalCollabPolicyWorkingDir(- wd,- typeof workspaceKind === 'string' ? workspaceKind : null,- (candidate) =>- matchDialogueWorkspacePath(candidate, dialogueWorkspaceRootDir()) !== null,- )- : wd;- const state = await getPluginRegistry().getEnableState(id, policyWorkingDir);- const acceptedWorkspaceKind =- id === 'collab' && (workspaceKind === 'project' || workspaceKind === 'dialogue')- ? workspaceKind- : undefined;- // 远端控制端不能只靠 channel 存在判断 dialogue 协同:旧被控端也已有这个 channel,- // 但它会忽略第三个参数,且最终授权不接受 dialogue。回显被 Main 接受的 kind 作为- // 同一次只读查询的向后兼容握手;旧端缺字段,新端即可 fail-closed。- return acceptedWorkspaceKind- ? { ...state, collabWorkspaceKind: acceptedWorkspaceKind }- : state;- });+ ipcMain.handle(+ MAKER_INVOKE.PLUGINS_GET_STATE,+ async (_e, id: unknown, workingDir: unknown, workspaceKind: unknown) => {+ if (typeof id !== 'string') {+ throwIpcError('INVALID_PARAMS', 'id (string) required');+ }+ const wd = typeof workingDir === 'string' ? workingDir : undefined;+ // collab 的 app 托管 dialogue cwd 只读取用户/全局级;显式真实目录仍读取项目覆盖。+ // 这里与 mutation 最终授权共用「dialogue kind + Main 可信路径」判据,device-link+ // 隧道到被控端后也由被控端自己的 dialogue root 解析,Renderer 无需知道或猜 userData。+ const policyWorkingDir =+ id === 'collab' && wd !== undefined+ ? resolveLocalCollabPolicyWorkingDir(+ wd,+ typeof workspaceKind === 'string' ? workspaceKind : null,+ (candidate) =>+ matchDialogueWorkspacePath(candidate, dialogueWorkspaceRootDir()) !== null,+ )+ : wd;+ const state = await getPluginRegistry().getEnableState(id, policyWorkingDir);+ const acceptedWorkspaceKind =+ id === 'collab' && (workspaceKind === 'project' || workspaceKind === 'dialogue')+ ? workspaceKind+ : undefined;+ // 远端控制端不能只靠 channel 存在判断 dialogue 协同:旧被控端也已有这个 channel,+ // 但它会忽略第三个参数,且最终授权不接受 dialogue。回显被 Main 接受的 kind 作为+ // 同一次只读查询的向后兼容握手;旧端缺字段,新端即可 fail-closed。+ return acceptedWorkspaceKind+ ? { ...state, collabWorkspaceKind: acceptedWorkspaceKind }+ : state;+ },+ );ipcMain.handle(MAKER_INVOKE.PLUGINS_SET_ENABLED, async (_e, id: unknown, enabled: unknown) => {if (typeof id !== 'string' || typeof enabled !== 'boolean') {@@ -10516,27 +11817,30 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// ── Local desktop computer-use (Settings →「电脑使用」) ─────────────────// Probe the installed CuaDriver used by the phase-one Computer Use runtime.- ipcMain.handle(MAKER_INVOKE.COMPUTER_STATUS, async (_event, options?: {- includeDoctor?: boolean;- forcePermissionProbe?: boolean;- skipPermissionProbe?: boolean;- freshPermissionProbe?: boolean;- bypassPermissionProbeCache?: boolean;- passivePermissionProbeOnly?: boolean;- }) => {- try {- const status = await getComputerDriverStatus(options);- if (- options?.forcePermissionProbe === true- || options?.freshPermissionProbe === true- ) {- refreshComputerPermissionGuideWindow(status);+ ipcMain.handle(+ MAKER_INVOKE.COMPUTER_STATUS,+ async (+ _event,+ options?: {+ includeDoctor?: boolean;+ forcePermissionProbe?: boolean;+ skipPermissionProbe?: boolean;+ freshPermissionProbe?: boolean;+ bypassPermissionProbeCache?: boolean;+ passivePermissionProbeOnly?: boolean;+ },+ ) => {+ try {+ const status = await getComputerDriverStatus(options);+ if (options?.forcePermissionProbe === true || options?.freshPermissionProbe === true) {+ refreshComputerPermissionGuideWindow(status);+ }+ return status;+ } catch (err) {+ throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));}- return status;- } catch (err) {- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));- }- });+ },+ );ipcMain.handle(MAKER_INVOKE.COMPUTER_INSTALL_DRIVER, async () => {try {@@ -10583,9 +11887,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)initialStatus,);}- return await grantComputerDriverPermissions(- initialStatus,- );+ return await grantComputerDriverPermissions(initialStatus);} catch (err) {if (shouldShowGuide) closeComputerPermissionGuideWindow();throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));@@ -10605,17 +11907,29 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return status;});- ipcMain.on(MAKER_SEND.COMPUTER_PERMISSION_APP_DRAG_START, (_event, payload?: {- iconDataUrl?: unknown;- }) => {- startComputerPermissionAppDrag(_event.sender, payload?.iconDataUrl);- });+ ipcMain.on(+ MAKER_SEND.COMPUTER_PERMISSION_APP_DRAG_START,+ (+ _event,+ payload?: {+ iconDataUrl?: unknown;+ },+ ) => {+ startComputerPermissionAppDrag(_event.sender, payload?.iconDataUrl);+ },+ );- ipcMain.handle(MAKER_INVOKE.COMPUTER_PERMISSION_APP_DRAG_END, async (_event, payload?: {- didCopy?: unknown;- }) => {- return finishComputerPermissionAppDrag(_event.sender, payload?.didCopy);- });+ ipcMain.handle(+ MAKER_INVOKE.COMPUTER_PERMISSION_APP_DRAG_END,+ async (+ _event,+ payload?: {+ didCopy?: unknown;+ },+ ) => {+ return finishComputerPermissionAppDrag(_event.sender, payload?.didCopy);+ },+ );// 命令型:取消在途授权流程。幂等,无在途 grant 时 no-op。ipcMain.handle(MAKER_INVOKE.COMPUTER_CANCEL_PERMISSION_GRANT, async (_event) => {@@ -10648,19 +11962,25 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 更新执行:in-flight 托管在 main,设置窗口关闭安装照常跑完;重开面板// 再调用会 join 同一个安装 Promise,不会重复安装。下载进度经广播推给// 所有窗口(join 的调用方天然共享同一份进度流)。- ipcMain.handle(MAKER_INVOKE.COMPUTER_UPDATE_DRIVER, async (_event, opts?: { joinOnly?: boolean }) => {- try {- return await updateComputerDriver((progress) => {- for (const win of BrowserWindow.getAllWindows()) {- if (!win.isDestroyed()) {- win.webContents.send('computer-driver-update-progress', progress);- }- }- }, { joinOnly: opts?.joinOnly === true });- } catch (err) {- throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));- }- });+ ipcMain.handle(+ MAKER_INVOKE.COMPUTER_UPDATE_DRIVER,+ async (_event, opts?: { joinOnly?: boolean }) => {+ try {+ return await updateComputerDriver(+ (progress) => {+ for (const win of BrowserWindow.getAllWindows()) {+ if (!win.isDestroyed()) {+ win.webContents.send('computer-driver-update-progress', progress);+ }+ }+ },+ { joinOnly: opts?.joinOnly === true },+ );+ } catch (err) {+ throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));+ }+ },+ );// ── Plugin hub (Phase 2) ──────────────────────────────────────────────────@@ -10747,7 +12067,7 @@ function broadcastSyntheticToolEvent(const prepared = prepareSyntheticToolEventForBroadcast(sessionId,{ type: event.type, data: event.data },- event.agentMeta as AgentMeta | null | undefined ?? null,+ (event.agentMeta as AgentMeta | null | undefined) ?? null,);broadcastToAllWindows(MAKER_PUSH.EVENT, {sessionId,@@ -10809,7 +12129,10 @@ async function checkWorkDirExists(const stat = await fsp.stat(workingDir);if (!stat.isDirectory()) {if (suppress) {- log.warn('send: workdir not a directory (broadcast suppressed, caller has fallback)', { sessionId, workingDir });+ log.warn('send: workdir not a directory (broadcast suppressed, caller has fallback)', {+ sessionId,+ workingDir,+ });} else {emitWorkDirMissingError(sessionId, workingDir, source, 'not-dir');}@@ -10823,7 +12146,10 @@ async function checkWorkDirExists(const ready = await restoreMissingManagedWorktreeForSession(sessionId, workingDir);if (!ready) {if (suppress) {- log.warn('send: managed worktree not ready (broadcast suppressed, caller has fallback)', { sessionId, workingDir });+ log.warn('send: managed worktree not ready (broadcast suppressed, caller has fallback)', {+ sessionId,+ workingDir,+ });} else {emitWorkDirMissingError(sessionId, workingDir, source, 'not-exist');}@@ -10849,7 +12175,10 @@ async function checkWorkDirExists(return true;}if (suppress) {- log.warn('send: workdir missing (broadcast suppressed, caller has fallback)', { sessionId, workingDir });+ log.warn('send: workdir missing (broadcast suppressed, caller has fallback)', {+ sessionId,+ workingDir,+ });return false;}const similar = await findSimilarDirOnDisk(workingDir);@@ -10896,7 +12225,12 @@ function emitWorkDirMissingError(? ` — 注意: 磁盘上有同名但不完全一致的目录 ${JSON.stringify(similarPath)} (可能末尾带空格或大小写不同),建议在 Finder 重命名后重新选择目录。`: '';const message = base + hint;- log.warn('send aborted: workdir missing', { sessionId, workingDir, reason, similarPath: similarPath ?? undefined });+ log.warn('send aborted: workdir missing', {+ sessionId,+ workingDir,+ reason,+ similarPath: similarPath ?? undefined,+ });broadcastToAllWindows(MAKER_PUSH.EVENT, {sessionId,event: {@@ -10949,6 +12283,7 @@ function redactEventForRenderer(event: AgentEvent): AgentEvent {}function broadcastToAllWindows(channel: string, payload: unknown): void {+ const ownerStamp = getActiveDataOwnerPushStamp();if (channel === MAKER_PUSH.ORCA_WORKER_CHANGED &&payload &&@@ -10963,7 +12298,8 @@ function broadcastToAllWindows(channel: string, payload: unknown): void {// 可能暂不可用;如果异常冒泡,Session 的 status/terminal listener 会在// 清理前中止,最终留下 tracker busy + 死进程,所有后续消息永久排队。try {- tapWindowBroadcast(channel, payload);+ if (ownerStamp === undefined) tapWindowBroadcast(channel, payload);+ else tapWindowBroadcast(channel, payload, ownerStamp);} catch (err) {log.warn('device-link broadcast tap failed; keeping local broadcast alive', {channel,@@ -10973,7 +12309,8 @@ function broadcastToAllWindows(channel: string, payload: unknown): void {for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;try {- win.webContents.send(channel, payload);+ if (ownerStamp === undefined) win.webContents.send(channel, payload);+ else win.webContents.send(channel, payload, ownerStamp);} catch (e) {log.warn(`broadcast to window failed: ${String(e)}`);}diff --git a/apps/desktop/src/main/maker-ipc/sessionSendHandler.ts b/apps/desktop/src/main/maker-ipc/sessionSendHandler.tsindex a9f8081827..959a018037 100644--- a/apps/desktop/src/main/maker-ipc/sessionSendHandler.ts+++ b/apps/desktop/src/main/maker-ipc/sessionSendHandler.ts@@ -1,7 +1,10 @@import { throwIpcError } from '../utils/ipcValidate.js';import { MAKER_INVOKE } from './channels.js';import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';-import { stripMainOnlySendOpts } from './mobileClientPromptNote.js';+import {+ attachMainOwnedInputBoundary,+ type MainOwnedInputBoundaryStamp,+} from './mobileClientPromptNote.js';/*** SEND adapter 只校验 IPC 入口并委托事务;lazy-create / rehydrate / accepted@@ -14,6 +17,15 @@ export interface MakerSessionSendHandlerDeps<TResult = unknown> {createOpts?: unknown,sendOpts?: unknown,): TResult | Promise<TResult>;+ /**+ * Legacy direct maker:send callers still exist on older controllers. Give+ * them the same clear-generation fence as the modern input coordinator+ * before delegating to the send transaction.+ */+ assertRemoteInputControlBoundary?(+ sessionId: string,+ opts: unknown,+ ): MainOwnedInputBoundaryStamp | void | Promise<MainOwnedInputBoundaryStamp | void>;}export function registerMakerSessionSendHandler<TResult>(@@ -32,13 +44,18 @@ export function registerMakerSessionSendHandler<TResult>(if (typeof sessionId !== 'string') {throwIpcError('INVALID_PARAMS', 'sessionId required');}+ const boundaryStamp = await deps.assertRemoteInputControlBoundary?.(sessionId, sendOpts);+ const mainOwnedBoundaryStamp =+ boundaryStamp && typeof boundaryStamp === 'object' ? boundaryStamp : undefined;// sendOpts 来自 wire:剥掉只允许 main 写的字段(fromMobileClient 由 coordinator- // 从队列项透传,客户端不得自报 —— 直连路径的来源判据只能是 async context)。+ // 从队列项透传,客户端不得自报 —— 直连路径的来源判据只能是 async context),然后+ // 由 main 覆盖 clear token + generation。旧控制端不带 token 也因此获得同样的+ // clear 竞态保护,而不是在最终 fence 缺 precondition 时放行。return await deps.sendToAgentAccepted(sessionId,message,createOpts,- stripMainOnlySendOpts(sendOpts),+ attachMainOwnedInputBoundary(sendOpts, mainOwnedBoundaryStamp),);},);diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.tsindex a4b86f6357..7370c18baa 100644--- a/apps/desktop/src/main/messagePersistBroadcaster.ts+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts@@ -42,7 +42,7 @@ import { getDbClient } from './localDb/client/current.js';import { isTopLevelTitleAssistant } from './localDb/latestMessageText.logic.js';import { messages as messagesTable } from './localDb/schema.js';import { createLogger } from './logger.js';-import { tapWindowBroadcast } from './device-link/broadcast-tap.js';+import * as broadcastTap from './device-link/broadcast-tap.js';import { takeMediaToolResult } from './mcp-integrations/mediaToolResultFallback.js';import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';import { getSessionProvider } from './maker-host/session-provider-store.js';@@ -75,6 +75,7 @@ export function noteSessionClearBoundary(sessionId: string, clearedAt: string |}type CreateDbMessageBody = Parameters<typeof createDbMessage>[1];+type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;/*** session-agent-switch:每会话当前 agent 引擎('cc'/'codex'),由 register.ts@@ -99,18 +100,24 @@ function withAgentKindStamp(sessionId: string, body: CreateDbMessageBody): Creatreturn kind ? { ...body, agentKind: kind } : body;}-function createVisibleDbMessage(sessionId: string, body: CreateDbMessageBody): ReturnType<typeof createDbMessage> {+function createVisibleDbMessage(+ sessionId: string,+ body: CreateDbMessageBody,+ ownerScope: OwnerScope,+): ReturnType<typeof createDbMessage> {const createdAt = typeof body.createdAt === 'number' && Number.isFinite(body.createdAt)? body.createdAt: undefined;- if (createdAt === undefined) {- return createDbMessage(sessionId, body);- }return createDbMessage(sessionId, body, {- shouldBroadcast: () => {- const latestBoundary = clearBoundaryBySession.get(sessionId);- return latestBoundary === undefined || createdAt > latestBoundary;- },+ ...(createdAt === undefined+ ? {}+ : {+ shouldBroadcast: () => {+ const latestBoundary = clearBoundaryBySession.get(sessionId);+ return latestBoundary === undefined || createdAt > latestBoundary;+ },+ }),+ broadcastOwnerScope: ownerScope,});}@@ -243,12 +250,12 @@ function markAssistantTurnBoundary(completed: boolean,): Promise<boolean> {if (!sessionId || !clientId) return Promise.resolve(false);- return enqueueDurableWrite(`turn-boundary:${sessionId}:${clientId}:${completed}`, async () => {+ return enqueueDurableWrite(`turn-boundary:${sessionId}:${clientId}:${completed}`, async (ownerScope) => {const patched = await patchMessageAgentMetaWithResult(sessionId, clientId, {turnCompleted: completed,});if (!patched) return false;- return broadcastMessageAgentMetaUpdate(sessionId, clientId);+ return broadcastMessageAgentMetaUpdate(sessionId, clientId, ownerScope);});}@@ -291,12 +298,12 @@ export function markAutoResumeOutcome(outcome: 'succeeded' | 'failed',): Promise<boolean> {if (!sessionId || !clientId) return Promise.resolve(false);- return enqueueDurableWrite(`auto-resume-outcome:${sessionId}:${clientId}`, async () => {+ return enqueueDurableWrite(`auto-resume-outcome:${sessionId}:${clientId}`, async (ownerScope) => {const patched = await patchMessageAgentMetaWithResult(sessionId, clientId, {autoResumeOutcome: outcome,});if (!patched) return false;- return broadcastMessageAgentMetaUpdate(sessionId, clientId);+ return broadcastMessageAgentMetaUpdate(sessionId, clientId, ownerScope);});}@@ -305,9 +312,42 @@ export function markAutoResumeOutcome(* 序列化(sqlite 本就单写者)。每个 link 单独 catch,失败只 warn、不打断后续写。*/let writeChain: Promise<unknown> = Promise.resolve();-function enqueueWrite(label: string, fn: () => Promise<unknown>): void {+const OWNER_SCOPE_SUPERSEDED = 'OWNER_SCOPE_SUPERSEDED';++function captureOwnerScope(): ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null {+ return broadcastTap.captureDataOwnerBroadcastScope?.() ?? null;+}++function isOwnerScopeCurrent(+ scope: ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null,+): boolean {+ return scope === null || broadcastTap.isDataOwnerBroadcastScopeCurrent?.(scope) !== false;+}++function ownerScopeSupersededError(): Error & { code: string } {+ return Object.assign(new Error('durable write superseded by an app-session boundary'), {+ code: OWNER_SCOPE_SUPERSEDED,+ });+}++function isOwnerScopeSupersededError(error: unknown): boolean {+ return (+ error !== null &&+ typeof error === 'object' &&+ (error as { code?: unknown }).code === OWNER_SCOPE_SUPERSEDED+ );+}++function enqueueWrite(label: string, fn: (ownerScope: OwnerScope) => Promise<unknown>): void {+ const ownerScope = captureOwnerScope();writeChain = writeChain- .then(fn)+ .then(() => {+ if (!isOwnerScopeCurrent(ownerScope)) {+ log.debug('message persist skipped after app-session boundary', { label });+ return;+ }+ return fn(ownerScope);+ }).catch((err) => {log.warn('message persist failed', {label,@@ -323,7 +363,7 @@ function enqueueVisibleDbMessage(body: CreateDbMessageBody,): void {const stamped = withAgentKindStamp(sessionId, body);- enqueueWrite(label, () => createVisibleDbMessage(sessionId, stamped));+ enqueueWrite(label, (ownerScope) => createVisibleDbMessage(sessionId, stamped, ownerScope));}/**@@ -336,18 +376,33 @@ function enqueueVisibleDbMessage(* `fn` 在 microtask 里跑, 内部用 sync drizzle write OK; reject 透传给调用方, 单* 个 link reject 不打断后续 chain (跟 enqueueWrite 的吞错语义对齐, log.warn 即可)。*/-export function enqueueDurableWrite<T>(label: string, fn: () => Promise<T> | T): Promise<T> {+export function enqueueDurableWrite<T>(+ label: string,+ fn: (ownerScope: OwnerScope) => Promise<T> | T,+): Promise<T> {+ const ownerScope = captureOwnerScope();return new Promise<T>((resolve, reject) => {writeChain = writeChain.then(async () => {+ if (!isOwnerScopeCurrent(ownerScope)) {+ reject(ownerScopeSupersededError());+ return;+ }try {- const value = await fn();+ const value = await fn(ownerScope);+ // The durable side effect may have committed just before an app+ // session boundary becomes observable. Keep that commit's result:+ // callers must not retry or compensate a row/ledger write merely+ // because its owner-scoped broadcast is now stale. Each fn owns+ // suppressing its old-owner broadcast via ownerScope.resolve(value);} catch (err) {- log.warn('durable write failed', {- label,- error: err instanceof Error ? err.message : String(err),- });+ if (!isOwnerScopeSupersededError(err)) {+ log.warn('durable write failed', {+ label,+ error: err instanceof Error ? err.message : String(err),+ });+ }reject(err);}})@@ -1110,6 +1165,7 @@ export function onTurnErrorEvent(): string | undefined {const message = typeof data?.message === 'string' ? redactSensitiveText(data.message) : '';if (!message) return undefined;+ const ownerScope = captureOwnerScope();const capturedAt = Date.now();const recordedTurnStartedAt =_turnStartedAtBySession.get(sessionId) ??@@ -1206,16 +1262,26 @@ export function onTurnErrorEvent(},{ shouldBroadcast: () => false },);+ if (!isOwnerScopeCurrent(ownerScope)) return;+ const ownerStamp = ownerScope ? ownerScope.ownerStamp : broadcastTap.getSafeDataOwnerPushStamp?.();for (const win of BrowserWindow.getAllWindows()) {if (win.isDestroyed()) continue;try {- win.webContents.send('local-db:session:error-persisted', { sessionId });+ if (ownerScope === null) {+ win.webContents.send('local-db:session:error-persisted', { sessionId });+ } else {+ win.webContents.send('local-db:session:error-persisted', { sessionId }, ownerStamp);+ }} catch {/* swallow per-window broadcast failures */}}// device-link:把脏信号也转发给远控端,让已加载该会话历史的控制端窗口同样失效。- tapWindowBroadcast('local-db:session:error-persisted', { sessionId });+ if (ownerScope === null) {+ broadcastTap.tapWindowBroadcast('local-db:session:error-persisted', { sessionId });+ } else {+ broadcastTap.tapWindowBroadcast('local-db:session:error-persisted', { sessionId }, ownerStamp);+ }});notePersistedMessage(sessionId, 'error', persistId);return persistId;diff --git a/apps/desktop/src/main/modelMismatchBroadcaster.ts b/apps/desktop/src/main/modelMismatchBroadcaster.tsindex 5fba91a1c2..dff0ec8095 100644--- a/apps/desktop/src/main/modelMismatchBroadcaster.ts+++ b/apps/desktop/src/main/modelMismatchBroadcaster.ts@@ -19,9 +19,10 @@ import type { ModelMismatchInfo } from '../shared/modelMismatch.js';import { patchMessageAgentMeta } from './localDb/ipc/messages.js';import { enqueueDurableWrite } from './messagePersistBroadcaster.js';import { createLogger } from './logger.js';-import { tapWindowBroadcast } from './device-link/broadcast-tap.js';+import * as broadcastTap from './device-link/broadcast-tap.js';const log = createLogger('modelMismatchBroadcaster');+type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;/** IPC channel: main → renderer 推单条消息的模型降级标记。 */export const MESSAGE_MODEL_MISMATCH_CHANGED = 'usage:message-model-mismatch';@@ -42,18 +43,53 @@ export interface ModelMismatchDeps {): Promise<boolean>;enqueue<T>(label: string, fn: () => Promise<T> | T): Promise<T>;broadcast(payload: MessageModelMismatchPayload): void;+ /** Optional owner-aware broadcast used by production; test doubles may omit it. */+ broadcastWithOwnerScope?(+ payload: MessageModelMismatchPayload,+ ownerScope: OwnerScope,+ ): void;+}++function captureOwnerScope(): OwnerScope {+ return broadcastTap.captureDataOwnerBroadcastScope?.() ?? null;+}++function isOwnerScopeCurrent(scope: OwnerScope): boolean {+ return scope === null || broadcastTap.isDataOwnerBroadcastScopeCurrent?.(scope) !== false;+}++function broadcastModelMismatchPayload(+ payload: MessageModelMismatchPayload,+ ownerScope: OwnerScope,+): void {+ if (ownerScope === null) {+ broadcastTap.tapWindowBroadcast(MESSAGE_MODEL_MISMATCH_CHANGED, payload);+ } else {+ broadcastTap.tapWindowBroadcast(+ MESSAGE_MODEL_MISMATCH_CHANGED,+ payload,+ ownerScope.ownerStamp,+ );+ }+ for (const win of BrowserWindow.getAllWindows()) {+ if (!win.isDestroyed()) {+ if (ownerScope === null) {+ win.webContents.send(MESSAGE_MODEL_MISMATCH_CHANGED, payload);+ } else {+ win.webContents.send(MESSAGE_MODEL_MISMATCH_CHANGED, payload, ownerScope.ownerStamp);+ }+ }+ }}const defaultDeps: ModelMismatchDeps = {patchAgentMeta: patchMessageAgentMeta,enqueue: enqueueDurableWrite,broadcast(payload) {- tapWindowBroadcast(MESSAGE_MODEL_MISMATCH_CHANGED, payload);- for (const win of BrowserWindow.getAllWindows()) {- if (!win.isDestroyed()) {- win.webContents.send(MESSAGE_MODEL_MISMATCH_CHANGED, payload);- }- }+ broadcastModelMismatchPayload(payload, null);+ },+ broadcastWithOwnerScope(payload, ownerScope) {+ broadcastModelMismatchPayload(payload, ownerScope);},};@@ -75,12 +111,18 @@ export async function recordModelMismatchOnMessage(const { sessionId, clientId, mismatch } = args;if (!sessionId || !clientId) return;if (!mismatch?.selected || !mismatch.actual) return;+ const ownerScope = captureOwnerScope();try {const patched = await deps.enqueue(`model-mismatch:${sessionId}:${clientId}`, () =>deps.patchAgentMeta(sessionId, clientId, { modelMismatch: mismatch }),);- if (!patched) return;- deps.broadcast({ sessionId, clientId, modelMismatch: mismatch });+ if (!patched || !isOwnerScopeCurrent(ownerScope)) return;+ const payload = { sessionId, clientId, modelMismatch: mismatch };+ if (deps.broadcastWithOwnerScope) {+ deps.broadcastWithOwnerScope(payload, ownerScope);+ } else {+ deps.broadcast(payload);+ }} catch (err) {log.warn('recordModelMismatchOnMessage failed:', err instanceof Error ? err.message : String(err));}diff --git a/apps/desktop/src/main/sessionSpendBroadcaster.ts b/apps/desktop/src/main/sessionSpendBroadcaster.tsindex 7cf80a95ed..6d7fc3efaa 100644--- a/apps/desktop/src/main/sessionSpendBroadcaster.ts+++ b/apps/desktop/src/main/sessionSpendBroadcaster.ts@@ -24,7 +24,7 @@ import { sql } from 'drizzle-orm';import { sessions } from './localDb/schema';import { getDbClient } from './localDb/client/current';import { createLogger } from './logger';-import { tapWindowBroadcast } from './device-link/broadcast-tap.js';+import * as broadcastTap from './device-link/broadcast-tap.js';import {addRegionalMoney,legacyUsdMoney,@@ -68,6 +68,16 @@ export interface SessionContextPayload {contextWindow: number;}+type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope>;++function captureOwnerScope(): OwnerScope | null {+ return broadcastTap.captureDataOwnerBroadcastScope?.() ?? null;+}++function isOwnerScopeCurrent(scope: OwnerScope | null): boolean {+ return scope === null || broadcastTap.isDataOwnerBroadcastScopeCurrent?.(scope) !== false;+}+/*** 给 session 累加一笔 turn delta:UPDATE sessions SET total_cost_usd += delta,* 然后回读最新值并广播。@@ -79,6 +89,7 @@ export async function recordSessionTurnSpend(money: RegionalMoney,): Promise<void> {if (!sessionId) return;+ const ownerScope = captureOwnerScope();const normalized = normalizeRegionalMoney(money);if (!normalized || normalized.amount < 1e-10) return;// 只接受本账号的结算币种。基准取 currentLedgerCurrency() 而不是构建区域 —— 结算币种@@ -129,24 +140,37 @@ export async function recordSessionTurnSpend(? addRegionalMoney([legacy, current]): current: (current ?? legacy);- broadcast({+ if (!isOwnerScopeCurrent(ownerScope)) return;+ broadcast(+ {sessionId,totalMoney,...(totalMoney.currency === 'USD' ? { totalCostUsd: totalMoney.amount } : {}),- });+ },+ ownerScope,+ );} catch (err) {log.warn('recordSessionTurnSpend failed:', err instanceof Error ? err.message : String(err));}}-function broadcast(payload: SessionSpendPayload): void {+function broadcast(payload: SessionSpendPayload, ownerScope: OwnerScope | null = null): void {+ const ownerStamp = ownerScope ? ownerScope.ownerStamp : broadcastTap.getSafeDataOwnerPushStamp?.();// device-link 旁路:控制端经 sessions topic(列表订阅常开,会话未打开也不丢)收到// 累计 cost 镜像(本模块走裸 UPDATE、不发 sessions:patched,没有这条 tap 控制端的// $ 永远不更新)。- tapWindowBroadcast(USAGE_SESSION_SPEND_CHANGED, payload);+ if (ownerScope === null) {+ broadcastTap.tapWindowBroadcast(USAGE_SESSION_SPEND_CHANGED, payload);+ } else {+ broadcastTap.tapWindowBroadcast(USAGE_SESSION_SPEND_CHANGED, payload, ownerStamp);+ }for (const win of BrowserWindow.getAllWindows()) {if (!win.isDestroyed()) {- win.webContents.send(USAGE_SESSION_SPEND_CHANGED, payload);+ if (ownerScope === null) {+ win.webContents.send(USAGE_SESSION_SPEND_CHANGED, payload);+ } else {+ win.webContents.send(USAGE_SESSION_SPEND_CHANGED, payload, ownerStamp);+ }}}}@@ -158,6 +182,7 @@ export async function recordSessionTurnTokens(): Promise<void> {if (!sessionId) return;if (!Number.isFinite(tokenDelta) || tokenDelta <= 0) return;+ const ownerScope = captureOwnerScope();try {const db = getDbClient().drizzle;await db@@ -170,17 +195,27 @@ export async function recordSessionTurnTokens(.from(sessions).where(sql`${sessions.id} = ${sessionId}`).get();- broadcastTokens({ sessionId, totalTokens: row?.totalTokenUsage ?? 0 });+ if (!isOwnerScopeCurrent(ownerScope)) return;+ broadcastTokens({ sessionId, totalTokens: row?.totalTokenUsage ?? 0 }, ownerScope);} catch (err) {log.warn('recordSessionTurnTokens failed:', err instanceof Error ? err.message : String(err));}}-function broadcastTokens(payload: SessionTokensPayload): void {- tapWindowBroadcast(USAGE_SESSION_TOKENS_CHANGED, payload);+function broadcastTokens(payload: SessionTokensPayload, ownerScope: OwnerScope | null = null): void {+ const ownerStamp = ownerScope ? ownerScope.ownerStamp : broadcastTap.getSafeDataOwnerPushStamp?.();+ if (ownerScope === null) {+ broadcastTap.tapWindowBroadcast(USAGE_SESSION_TOKENS_CHANGED, payload);+ } else {+ broadcastTap.tapWindowBroadcast(USAGE_SESSION_TOKENS_CHANGED, payload, ownerStamp);+ }for (const win of BrowserWindow.getAllWindows()) {if (!win.isDestroyed()) {- win.webContents.send(USAGE_SESSION_TOKENS_CHANGED, payload);+ if (ownerScope === null) {+ win.webContents.send(USAGE_SESSION_TOKENS_CHANGED, payload);+ } else {+ win.webContents.send(USAGE_SESSION_TOKENS_CHANGED, payload, ownerStamp);+ }}}}@@ -205,6 +240,7 @@ export async function recordSessionContextSnapshot(if (!sessionId) return;if (!Number.isFinite(contextTokens) || contextTokens < 0) return;if (contextTokens === 0 && (!Number.isFinite(contextWindow) || contextWindow <= 0)) return;+ const ownerScope = captureOwnerScope();try {const db = getDbClient().drizzle;const updates: { contextTokens: number; contextWindow?: number } = {@@ -227,11 +263,15 @@ export async function recordSessionContextSnapshot(.from(sessions).where(sql`${sessions.id} = ${sessionId}`).get();- broadcastContext({- sessionId,- contextTokens: row?.contextTokens ?? 0,- contextWindow: row?.contextWindow ?? 0,- });+ if (!isOwnerScopeCurrent(ownerScope)) return;+ broadcastContext(+ {+ sessionId,+ contextTokens: row?.contextTokens ?? 0,+ contextWindow: row?.contextWindow ?? 0,+ },+ ownerScope,+ );} catch (err) {log.warn('recordSessionContextSnapshot failed:',@@ -240,10 +280,15 @@ export async function recordSessionContextSnapshot(}}-function broadcastContext(payload: SessionContextPayload): void {+function broadcastContext(payload: SessionContextPayload, ownerScope: OwnerScope | null = null): void {+ const ownerStamp = ownerScope ? ownerScope.ownerStamp : broadcastTap.getSafeDataOwnerPushStamp?.();for (const win of BrowserWindow.getAllWindows()) {if (!win.isDestroyed()) {- win.webContents.send(USAGE_SESSION_CONTEXT_CHANGED, payload);+ if (ownerScope === null) {+ win.webContents.send(USAGE_SESSION_CONTEXT_CHANGED, payload);+ } else {+ win.webContents.send(USAGE_SESSION_CONTEXT_CHANGED, payload, ownerStamp);+ }}}}diff --git a/apps/desktop/src/main/turnCostBroadcaster.ts b/apps/desktop/src/main/turnCostBroadcaster.tsindex e43972ddfa..dc8ff10fed 100644--- a/apps/desktop/src/main/turnCostBroadcaster.ts+++ b/apps/desktop/src/main/turnCostBroadcaster.ts@@ -32,7 +32,7 @@ import {} from './localDb/ipc/messages.js';import { enqueueDurableWrite } from './messagePersistBroadcaster.js';import { createLogger } from './logger.js';-import { tapWindowBroadcast } from './device-link/broadcast-tap.js';+import * as broadcastTap from './device-link/broadcast-tap.js';import {applyScheduleRunCostMetaChange,recordScheduleRunCostDirect,@@ -44,6 +44,7 @@ import {} from '../shared/regionalMoney.js';const log = createLogger('turnCostBroadcaster');+type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;/** IPC channel: main → renderer 推单条消息的 per-turn 费用。 */export const MESSAGE_TURN_COST_CHANGED = 'usage:message-turn-cost';@@ -71,6 +72,40 @@ export interface TurnCostDeps {}>;enqueue<T>(label: string, fn: () => Promise<T> | T): Promise<T>;broadcast(payload: MessageTurnCostPayload): void;+ /** Optional owner-aware broadcast used by production; test doubles may omit it. */+ broadcastWithOwnerScope?(+ payload: MessageTurnCostPayload,+ ownerScope: OwnerScope,+ ): void;+}++function captureOwnerScope(): OwnerScope {+ return broadcastTap.captureDataOwnerBroadcastScope?.() ?? null;+}++function isOwnerScopeCurrent(scope: OwnerScope): boolean {+ return scope === null || broadcastTap.isDataOwnerBroadcastScopeCurrent?.(scope) !== false;+}++function broadcastTurnCostPayload(payload: MessageTurnCostPayload, ownerScope: OwnerScope): void {+ if (ownerScope === null) {+ broadcastTap.tapWindowBroadcast(MESSAGE_TURN_COST_CHANGED, payload);+ } else {+ broadcastTap.tapWindowBroadcast(+ MESSAGE_TURN_COST_CHANGED,+ payload,+ ownerScope.ownerStamp,+ );+ }+ for (const win of BrowserWindow.getAllWindows()) {+ if (!win.isDestroyed()) {+ if (ownerScope === null) {+ win.webContents.send(MESSAGE_TURN_COST_CHANGED, payload);+ } else {+ win.webContents.send(MESSAGE_TURN_COST_CHANGED, payload, ownerScope.ownerStamp);+ }+ }+ }}const defaultDeps: TurnCostDeps = {@@ -79,12 +114,10 @@ const defaultDeps: TurnCostDeps = {readPriorUserRoundCost,enqueue: enqueueDurableWrite,broadcast(payload) {- tapWindowBroadcast(MESSAGE_TURN_COST_CHANGED, payload);- for (const win of BrowserWindow.getAllWindows()) {- if (!win.isDestroyed()) {- win.webContents.send(MESSAGE_TURN_COST_CHANGED, payload);- }- }+ broadcastTurnCostPayload(payload, null);+ },+ broadcastWithOwnerScope(payload, ownerScope) {+ broadcastTurnCostPayload(payload, ownerScope);},};@@ -109,6 +142,7 @@ export async function recordTurnCostOnMessage(if (!sessionId || !clientId) return false;const normalized = normalizeRegionalMoney(money);if (!normalized || normalized.amount < 1e-10) return false;+ const ownerScope = captureOwnerScope();try {let userTurnMoney = normalized;let userTurnCostIsEstimate = normalized.kind === 'value-estimate';@@ -155,22 +189,28 @@ export async function recordTurnCostOnMessage(return result;});if (!patched) return false;+ // The patch and scheduler ledger side effect are already durable. An+ // owner switch only suppresses the stale renderer/device-link broadcast;+ // report success so scheduler fallback cannot charge the same segment+ // again.+ if (!isOwnerScopeCurrent(ownerScope)) return true;+ const payload: MessageTurnCostPayload = {+ sessionId,+ clientId,+ turnMoney: normalized,+ ...(normalized.currency === 'USD' ? { turnCostUsd: normalized.amount } : {}),+ turnCostIsEstimate: normalized.kind === 'value-estimate',+ userTurnMoney,+ ...(userTurnMoney.currency === 'USD' ? { userTurnCostUsd: userTurnMoney.amount } : {}),+ userTurnCostIsEstimate,+ ...(turnUsageDetails ? { turnUsageDetails } : {}),+ };try {- deps.broadcast({- sessionId,- clientId,- turnMoney: normalized,- ...(normalized.currency === 'USD'- ? { turnCostUsd: normalized.amount }- : {}),- turnCostIsEstimate: normalized.kind === 'value-estimate',- userTurnMoney,- ...(userTurnMoney.currency === 'USD'- ? { userTurnCostUsd: userTurnMoney.amount }- : {}),- userTurnCostIsEstimate,- ...(turnUsageDetails ? { turnUsageDetails } : {}),- });+ if (deps.broadcastWithOwnerScope) {+ deps.broadcastWithOwnerScope(payload, ownerScope);+ } else {+ deps.broadcast(payload);+ }} catch (err) {// The message cost is already durable; a broadcast failure must not// make scheduler fallback record the same segment a second time.@@ -189,7 +229,11 @@ export async function recordTurnCostOnMessage(*/export type TurnUsageDeps = Pick<TurnCostDeps,- 'patchAgentMeta' | 'enqueue' | 'broadcast' | 'readPriorUserRoundCost'+ | 'patchAgentMeta'+ | 'enqueue'+ | 'broadcast'+ | 'broadcastWithOwnerScope'+ | 'readPriorUserRoundCost'>;/**@@ -217,6 +261,7 @@ export async function recordTurnUsageOnMessage(): Promise<boolean> {const { sessionId, clientId, turnUsageDetails } = args;if (!sessionId || !clientId || !turnUsageDetails) return false;+ const ownerScope = captureOwnerScope();try {const outcome = await deps.enqueue(`turn-usage:${sessionId}:${clientId}`, async () => {// 与 recordTurnCostOnMessage 同一条 durable FIFO,所以这里看得到本用户轮此前@@ -237,9 +282,12 @@ export async function recordTurnUsageOnMessage(return { userTurnMoney, userTurnCostIsEstimate: prior.hasEstimatedValue };});if (!outcome) return false;+ // Usage metadata is durable even when the captured owner became stale;+ // skip only the old-owner broadcast and keep the successful result.+ if (!isOwnerScopeCurrent(ownerScope)) return true;try {const { userTurnMoney, userTurnCostIsEstimate } = outcome;- deps.broadcast({+ const payload: MessageTurnCostPayload = {sessionId,clientId,turnUsageDetails,@@ -252,7 +300,12 @@ export async function recordTurnUsageOnMessage(userTurnCostIsEstimate,}: {}),- });+ };+ if (deps.broadcastWithOwnerScope) {+ deps.broadcastWithOwnerScope(payload, ownerScope);+ } else {+ deps.broadcast(payload);+ }} catch (err) {// 明细已落库,后开窗口走历史加载仍能读到;广播失败不影响持久事实。log.warn(diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex f1293cdf60..f14ef8d9fb 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -64,14 +64,14 @@ import type {SubagentModelSettingsWriteResult,} from '../shared/subagentModelSettings';import type { VoiceInputAsrMode, VoiceInputProviderKind } from '../shared/voiceInputAsrProfiles';-import type { VoiceInputRefinerProviderKind, VoiceInputRefinerTransport } from '../shared/voiceInputRefinerProfiles';+import type {+ VoiceInputRefinerProviderKind,+ VoiceInputRefinerTransport,+} from '../shared/voiceInputRefinerProfiles';import { isIpcErrorCode, type IpcErrorCode } from '../shared/ipc-errors';import type { VoiceInputSyncErrorResult } from '../shared/voiceInputData';import type { UtilityTextFailure } from '../shared/utilityTextResult';-import type {- BrowserBackendHealth,- BrowserBackendRecoveryResult,-} from '../shared/browserBackend';+import type { BrowserBackendHealth, BrowserBackendRecoveryResult } from '../shared/browserBackend';import type {ReviewBranchDiffData,ReviewCommitDiffData,@@ -138,13 +138,15 @@ import {// fans out to a Set of subscriber callbacks. Subscribers receive an unsubscribe// function; when the last subscriber leaves, the underlying binding is removed.-type IpcCallback = (data: unknown) => void;+type IpcCallback = (data: unknown, ownerStamp?: unknown) => void;function throwVoiceInputSyncError(result: unknown): void {if (!result || typeof result !== 'object' || (result as { ok?: unknown }).ok !== false) return;const candidate = result as Partial<VoiceInputSyncErrorResult>;if (!isIpcErrorCode(candidate.code)) return;- const error = new Error(`[${candidate.code}] ${candidate.message ?? 'voice input data operation failed'}`);+ const error = new Error(+ `[${candidate.code}] ${candidate.message ?? 'voice input data operation failed'}`,+ );(error as { code?: IpcErrorCode }).code = candidate.code;throw error;}@@ -179,15 +181,23 @@ type VoiceInputShortcutWire = {};type VoiceInputGlobalResult =| { ok: true }- | { ok: false; error: string; errorCode?: 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' | 'superseded' };+ | {+ ok: false;+ error: string;+ errorCode?: 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' | 'superseded';+ };type VoiceInputSettingsUpdateResult =| {- ok: true;- settings: import('../shared/voiceInputData').VoiceInputSettings;- /** 已存盘但 macOS 监听权限未授权,快捷键要等授权后才生效。 */- pendingInputMonitoring?: boolean;- }- | { ok: false; error: string; errorCode?: 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' | 'superseded' };+ ok: true;+ settings: import('../shared/voiceInputData').VoiceInputSettings;+ /** 已存盘但 macOS 监听权限未授权,快捷键要等授权后才生效。 */+ pendingInputMonitoring?: boolean;+ }+ | {+ ok: false;+ error: string;+ errorCode?: 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' | 'superseded';+ };type VoiceInputReadinessWire = {ok: boolean;serviceMode: 'cindy' | 'byok';@@ -197,7 +207,8 @@ type VoiceInputReadinessWire = {settingsTab: 'api-keys' | 'connections' | 'providers';error?: string;authErrorReason?: string;- failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';+ failureReason?:+ 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';};type VoiceInputModelSelectionWire = {serviceMode: 'cindy' | 'byok';@@ -264,7 +275,11 @@ type TelegramBotStatusWire =| { kind: 'connected'; appId: string }| { kind: 'conflict'; appId: string }| { kind: 'offline'; appId: string }- | { kind: 'error'; reason: string; code?: 'invalid-token' | 'provider-api' | 'network' | 'secret-unavailable' };+ | {+ kind: 'error';+ reason: string;+ code?: 'invalid-token' | 'provider-api' | 'network' | 'secret-unavailable';+ };/*** Factory for lazy, ref-counted IPC fan-out subscriptions.@@ -286,9 +301,9 @@ type FanOut = ((callback: IpcCallback) => () => void) & { __reset: () => void };function createIpcFanOut(channel: string): FanOut {const listeners = new Set<IpcCallback>();let bound = false;- const bridge = (_event: Electron.IpcRendererEvent, data: unknown) => {+ const bridge = (_event: Electron.IpcRendererEvent, data: unknown, ownerStamp?: unknown) => {listeners.forEach((cb) => {- cb(data);+ cb(data, ownerStamp);});};const subscribe = ((callback: IpcCallback): (() => void) => {@@ -324,7 +339,9 @@ const fanOutRsbWindowStateChanged = createIpcFanOut('maker:rsb-window:state-chanconst fanOutRsbWindowContextChanged = createIpcFanOut('maker:rsb-window:context-changed');const fanOutRsbWindowCommand = createIpcFanOut('maker:rsb-window:command');// 插件停靠面板独立窗口(ghost panel window)状态推送-const fanOutGhostPanelWindowStateChanged = createIpcFanOut('maker:ghost-panel-window:state-changed');+const fanOutGhostPanelWindowStateChanged = createIpcFanOut(+ 'maker:ghost-panel-window:state-changed',+);const fanOutBinaryDownloadProgress = createIpcFanOut('binary-download-progress');// Settings →「电脑使用」cua-driver 更新的下载进度(main 侧采样后广播)const fanOutComputerDriverUpdateProgress = createIpcFanOut('computer-driver-update-progress');@@ -401,7 +418,9 @@ const fanOutGitContextPrRefsChanged = createIpcFanOut('git-context:pr-refs-changconst fanOutSystemTransientNetworkError = createIpcFanOut('system:transient-network-error');// Find in Page (F-FIP-1): Chromium 异步回推匹配数 / 当前 ordinal。const fanOutFindInPageResult = createIpcFanOut('find-in-page:result');-const fanOutSelectionContextMenuAddToChat = createIpcFanOut(SELECTION_CONTEXT_MENU_ADD_TO_CHAT_CHANNEL);+const fanOutSelectionContextMenuAddToChat = createIpcFanOut(+ SELECTION_CONTEXT_MENU_ADD_TO_CHAT_CHANNEL,+);// session 级别"终身累计 cost"实时变化(每个 cc done 事件后 main 推)。chip 用它显示"$X.XX session"。// today aggregate 已搬到 maker.usage.* 下面 (取代老 fanOutUsageTodaySpendChanged + codex.usage.onChanged)。const fanOutUsageSessionSpendChanged = createIpcFanOut('usage:session-spend-changed');@@ -427,9 +446,13 @@ const fanOutWecomBotStatusChange = createIpcFanOut('wecomBot:status-changed');// Personal WeChat: main owns auth/polling and broadcasts a credential-free state snapshot.const fanOutWechatBotStateChange = createIpcFanOut('wechatBot:state-changed');const fanOutVoiceInputEvent = createIpcFanOut('voice-input:event');-const fanOutVoiceInputGlobalShortcutTrigger = createIpcFanOut('voice-input:global-shortcut-trigger');+const fanOutVoiceInputGlobalShortcutTrigger = createIpcFanOut(+ 'voice-input:global-shortcut-trigger',+);const fanOutVoiceInputGlobalOverlayCommand = createIpcFanOut('voice-input:global-overlay-command');-const fanOutVoiceInputDictionaryLearningEvidence = createIpcFanOut('voice-input:dictionary-learning-evidence');+const fanOutVoiceInputDictionaryLearningEvidence = createIpcFanOut(+ 'voice-input:dictionary-learning-evidence',+);const fanOutVoiceInputDataChanged = createIpcFanOut('voice-input:data-changed');// 挂起/锁屏 → renderer 释放 fast activation 的保活麦克风(见 shared/voiceInputPowerIpc)。const fanOutVoiceInputPowerStateChange = createIpcFanOut(VOICE_INPUT_POWER_STATE_CHANNEL);@@ -479,7 +502,9 @@ const fanOutGhostPreviewOpen = createIpcFanOut('ghosts:preview-open');const fanOutVoiceInputModifierShortcutKeys = createIpcFanOut('voice-input:modifier-shortcut-keys');// 「待授权」快捷键在设置页之外自动恢复失败(helper 起不来)。设置页不在,它的 toast 也就// 不在,所以由常挂载的 MainLayout 接这条并提示。main 侧一次 App 运行只推一次。-const fanOutVoiceInputShortcutRecoveryFailed = createIpcFanOut('voice-input:shortcut-recovery-failed');+const fanOutVoiceInputShortcutRecoveryFailed = createIpcFanOut(+ 'voice-input:shortcut-recovery-failed',+);// Remote SSH (Phase A) — host status fan-out. Channel literal kept in// sync with REMOTE_SSH_PUSH.STATUS_CHANGED in main/remote-ssh/index.ts;// preload can't import from main due to vite chunking.@@ -487,16 +512,18 @@ const fanOutRemoteSshStatus = createIpcFanOut('maker:remote-ssh:status-changed')// Phase B — install progress events (per hostId + agentKind).const fanOutRemoteSshInstallProgress = createIpcFanOut('maker:remote-ssh:install-progress');// Phase D — silent install status (maker:send 触发的自动 install 给 toast 用)。-const fanOutRemoteSshSilentInstallStatus = createIpcFanOut('maker:remote-ssh:silent-install-status');+const fanOutRemoteSshSilentInstallStatus = createIpcFanOut(+ 'maker:remote-ssh:silent-install-status',+);// cc-mgr 版本不匹配的 banner push (per hostId set / clear)。-const fanOutRemoteSshCcMgrUpgradeAvailable = createIpcFanOut('maker:remote-ssh:cc-mgr-upgrade-available');+const fanOutRemoteSshCcMgrUpgradeAvailable = createIpcFanOut(+ 'maker:remote-ssh:cc-mgr-upgrade-available',+);// Hook 连接(hook-control)状态推送(单条连接快照)。const fanOutHookControlStatus = createIpcFanOut('maker:hook-control:status-changed');// Hook 目录偏好快照推送(prefs.state; 含 Slack /model 卡改动的实时同步)。const fanOutHookControlPrefs = createIpcFanOut('maker:hook-control:prefs-changed');-const fanOutHookControlProviderPrefs = createIpcFanOut(- 'maker:hook-control:provider-prefs-changed',-);+const fanOutHookControlProviderPrefs = createIpcFanOut('maker:hook-control:provider-prefs-changed');const fanOutHookControlTelegramBehavior = createIpcFanOut('maker:hook-control:telegram-behavior-changed',);@@ -525,14 +552,20 @@ const fanOutMakerProviderUpstreamError = createIpcFanOut('maker:provider:upstreaconst fanOutMakerAutoPermissionFallback = createIpcFanOut('maker:auto-permission:fallback');const fanOutMakerCodexRuntimeRouteChanged = createIpcFanOut('maker:codex-runtime-route-changed');// 延迟凭证切换在 turn 结束兑现的广播(payload = { sessionId, model, providerId })。-const fanOutMakerSessionCredentialSwitchApplied = createIpcFanOut('maker:session-credential-switch-applied');+const fanOutMakerSessionCredentialSwitchApplied = createIpcFanOut(+ 'maker:session-credential-switch-applied',+);const fanOutMakerClaudeSessionRouteChanged = createIpcFanOut('maker:claude-session-route-changed');// 会话后台活动翻转广播(payload = { sessionId, active }):turn 已结束但 CC 子进程仍在调模型。-const fanOutMakerSessionBackgroundActivityChanged = createIpcFanOut('maker:session-background-activity-changed');-const fanOutMakerUsageTodaySpend = createIpcFanOut('usage:today-spend-changed'); // Claude USD-const fanOutMakerUsageTodayTokens = createIpcFanOut('usage:today-tokens-changed'); // Codex token+const fanOutMakerSessionBackgroundActivityChanged = createIpcFanOut(+ 'maker:session-background-activity-changed',+);+const fanOutMakerUsageTodaySpend = createIpcFanOut('usage:today-spend-changed'); // Claude USD+const fanOutMakerUsageTodayTokens = createIpcFanOut('usage:today-tokens-changed'); // Codex tokenconst fanOutMakerUsageModelPricing = createIpcFanOut('usage:model-pricing-changed');-const fanOutMakerUsageReferenceModelPricing = createIpcFanOut('usage:reference-model-pricing-changed');+const fanOutMakerUsageReferenceModelPricing = createIpcFanOut(+ 'usage:reference-model-pricing-changed',+);const fanOutMakerUsageClaudeAccount = createIpcFanOut('usage:claude-account-changed'); // Claude 月度配额const fanOutMakerUsageCodexAccount = createIpcFanOut('usage:codex-account-changed'); // Codex 订阅用量const fanOutMakerUsageXaiRateLimit = createIpcFanOut('usage:xai-rate-limit-changed'); // xAI bridge 限流快照@@ -619,14 +652,7 @@ type AndroidMcpErrorCode =| 'INVALID_NODE'| 'ANDROID_DRIVER_ERROR';-type AndroidAdbPathSource =- | 'custom'- | 'env'- | 'prepared'- | 'bundled'- | 'sdk'- | 'path'- | 'fallback';+type AndroidAdbPathSource = 'custom' | 'env' | 'prepared' | 'bundled' | 'sdk' | 'path' | 'fallback';interface AndroidConnectedDevice {device_serial: string;@@ -766,15 +792,12 @@ contextBridge.exposeInMainWorld('electronAPI', {* splash / login 阶段 maker-ipc handler 还没注册时,invoke 会 reject — 由调用方* catch 后兜底当作 false (那个阶段本来就不可能有 in-flight)。*/- anySessionInTurn: (): Promise<boolean> =>- ipcRenderer.invoke('maker:any-session-in-turn'),+ anySessionInTurn: (): Promise<boolean> => ipcRenderer.invoke('maker:any-session-in-turn'),pageZoomIn: (): Promise<{ ok: true; zoomLevel: number }> => ipcRenderer.invoke('page-zoom:in'),pageZoomOut: (): Promise<{ ok: true; zoomLevel: number }> => ipcRenderer.invoke('page-zoom:out'),pageZoomReset: (): Promise<{ ok: true; zoomLevel: number }> =>ipcRenderer.invoke('page-zoom:reset'),- onApplicationMenuCommand: (- callback: (command: ApplicationMenuCommand) => void,- ): (() => void) =>+ onApplicationMenuCommand: (callback: (command: ApplicationMenuCommand) => void): (() => void) =>fanOutApplicationMenuCommand((payload) => {if (isApplicationMenuCommand(payload)) {callback(payload);@@ -817,8 +840,7 @@ contextBridge.exposeInMainWorld('electronAPI', {list: (): Promise<LocalThemesResult> => ipcRenderer.invoke('local-themes:list'),write: (req: LocalThemeWriteRequest): Promise<LocalThemeWriteResult> =>ipcRenderer.invoke('local-themes:write', req),- openDir: (): Promise<LocalThemeOpenDirResult> =>- ipcRenderer.invoke('local-themes:open-dir'),+ openDir: (): Promise<LocalThemeOpenDirResult> => ipcRenderer.invoke('local-themes:open-dir'),// 导入 VSCode / Obsidian 主题文件。对话框与读文件都在 main 侧,这里不接受// 任何路径参数。失败走 IPC 错误协议(reject,renderer 用 extractIpcError 解码)。importExternal: (): Promise<LocalThemeImportResult> =>@@ -831,16 +853,13 @@ contextBridge.exposeInMainWorld('electronAPI', {// - onData / onExit: main → renderer 推送(fanOut 内部一次绑定多订阅,每个 tab 自己按 id filter)terminal: {create: (params: unknown) => ipcRenderer.invoke('terminal:create', params),- write: (id: string, data: string) =>- ipcRenderer.invoke('terminal:write', id, data),+ write: (id: string, data: string) => ipcRenderer.invoke('terminal:write', id, data),resize: (id: string, cols: number, rows: number) =>ipcRenderer.invoke('terminal:resize', id, cols, rows),dispose: (id: string) => ipcRenderer.invoke('terminal:dispose', id),restart: (id: string) => ipcRenderer.invoke('terminal:restart', id),- listAvailableShells: () =>- ipcRenderer.invoke('terminal:list-available-shells'),- getDefaultShellPref: () =>- ipcRenderer.invoke('terminal:get-default-shell-pref'),+ listAvailableShells: () => ipcRenderer.invoke('terminal:list-available-shells'),+ getDefaultShellPref: () => ipcRenderer.invoke('terminal:get-default-shell-pref'),setDefaultShellPref: (value: string) =>ipcRenderer.invoke('terminal:set-default-shell-pref', value),onData: (cb: IpcCallback) => fanOutTerminalData(cb),@@ -931,13 +950,11 @@ contextBridge.exposeInMainWorld('electronAPI', {install: (lizFilePath: string,opts: { enable?: boolean; expectedPackageSha256: string },- ): Promise<{ ghost: unknown }> =>- ipcRenderer.invoke('ghosts:install', lizFilePath, opts),+ ): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:install', lizFilePath, opts),update: (lizFilePath: string,opts: { expectedPackageSha256: string },- ): Promise<{ ghost: unknown }> =>- ipcRenderer.invoke('ghosts:update', lizFilePath, opts),+ ): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:update', lizFilePath, opts),cindyPrefsSync: (id: string,): {@@ -946,12 +963,25 @@ contextBridge.exposeInMainWorld('electronAPI', {* 每类目一份下拉数据(能力键按类目取对应清单)。* options 为空或 defaultModel 为 null = 目录没给该类目模型,能力暂不可用。*/- image: { options: Array<{ id: string; label: string }>; defaultModel: { id: string; label: string } | null };- video: { options: Array<{ id: string; label: string }>; defaultModel: { id: string; label: string } | null };+ image: {+ options: Array<{ id: string; label: string }>;+ defaultModel: { id: string; label: string } | null;+ };+ video: {+ options: Array<{ id: string; label: string }>;+ defaultModel: { id: string; label: string } | null;+ };/** 文本类(快问快答):选项是轻量任务模型链的档位(供应商×模型),不是媒体目录模型。 */- text: { options: Array<{ id: string; label: string }>; defaultModel: { id: string; label: string } | null };+ text: {+ options: Array<{ id: string; label: string }>;+ defaultModel: { id: string; label: string } | null;+ };} => ipcRenderer.sendSync('ghosts:cindy-prefs', id),- setCindyPref: (id: string, capability: string, model: string | null): Promise<{ overrides: Record<string, string> }> =>+ setCindyPref: (+ id: string,+ capability: string,+ model: string | null,+ ): Promise<{ overrides: Record<string, string> }> =>ipcRenderer.invoke('ghosts:cindy-prefs:set', id, capability, model),/** 派活(errand)每插件配置(插件详情页「AI 代办」卡;sendSync 首帧同帧渲染)。 */errandPrefsSync: (id: string): { config: Record<string, unknown> } =>@@ -963,23 +993,30 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('ghosts:errand-prefs:set', id, config),pickFile: (): Promise<{ canceled: true } | { filePath: string }> =>ipcRenderer.invoke('ghosts:pick-file'),- inspect: (lizFilePath: string): Promise<{+ inspect: (+ lizFilePath: string,+ ): Promise<{manifest: unknown;trust: unknown;packageSha256: string;iconDataUrl?: string;- }> =>- ipcRenderer.invoke('ghosts:inspect', lizFilePath),+ }> => ipcRenderer.invoke('ghosts:inspect', lizFilePath),uninstall: (id: string): Promise<{ ok: true }> => ipcRenderer.invoke('ghosts:uninstall', id),/** 详情页「导出 .cindy」:main 打包安装目录 → 系统保存对话框落盘。 */- export: (id: string): Promise<{ status: 'saved'; savedPath: string } | { status: 'canceled' }> =>+ export: (+ id: string,+ ): Promise<{ status: 'saved'; savedPath: string } | { status: 'canceled' }> =>ipcRenderer.invoke('ghosts:export', id),setEnabled: (id: string, enabled: boolean): Promise<{ ok: true }> =>ipcRenderer.invoke('ghosts:set-enabled', id, enabled),/** 目录级禁用清单(插件页项目范围视图;sendSync 保证切换同帧渲染)。 */workdirPrefsSync: (workdir: string): { disabled: string[] } =>ipcRenderer.sendSync('ghosts:workdir-prefs', workdir),- setWorkdirDisabled: (workdir: string, id: string, disabled: boolean): Promise<{ disabled: string[] }> =>+ setWorkdirDisabled: (+ workdir: string,+ id: string,+ disabled: boolean,+ ): Promise<{ disabled: string[] }> =>ipcRenderer.invoke('ghosts:workdir-prefs:set', workdir, id, disabled),takePendingInstall: (): Promise<{ filePath: string | null }> =>ipcRenderer.invoke('ghosts:take-pending-install'),@@ -1050,22 +1087,36 @@ contextBridge.exposeInMainWorld('electronAPI', {// 交互卡(v2)按钮点击回传:renderer 受信桥捕获 data-ghost-action 点击后调,// 主机验卡片归属→唤醒意识→管子下发 card-action 事件。fire-and-forget。// prompt 仅 data-ghost-prompt 类动作有(宿主输入框收集的用户文字)。- dispatchCardAction: (callId: string, actionId: string, prompt?: string): Promise<{ ok: boolean }> =>+ dispatchCardAction: (+ callId: string,+ actionId: string,+ prompt?: string,+ ): Promise<{ ok: boolean }> =>ipcRenderer.invoke('ghosts:card:action', callId, actionId, prompt),resolvePanelMedia: (uri: string,purpose?: 'attach' | 'menu',): Promise<| { url: string; kind?: 'image' }- | { url: string; kind: 'video'; absPath: string; size: number; name: string; ext: string; mimeType: string }+ | {+ url: string;+ kind: 'video';+ absPath: string;+ size: number;+ name: string;+ ext: string;+ mimeType: string;+ }> => ipcRenderer.invoke('ghosts:resolve-panel-media', uri, purpose),runtimeStates: (): Promise<{ states: Record<string, string> }> =>ipcRenderer.invoke('ghosts:runtime-states'),reload: (id: string): Promise<{ state: string }> => ipcRenderer.invoke('ghosts:reload', id),- legacyRecoveryStatus: (): Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus> =>- ipcRenderer.invoke('ghosts:legacy-recovery-status'),- retryLegacyRecovery: (): Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus> =>- ipcRenderer.invoke('ghosts:retry-legacy-recovery'),+ legacyRecoveryStatus: (): Promise<+ import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus+ > => ipcRenderer.invoke('ghosts:legacy-recovery-status'),+ retryLegacyRecovery: (): Promise<+ import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus+ > => ipcRenderer.invoke('ghosts:retry-legacy-recovery'),// dev-only 运行时控制(packaged 版 main 侧不注册该 channel)。devRuntime: (action: 'status' | 'spawn' | 'stop' | 'crash', id?: string): Promise<unknown> =>ipcRenderer.invoke('ghosts:dev-runtime', action, id),@@ -1076,9 +1127,7 @@ contextBridge.exposeInMainWorld('electronAPI', {pluginMarket: {snapshot: (): Promise<import('../shared/pluginMarket').PluginMarketSnapshot> =>ipcRenderer.invoke('plugin-market:snapshot'),- detail: (- pluginId: string,- ): Promise<import('../shared/pluginMarket').PluginMarketDetail> =>+ detail: (pluginId: string): Promise<import('../shared/pluginMarket').PluginMarketDetail> =>ipcRenderer.invoke('plugin-market:detail', pluginId),install: (pluginId: string,@@ -1103,28 +1152,27 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('plugin-market:add-source', input),removeSource: (name: string): Promise<{ ok: true }> =>ipcRenderer.invoke('plugin-market:remove-source', name),- refreshSource: (- name: string,- ): Promise<import('../shared/pluginMarket').MarketSourceSummary> =>+ refreshSource: (name: string): Promise<import('../shared/pluginMarket').MarketSourceSummary> =>ipcRenderer.invoke('plugin-market:refresh-source', name),gitPreflight: (): Promise<{ ok: boolean; version: string | null }> =>ipcRenderer.invoke('plugin-market:git-preflight'),},voiceInput: {- prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }): Promise<{ ok: true }> =>- ipcRenderer.invoke('voice-input:prewarm', payload),- getBenchmarkFixtureAudio: (): Promise<{ ok: true; path: string; wav: ArrayBuffer } | { ok: false }> =>- ipcRenderer.invoke('voice-input:benchmark-fixture-audio'),+ prewarm: (payload?: {+ sourceLanguage?: string;+ refinementEnabled?: boolean;+ }): Promise<{ ok: true }> => ipcRenderer.invoke('voice-input:prewarm', payload),+ getBenchmarkFixtureAudio: (): Promise<+ { ok: true; path: string; wav: ArrayBuffer } | { ok: false }+ > => ipcRenderer.invoke('voice-input:benchmark-fixture-audio'),getMicrophonePermissionCached: ():- | { ok: true; status: string }- | { ok: false; status: string; error: string } =>+ { ok: true; status: string } | { ok: false; status: string; error: string } =>ipcRenderer.sendSync('voice-input:get-microphone-permission-cached'),getSystemPermissionsCached: (): {microphone: { ok: true; status: string } | { ok: false; status: string; error: string };inputMonitoring: { ok: true; status: string } | { ok: false; status: string; error: string };accessibility: { ok: true; status: string } | { ok: false; status: string; error: string };- } =>- ipcRenderer.sendSync('voice-input:get-system-permissions-cached'),+ } => ipcRenderer.sendSync('voice-input:get-system-permissions-cached'),requestMicrophonePermission: (): Promise<{ ok: true } | { ok: false; error: string }> =>ipcRenderer.invoke('voice-input:request-microphone-permission'),setRendererMicrophonePermissionVerified: (verified: boolean): Promise<{ ok: true }> =>@@ -1133,8 +1181,7 @@ contextBridge.exposeInMainWorld('electronAPI', {microphone: { ok: true; status: string } | { ok: false; status: string; error: string };inputMonitoring: { ok: true; status: string } | { ok: false; status: string; error: string };accessibility: { ok: true; status: string } | { ok: false; status: string; error: string };- }> =>- ipcRenderer.invoke('voice-input:get-system-permissions'),+ }> => ipcRenderer.invoke('voice-input:get-system-permissions'),openMicrophoneSettings: (): Promise<{ ok: true } | { ok: false; error: string }> =>ipcRenderer.invoke('voice-input:open-microphone-settings'),openInputMonitoringSettings: (): Promise<VoiceInputGlobalResult> =>@@ -1151,12 +1198,15 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('voice-input:restore-system-audio'),testConnection: (): Promise<VoiceInputConnectionTestResult> =>ipcRenderer.invoke(VOICE_INPUT_TEST_CONNECTION_CHANNEL),- getReadiness: (): Promise<VoiceInputReadinessWire> => ipcRenderer.invoke('voice-input:get-readiness'),+ getReadiness: (): Promise<VoiceInputReadinessWire> =>+ ipcRenderer.invoke('voice-input:get-readiness'),getReadinessCached: (): VoiceInputReadinessWire | null =>ipcRenderer.sendSync('voice-input:get-readiness-cached'),getModelSelection: (): Promise<VoiceInputModelSelectionResultWire> =>ipcRenderer.invoke('voice-input:model-selection:get'),- setModelSelection: (patch: VoiceInputModelSelectionPatchWire): Promise<VoiceInputModelSelectionResultWire> =>+ setModelSelection: (+ patch: VoiceInputModelSelectionPatchWire,+ ): Promise<VoiceInputModelSelectionResultWire> =>ipcRenderer.invoke('voice-input:model-selection:set', patch),reloadModelSelection: (): Promise<VoiceInputModelSelectionResultWire> =>ipcRenderer.invoke('voice-input:model-selection:reload'),@@ -1177,26 +1227,31 @@ contextBridge.exposeInMainWorld('electronAPI', {selectionAfter?: string;replyToMessage?: string;};- }): Promise<{ ok: true; runId: string } | { ok: false; error: string; authErrorReason?: string }> =>- ipcRenderer.invoke('voice-input:start', params),+ }): Promise<+ { ok: true; runId: string } | { ok: false; error: string; authErrorReason?: string }+ > => ipcRenderer.invoke('voice-input:start', params),appendAudio: (chunk: { pcm16k: ArrayBuffer; trace?: unknown }): void =>ipcRenderer.send('voice-input:audio', chunk),- drainAudioQueue: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('voice-input:audio-drain'),+ drainAudioQueue: (): Promise<{ ok: true }> => ipcRenderer.invoke('voice-input:audio-drain'),stop: (): Promise<{ ok: true } | { ok: false; error: string }> =>ipcRenderer.invoke('voice-input:stop'),cancel: (params?: { runId?: string }): Promise<{ ok: true }> =>ipcRenderer.invoke('voice-input:cancel', params),onEvent: fanOutVoiceInputEvent,getDataSnapshot: (): unknown => ipcRenderer.sendSync('voice-input:data:get'),- migrateLegacyRendererData: (payload: { settingsRaw?: string | null; historyRaw?: string | null }): unknown => {+ migrateLegacyRendererData: (payload: {+ settingsRaw?: string | null;+ historyRaw?: string | null;+ }): unknown => {const result = ipcRenderer.sendSync('voice-input:data:migrate-legacy', payload);throwVoiceInputSyncError(result);return result;},updateSettings: (patch: unknown): Promise<unknown> =>ipcRenderer.invoke('voice-input:settings:update', patch),- updateShortcutSetting: (shortcut: VoiceInputShortcutWire | null): Promise<VoiceInputSettingsUpdateResult> =>+ updateShortcutSetting: (+ shortcut: VoiceInputShortcutWire | null,+ ): Promise<VoiceInputSettingsUpdateResult> =>ipcRenderer.invoke('voice-input:settings:update-shortcut', shortcut),deleteDictionaryEntries: (entryIds: string[]): Promise<unknown> =>ipcRenderer.invoke('voice-input:dictionary:delete-entries', entryIds),@@ -1255,9 +1310,11 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('voice-input:dictionary-learning:advise', payload),onDictionaryLearningEvidence: fanOutVoiceInputDictionaryLearningEvidence,onPowerStateChange: fanOutVoiceInputPowerStateChange,- notifyGlobalOverlayReady: (): void =>- ipcRenderer.send('voice-input:global-overlay-ready'),- pasteIntoFocusedTarget: (text: string, rawTranscriptText?: string): Promise<VoiceInputGlobalResult> =>+ notifyGlobalOverlayReady: (): void => ipcRenderer.send('voice-input:global-overlay-ready'),+ pasteIntoFocusedTarget: (+ text: string,+ rawTranscriptText?: string,+ ): Promise<VoiceInputGlobalResult> =>ipcRenderer.invoke('voice-input:global-paste', { text, rawTranscriptText }),restoreGlobalPasteTargetFocus: (): Promise<VoiceInputGlobalResult> =>ipcRenderer.invoke('voice-input:global-restore-target-focus'),@@ -1267,12 +1324,9 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('voice-input:global-overlay-show-passive'),// 浮窗自定义拖动:renderer 只报告手势相位,坐标由 main 读系统光标位置;// send(fire-and-forget)保证 move tick 不阻塞渲染帧。- beginGlobalOverlayDrag: (): void =>- ipcRenderer.send('voice-input:global-overlay-drag-start'),- moveGlobalOverlayDrag: (): void =>- ipcRenderer.send('voice-input:global-overlay-drag-move'),- endGlobalOverlayDrag: (): void =>- ipcRenderer.send('voice-input:global-overlay-drag-end'),+ beginGlobalOverlayDrag: (): void => ipcRenderer.send('voice-input:global-overlay-drag-start'),+ moveGlobalOverlayDrag: (): void => ipcRenderer.send('voice-input:global-overlay-drag-move'),+ endGlobalOverlayDrag: (): void => ipcRenderer.send('voice-input:global-overlay-drag-end'),resetGlobalOverlayPosition: (): Promise<{ ok: true }> =>ipcRenderer.invoke('voice-input:global-overlay-position-reset'),openAccessibilitySettings: (): Promise<VoiceInputGlobalResult> =>@@ -1296,17 +1350,16 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke(WINDOW_BEHAVIOR_SET_SWALLOW_ACTIVATION_CLICK_CHANNEL, enabled),getWindowsCloseBehavior: (): Promise<WindowsCloseBehavior | null> =>ipcRenderer.invoke(WINDOW_BEHAVIOR_GET_WINDOWS_CLOSE_BEHAVIOR_CHANNEL),- setWindowsCloseBehavior: (- behavior: WindowsCloseBehavior,- ): Promise<WindowsCloseBehavior> =>+ setWindowsCloseBehavior: (behavior: WindowsCloseBehavior): Promise<WindowsCloseBehavior> =>ipcRenderer.invoke(WINDOW_BEHAVIOR_SET_WINDOWS_CLOSE_BEHAVIOR_CHANNEL, behavior),onWindowsCloseBehaviorRequested: (callback: () => void): (() => void) => {const listener = (): void => callback();ipcRenderer.on(WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_REQUESTED_CHANNEL, listener);- return () => ipcRenderer.removeListener(- WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_REQUESTED_CHANNEL,- listener,- );+ return () =>+ ipcRenderer.removeListener(+ WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_REQUESTED_CHANNEL,+ listener,+ );},notifyWindowsCloseBehaviorPromptShown: (): void =>ipcRenderer.send(WINDOW_BEHAVIOR_WINDOWS_CLOSE_BEHAVIOR_SHOWN_CHANNEL),@@ -1366,8 +1419,9 @@ contextBridge.exposeInMainWorld('electronAPI', {string,{ detached: boolean; lastOpen: boolean; open: boolean }>,- getState: (): Promise<Record<string, { detached: boolean; lastOpen: boolean; open: boolean }>> =>- ipcRenderer.invoke('maker:ghost-panel-window:get-state'),+ getState: (): Promise<+ Record<string, { detached: boolean; lastOpen: boolean; open: boolean }>+ > => ipcRenderer.invoke('maker:ghost-panel-window:get-state'),/** 幂等:已开则 show + focus。 */open: (ghostId: string): Promise<void> =>ipcRenderer.invoke('maker:ghost-panel-window:open', ghostId),@@ -1395,8 +1449,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ok: true;options: AgentIslandDisplayOption[];target?: AgentIslandDisplayTarget;- }> =>- ipcRenderer.invoke(AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL),+ }> => ipcRenderer.invoke(AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL),previewSound: (sound: AgentIslandSoundChoice): Promise<{ ok: true }> =>ipcRenderer.invoke(AGENT_ISLAND_PREVIEW_SOUND_CHANNEL, sound),selectSoundFile: (): Promise<{ ok: true; path: string | null; name: string | null }> =>@@ -1416,8 +1469,9 @@ contextBridge.exposeInMainWorld('electronAPI', {findNext?: boolean;matchCase?: boolean;}): Promise<number | null> => ipcRenderer.invoke('find-in-page:start', params),- stopFindInPage: (action: 'clearSelection' | 'keepSelection' | 'activateSelection' = 'clearSelection') =>- ipcRenderer.send('find-in-page:stop', action),+ stopFindInPage: (+ action: 'clearSelection' | 'keepSelection' | 'activateSelection' = 'clearSelection',+ ) => ipcRenderer.send('find-in-page:stop', action),onFindInPageResult: fanOutFindInPageResult,onSelectionContextMenuAddToChat: fanOutSelectionContextMenuAddToChat,@@ -1472,8 +1526,7 @@ contextBridge.exposeInMainWorld('electronAPI', {deviceId: string;hasAccountDeletionReceipt: boolean;accountDeletionRestored: boolean;- }> =>- ipcRenderer.invoke('auth:initialize'),+ }> => ipcRenderer.invoke('auth:initialize'),authGetLoginState: (): Promise<DesktopLoginActionResult> =>ipcRenderer.invoke('auth:get-login-state'),authDispatchLoginAction: (action: DesktopLoginAction): Promise<DesktopLoginActionResult> =>@@ -1576,9 +1629,11 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{verdict: 'connected' | 'conflict' | 'error' | 'pending';}> => ipcRenderer.invoke('feishuBot:save', payload),- reconnect: (): Promise<{ verdict: 'connected' | 'conflict' | 'error' }> => ipcRenderer.invoke('feishuBot:reconnect'),+ reconnect: (): Promise<{ verdict: 'connected' | 'conflict' | 'error' }> =>+ ipcRenderer.invoke('feishuBot:reconnect'),clear: (): Promise<{ ok: true }> => ipcRenderer.invoke('feishuBot:clear'),- setLifecycleAnnouncement: (enabled: boolean): Promise<{ ok: true }> => ipcRenderer.invoke('feishuBot:set-lifecycle-announcement', { enabled }),+ setLifecycleAnnouncement: (enabled: boolean): Promise<{ ok: true }> =>+ ipcRenderer.invoke('feishuBot:set-lifecycle-announcement', { enabled }),registrationBegin: (service: 'feishu' | 'lark',): Promise<{@@ -1590,7 +1645,8 @@ contextBridge.exposeInMainWorld('electronAPI', {interval?: number;error?: string;}> => ipcRenderer.invoke('feishuBot:registration-begin', { service }),- registrationCancel: (): Promise<{ ok: true }> => ipcRenderer.invoke('feishuBot:registration-cancel'),+ registrationCancel: (): Promise<{ ok: true }> =>+ ipcRenderer.invoke('feishuBot:registration-cancel'),onStatusChange: fanOutFeishuBotStatusChange,onConflict: fanOutFeishuBotConflict,onRegistrationStatus: fanOutFeishuBotRegistrationStatus,@@ -1608,7 +1664,10 @@ contextBridge.exposeInMainWorld('electronAPI', {| { kind: 'error'; reason: string };ownerUserId: string | null;}> => ipcRenderer.invoke('discordBot:get-status'),- setConfig: (payload: { token: string; ownerUserId: string }): Promise<{+ setConfig: (payload: {+ token: string;+ ownerUserId: string;+ }): Promise<{status:| { kind: 'idle' }| { kind: 'connecting' }@@ -1645,7 +1704,10 @@ contextBridge.exposeInMainWorld('electronAPI', {ownerUserId: string | null;botUsername: string | null;}> => ipcRenderer.invoke('telegramBot:get-status'),- setConfig: (payload: { token: string; ownerUserId: string }): Promise<{+ setConfig: (payload: {+ token: string;+ ownerUserId: string;+ }): Promise<{status: TelegramBotStatusWire;saveErrorStatus?: TelegramBotStatusWire;ownerUserId: string | null;@@ -1658,7 +1720,9 @@ contextBridge.exposeInMainWorld('electronAPI', {* 上线/下线: 只切轮询, 保留 token 与绑定信息(与 disconnect 清凭证相对)。* 换机器时把这一端让出来, 之后随时可再上线。*/- setOnline: (payload: { online: boolean }): Promise<{+ setOnline: (payload: {+ online: boolean;+ }): Promise<{status: TelegramBotStatusWire;}> => ipcRenderer.invoke('telegramBot:set-online', payload),checkSessionAuth: (): Promise<DiscordBotSessionAuthCheckWire> =>@@ -1754,7 +1818,10 @@ contextBridge.exposeInMainWorld('electronAPI', {botId: string | null;ownerUserId: string | null;}> => ipcRenderer.invoke('wecomBot:get-status'),- setConfig: (payload: { botId: string; secret: string }): Promise<{+ setConfig: (payload: {+ botId: string;+ secret: string;+ }): Promise<{status:| { kind: 'idle' }| { kind: 'connecting' }@@ -1838,8 +1905,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// ensureReady 成功之后 fire-and-forget 调一次。main 收到后才启动 FeishuBot// 的 WS 长连接 —— 在此之前 bot 不上线,避免"bot 已上线但 db/auth 未就绪,// 用户回消息撞 localDb not ready" 的 race。幂等,多次调用无副作用。- appReadyForBot: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('app:ready-for-bot'),+ appReadyForBot: (): Promise<{ ok: true }> => ipcRenderer.invoke('app:ready-for-bot'),// ── IM Binding (feishu /ctr 接管 → desktop session 路由) ──// 整体接管态由 main/im/binding.ts 维护; renderer 用这套 API 实时知道@@ -1876,10 +1942,12 @@ contextBridge.exposeInMainWorld('electronAPI', {* 被控端 renderer → 自身 main:providerModelMemory 全量快照镜像。device-link 草稿列表行的真实* 读源(非选中模型),控制端据此完整镜像被控端草稿模型列表。启动推一次 + 变化增量推。*/- syncProviderModelMemory: (snapshot: Record<- string,- { effortByModel: Record<string, string>; fastByModel: Record<string, boolean> }- >): void => ipcRenderer.send('maker:sync-provider-model-memory', snapshot),+ syncProviderModelMemory: (+ snapshot: Record<+ string,+ { effortByModel: Record<string, string>; fastByModel: Record<string, boolean> }+ >,+ ): void => ipcRenderer.send('maker:sync-provider-model-memory', snapshot),/*** 被控端 renderer → 自身 main:会话「非选中模型」effort/fast 在本端变化时镜像给 main,@@ -1909,13 +1977,17 @@ contextBridge.exposeInMainWorld('electronAPI', {binding: {/** 查指定 sessionId 当前是否被任何 IM 接管。命中带 displayName (channel* 上下文里取的姓名, e.g. 飞书姓名), 失败 null, mask 用 fallback 文案。 */- resolveSession: (sessionId: string): Promise<{+ resolveSession: (+ sessionId: string,+ ): Promise<{attached: boolean;identity?: { channel: string; botContextId: string; userId: string } | null;displayName?: string | null;}> => ipcRenderer.invoke('binding:resolve-session', sessionId),/** desktop UI 收回按钮: 触发 detach + 通知对应 IM 用户 */- revoke: (sessionId: string): Promise<{+ revoke: (+ sessionId: string,+ ): Promise<{ok: true;alreadyDetached?: boolean;}> => ipcRenderer.invoke('binding:revoke', sessionId),@@ -1941,8 +2013,7 @@ contextBridge.exposeInMainWorld('electronAPI', {action?: 'relaunch' | 'none';version?: string;error?: 'manifest_failed' | 'download_failed';- }> =>- ipcRenderer.invoke('update-check-startup'),+ }> => ipcRenderer.invoke('update-check-startup'),getUpdateStatus: (): Promise<{ status: string; version?: string; errorCode?: string }> =>ipcRenderer.invoke('update-get-status'),getAutoUpdateSettings: (): Promise<{@@ -1990,15 +2061,12 @@ contextBridge.exposeInMainWorld('electronAPI', {createSubscription: (payload) =>ipcRenderer.invoke(BILLING_INVOKE.CREATE_SUBSCRIPTION, payload),getCurrentSubscription: () => ipcRenderer.invoke(BILLING_INVOKE.GET_CURRENT_SUBSCRIPTION),- cancelCurrentSubscription: () =>- ipcRenderer.invoke(BILLING_INVOKE.CANCEL_CURRENT_SUBSCRIPTION),+ cancelCurrentSubscription: () => ipcRenderer.invoke(BILLING_INVOKE.CANCEL_CURRENT_SUBSCRIPTION),refreshSubscriptionPurchase: (payload) =>ipcRenderer.invoke(BILLING_INVOKE.REFRESH_SUBSCRIPTION_PURCHASE, payload),quotePlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.QUOTE_PLAN_CHANGE, payload),- confirmPlanChange: (payload) =>- ipcRenderer.invoke(BILLING_INVOKE.CONFIRM_PLAN_CHANGE, payload),- refreshPlanChange: (payload) =>- ipcRenderer.invoke(BILLING_INVOKE.REFRESH_PLAN_CHANGE, payload),+ confirmPlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.CONFIRM_PLAN_CHANGE, payload),+ refreshPlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.REFRESH_PLAN_CHANGE, payload),cancelPlanChange: (payload) => ipcRenderer.invoke(BILLING_INVOKE.CANCEL_PLAN_CHANGE, payload),openSubscriptionPortal: () => ipcRenderer.invoke(BILLING_INVOKE.OPEN_SUBSCRIPTION_PORTAL),openPaymentRedirect: (payload) =>@@ -2017,57 +2085,116 @@ contextBridge.exposeInMainWorld('electronAPI', {relPath?: string;hideMetaFiles?: boolean;docMode?: boolean;- }): Promise<Array<{- name: string;- relPath: string;- type: 'file' | 'directory';- size: number;- mtimeMs: number;- }>> => ipcRenderer.invoke('maker:file-browser:list-dir', params),+ }): Promise<+ Array<{+ name: string;+ relPath: string;+ type: 'file' | 'directory';+ size: number;+ mtimeMs: number;+ }>+ > => ipcRenderer.invoke('maker:file-browser:list-dir', params),/** 项目级文件名扁平列表(ripgrep --files honor .gitignore);供 RSB 快速文件* 筛选用。失败返回空数组 + `error`,renderer fallback 渲染"项目空"占位。 */- listAllFiles: (params: { remoteHostId?: string | null; workdir: string; cap?: number }): Promise<{+ listAllFiles: (params: {+ remoteHostId?: string | null;+ workdir: string;+ cap?: number;+ }): Promise<{files: string[];truncated: boolean;elapsedMs: number;error?: string;}> => ipcRenderer.invoke('maker:file-browser:list-all', params),- readFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<- | { ok: true; data: { relPath: string; content: string; size: number; mtimeMs: number; truncated: boolean } }+ readFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<+ | {+ ok: true;+ data: {+ relPath: string;+ content: string;+ size: number;+ mtimeMs: number;+ truncated: boolean;+ };+ }| { ok: false; code: 'BINARY_FILE' | 'READ_FAILED'; message?: string }/** OVERSIZE = 远程文本超传输上限(device-link 帧限预判),stat 供"文件过大"占位卡。 */- | { ok: false; code: 'OVERSIZE'; stat: { relPath: string; type: 'file'; size: number; mtimeMs: number } }+ | {+ ok: false;+ code: 'OVERSIZE';+ stat: { relPath: string; type: 'file'; size: number; mtimeMs: number };+ }> => ipcRenderer.invoke('maker:file-browser:read-file', params),- writeFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string; content: string }): Promise<- | { ok: true; size: number; mtimeMs: number }- | { ok: false; message: string }- > => ipcRenderer.invoke('maker:file-browser:write-file', params),- createFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ writeFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ content: string;+ }): Promise<{ ok: true; size: number; mtimeMs: number } | { ok: false; message: string }> =>+ ipcRenderer.invoke('maker:file-browser:write-file', params),+ createFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }> => ipcRenderer.invoke('maker:file-browser:create-file', params),- createFolder: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ createFolder: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }> => ipcRenderer.invoke('maker:file-browser:create-folder', params),- deleteEntry: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<- | { ok: true }- | { ok: false; message: string }- > => ipcRenderer.invoke('maker:file-browser:delete-entry', params),- renameEntry: (params: { remoteHostId?: string | null; workdir: string; fromRel: string; toRel: string }): Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ deleteEntry: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<{ ok: true } | { ok: false; message: string }> =>+ ipcRenderer.invoke('maker:file-browser:delete-entry', params),+ renameEntry: (params: {+ remoteHostId?: string | null;+ workdir: string;+ fromRel: string;+ toRel: string;+ }): Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }> => ipcRenderer.invoke('maker:file-browser:rename-entry', params),- stat: (params: { remoteHostId?: string | null; workdir: string; relPath: string }): Promise<{+ stat: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }): Promise<{relPath: string;type: 'file' | 'directory';size: number;mtimeMs: number;}> => ipcRenderer.invoke('maker:file-browser:stat', params),- startWatch: (params: { remoteHostId?: string | null; workdir: string; hideMetaFiles?: boolean }): Promise<{ ok: boolean }> =>- ipcRenderer.invoke('maker:file-browser:start-watch', params),- stopWatch: (params: { remoteHostId?: string | null; workdir: string }): Promise<{ ok: boolean }> =>- ipcRenderer.invoke('maker:file-browser:stop-watch', params),+ startWatch: (params: {+ remoteHostId?: string | null;+ workdir: string;+ hideMetaFiles?: boolean;+ }): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:file-browser:start-watch', params),+ stopWatch: (params: {+ remoteHostId?: string | null;+ workdir: string;+ }): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:file-browser:stop-watch', params),onEvent: (cb: (event: {workdir: string;@@ -2086,7 +2213,9 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{ ok: true; cachePath: string; stale: boolean } | { ok: false; message: string }> =>ipcRenderer.invoke('maker:file-browser:fetch-remote', params),/** 读缓存副本内容(cached 态文本预览;32MB 显示上限,二进制回 kind:'binary')。 */- readCached: (params: { cachePath: string }): Promise<+ readCached: (params: {+ cachePath: string;+ }): Promise<| { ok: true; kind: 'text'; content: string; truncated: boolean }| { ok: true; kind: 'binary' }| { ok: false; message: string }@@ -2103,7 +2232,13 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:file-browser:cache-put', params),/** 大文件取回进度(发起窗口收):{ workdir, relPath, received, total }。 */onTransferProgress: (- cb: (event: { workdir: string; relPath: string; received: number; total: number; phase?: 'upload' | 'download' }) => void,+ cb: (event: {+ workdir: string;+ relPath: string;+ received: number;+ total: number;+ phase?: 'upload' | 'download';+ }) => void,): (() => void) => fanOutFileBrowserTransfer(cb as IpcCallback),/*** 聊天流文件取回:远端绝对路径 → 本地缓存副本(fetch-到缓存-再操作)。@@ -2116,7 +2251,11 @@ contextBridge.exposeInMainWorld('electronAPI', {absPath: string;}): Promise<| { ok: true; cachePath: string; stale: boolean; size: number }- | { ok: false; code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED'; message?: string }+ | {+ ok: false;+ code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED';+ message?: string;+ }> => ipcRenderer.invoke('maker:chat-file:fetch', params),/** 聊天流文件 chip 点亮预检:远端精确 stat。file=点亮;nonfile=保持纯文本;unknown=乐观点亮。 */chatStat: (params: {@@ -2154,34 +2293,40 @@ contextBridge.exposeInMainWorld('electronAPI', {lineText: string;submatches: Array<{ start: number; end: number }>;}- | { type: 'end'; searchId: string; truncated: boolean; totalMatches: number; totalFiles: number }+ | {+ type: 'end';+ searchId: string;+ truncated: boolean;+ totalMatches: number;+ totalFiles: number;+ }| { type: 'error'; searchId: string; message: string }>;}/** code = 稳定错误码(如 RG_UNAVAILABLE),renderer 按码映射友好文案。 */| { ok: false; message: string; code?: string }- > =>- ipcRenderer.invoke('maker:search:start', params),+ > => ipcRenderer.invoke('maker:search:start', params),cancel: (params: { searchId: string; remoteHostId?: string | null }): Promise<{ ok: true }> =>ipcRenderer.invoke('maker:search:cancel', params),onEvent: (- cb: (event:- | {- type: 'match';- searchId: string;- relPath: string;- lineNumber: number;- lineText: string;- submatches: Array<{ start: number; end: number }>;- }- | {- type: 'end';- searchId: string;- truncated: boolean;- totalMatches: number;- totalFiles: number;- }- | { type: 'error'; searchId: string; message: string }+ cb: (+ event:+ | {+ type: 'match';+ searchId: string;+ relPath: string;+ lineNumber: number;+ lineText: string;+ submatches: Array<{ start: number; end: number }>;+ }+ | {+ type: 'end';+ searchId: string;+ truncated: boolean;+ totalMatches: number;+ totalFiles: number;+ }+ | { type: 'error'; searchId: string; message: string },) => void,): (() => void) => fanOutSearchEvent(cb as IpcCallback),},@@ -2222,20 +2367,24 @@ contextBridge.exposeInMainWorld('electronAPI', {// 状态流:learn:start 后经 onEvent 订阅 run 状态推进(collecting → distilling →// awaiting-review);提案经 getProposalDiff 审查,apply 确认落盘 / discard 放弃。learn: {- start: (- req: import('../shared/learnTypes').LearnStartRequest,- ): Promise<{ runId: string }> => ipcRenderer.invoke('learn:start', req),+ start: (req: import('../shared/learnTypes').LearnStartRequest): Promise<{ runId: string }> =>+ ipcRenderer.invoke('learn:start', req),- listRuns: (): Promise<{ runs: import('../shared/learnTypes').LearnRunPublic[]; ready: boolean }> =>- ipcRenderer.invoke('learn:list-runs'),+ listRuns: (): Promise<{+ runs: import('../shared/learnTypes').LearnRunPublic[];+ ready: boolean;+ }> => ipcRenderer.invoke('learn:list-runs'),- getProposalDiff: (params: { runId: string }): Promise<import('../shared/learnTypes').LearnProposalDiff> =>+ getProposalDiff: (params: {+ runId: string;+ }): Promise<import('../shared/learnTypes').LearnProposalDiff> =>ipcRenderer.invoke('learn:get-proposal-diff', params),- apply: (params: { runId: string }): Promise<{ name: string; absolutePath: string; replacedBackupPath?: string }> =>+ apply: (params: {+ runId: string;+ }): Promise<{ name: string; absolutePath: string; replacedBackupPath?: string }> =>ipcRenderer.invoke('learn:apply', params),-discard: (params: { runId: string }): Promise<{ ok: boolean }> =>ipcRenderer.invoke('learn:discard', params),@@ -2245,8 +2394,10 @@ contextBridge.exposeInMainWorld('electronAPI', {onEvent: (callback: (payload: import('../shared/learnTypes').LearnEventPayload) => void,): (() => void) => {- const listener = (_event: Electron.IpcRendererEvent, payload: import('../shared/learnTypes').LearnEventPayload): void =>- callback(payload);+ const listener = (+ _event: Electron.IpcRendererEvent,+ payload: import('../shared/learnTypes').LearnEventPayload,+ ): void => callback(payload);ipcRenderer.on('learn:event', listener);return () => ipcRenderer.removeListener('learn:event', listener);},@@ -2266,14 +2417,18 @@ contextBridge.exposeInMainWorld('electronAPI', {sources?: import('../main/skillhub/scanner').SourceReport[];}> => ipcRenderer.invoke('skillhub:scan', params),- readSkill: (params: { mdPath: string }): Promise<{+ readSkill: (params: {+ mdPath: string;+ }): Promise<{success: boolean;error?: string;content?: string;}> => ipcRenderer.invoke('skillhub:read-skill', params),// Lazy directory expansion under a skill's folder (FILES panel tree).- listChildren: (params: { dirPath: string }): Promise<{+ listChildren: (params: {+ dirPath: string;+ }): Promise<{success: boolean;error?: string;entries?: import('../main/skillhub/scanner').SkillFileEntry[];@@ -2282,7 +2437,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// Read a sibling file (any text file inside a skill folder) for in-pane// preview. Returns raw content; renderer wraps non-md files in a code// fence based on their extension.- readSiblingFile: (params: { filePath: string }): Promise<{+ readSiblingFile: (params: {+ filePath: string;+ }): Promise<{success: boolean;error?: string;content?: string;@@ -2290,7 +2447,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// v0.2.2: read raw .md (frontmatter intact) for the in-app MD editor.// Different from readSkill (which strips frontmatter for view rendering).- readRaw: (params: { filePath: string }): Promise<{+ readRaw: (params: {+ filePath: string;+ }): Promise<{success: boolean;error?: string;content?: string;@@ -2298,7 +2457,10 @@ contextBridge.exposeInMainWorld('electronAPI', {// v0.2.2: write a .md back to disk after edit. main enforces path// whitelist + atomic write + 1MB cap + file-must-exist.- writeFile: (params: { filePath: string; content: string }): Promise<{+ writeFile: (params: {+ filePath: string;+ content: string;+ }): Promise<{success: boolean;error?: string;}> => ipcRenderer.invoke('skillhub:write-file', params),@@ -2315,17 +2477,22 @@ contextBridge.exposeInMainWorld('electronAPI', {// 改名整个 skill (目录名 + SKILL.md frontmatter `name`)。// 用于"市场撞名,本地需改名再发布"流程。失败时盘上已回滚。- renameLocal: (params: { absolutePath: string; newName: string }): Promise<- | { success: true; newAbsolutePath: string }- | { success: false; error: string }- > => ipcRenderer.invoke('skillhub:rename-local', params),+ renameLocal: (params: {+ absolutePath: string;+ newName: string;+ }): Promise<{ success: true; newAbsolutePath: string } | { success: false; error: string }> =>+ ipcRenderer.invoke('skillhub:rename-local', params),// ── SkillHub v0.2.1: 发布链路 ──────────────────────────────────────────// 批量同步 skill 市场状态- sync: (params: string[] | {- slugs?: string[];- }): Promise<{+ sync: (+ params:+ | string[]+ | {+ slugs?: string[];+ },+ ): Promise<{success: boolean;results?: unknown[];availableUninstalledCount?: number;@@ -2376,7 +2543,9 @@ contextBridge.exposeInMainWorld('electronAPI', {}> => ipcRenderer.invoke('skillhub:list-market', params),// 查询单个 skill 市场详情(有 in-flight dedupe 在 renderer 侧)- info: (name: string): Promise<{+ info: (+ name: string,+ ): Promise<{success: boolean;info?: unknown;deleted?: boolean;@@ -2384,7 +2553,10 @@ contextBridge.exposeInMainWorld('electronAPI', {errorCode?: string;}> => ipcRenderer.invoke('skillhub:info', { name }),- getPublishedFiles: (params: { name: string; version?: string }): Promise<{+ getPublishedFiles: (params: {+ name: string;+ version?: string;+ }): Promise<{success: boolean;slug?: string;version?: string;@@ -2393,14 +2565,20 @@ contextBridge.exposeInMainWorld('electronAPI', {errorCode?: string;}> => ipcRenderer.invoke('skillhub:get-published-files', params),- readPublishedFile: (params: { name: string; path: string; version?: string }): Promise<{+ readPublishedFile: (params: {+ name: string;+ path: string;+ version?: string;+ }): Promise<{success: boolean;file?: { path: string; size: number; language: string; truncated: boolean; content: string };error?: string;errorCode?: string;}> => ipcRenderer.invoke('skillhub:read-published-file', params),- listPublishedVersions: (name: string): Promise<{+ listPublishedVersions: (+ name: string,+ ): Promise<{success: boolean;versions?: unknown[];error?: string;@@ -2421,10 +2599,14 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>ipcRenderer.invoke('skillhub:update-published', params),- deletePublished: (name: string): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>+ deletePublished: (+ name: string,+ ): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>ipcRenderer.invoke('skillhub:delete-published', { name }),- unpublishPublished: (name: string): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>+ unpublishPublished: (+ name: string,+ ): Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }> =>ipcRenderer.invoke('skillhub:unpublish-published', { name }),setPublishedVisibility: (params: {@@ -2436,7 +2618,9 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('skillhub:set-published-visibility', params),// 读取已发布 skill 的可见对象(共享团队 + 可见部门),编辑可见范围弹窗回显用- getPublishedVisibility: (name: string): Promise<{+ getPublishedVisibility: (+ name: string,+ ): Promise<{success: boolean;sharedTeams?: Array<{ id: number; slug: string; name: string }>;visibleDepts?: string[];@@ -2454,7 +2638,10 @@ contextBridge.exposeInMainWorld('electronAPI', {}> => ipcRenderer.invoke('skillhub:list-categories'),// 查询发布后的安全扫描状态- getScanStatus: (params: { slug: string; version?: string }): Promise<{+ getScanStatus: (params: {+ slug: string;+ version?: string;+ }): Promise<{success: boolean;status: string;gates?: Array<{ name: string; status: string; issues?: unknown[] }>;@@ -2465,13 +2652,22 @@ contextBridge.exposeInMainWorld('electronAPI', {// 拉当前用户所属团队列表(PublishDialog 多团队可见选择用)listUserTeams: (): Promise<{success: boolean;- teams: Array<{ slug: string; name: string; type: string; source?: string | null; isPersonal?: boolean; myRole?: 'admin' | 'publisher' | 'viewer' }>;+ teams: Array<{+ slug: string;+ name: string;+ type: string;+ source?: string | null;+ isPersonal?: boolean;+ myRole?: 'admin' | 'publisher' | 'viewer';+ }>;error?: string;}> => ipcRenderer.invoke('skillhub:list-user-teams'),// 计算本地 skill 文件夹 hash(30s 缓存在 renderer 侧)// manifest 是参与 hash 的文件清单(path + sha256),用于 dirty 排查- getFolderHash: (absolutePath: string): Promise<{+ getFolderHash: (+ absolutePath: string,+ ): Promise<{success: boolean;folderHash?: string;manifest?: Array<{ path: string; sha256: string }>;@@ -2499,14 +2695,23 @@ contextBridge.exposeInMainWorld('electronAPI', {}> => ipcRenderer.invoke('skillhub:get-snapshot-diff', params),// 仅查快照是否存在(轻量 fs.stat) — DetailView 区分"无快照"vs"有快照但 dirty"- hasSnapshot: (name: string): Promise<{+ hasSnapshot: (+ name: string,+ ): Promise<{success: boolean;exists?: boolean;error?: string;}> => ipcRenderer.invoke('skillhub:has-snapshot', { name }),- getUsageSummary: (params: { name: string; mdPath?: string }): Promise<- | { success: true; summary: import('../main/skillhub/usageStore').SkillUsageSummary; refreshing: boolean }+ getUsageSummary: (params: {+ name: string;+ mdPath?: string;+ }): Promise<+ | {+ success: true;+ summary: import('../main/skillhub/usageStore').SkillUsageSummary;+ refreshing: boolean;+ }| { success: false; error: string }> => ipcRenderer.invoke('skillhub:get-usage-summary', params),@@ -2516,7 +2721,10 @@ contextBridge.exposeInMainWorld('electronAPI', {return () => ipcRenderer.removeListener('skillhub:usage-analytics-refreshed', handler);},- getUsageDiagnosisContext: (params: { name: string; mdPath?: string }): Promise<+ getUsageDiagnosisContext: (params: {+ name: string;+ mdPath?: string;+ }): Promise<| { success: true; context: import('../main/skillhub/usageStore').SkillUsageDiagnosisContext }| { success: false; error: string }> => ipcRenderer.invoke('skillhub:get-usage-diagnosis-context', params),@@ -2592,10 +2800,10 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('skillhub:cancel-install', { name }),// 卸载(删本地文件夹)—— main 会校验目标必须有 registry 记录- uninstall: (absolutePath: string): Promise<- | { success: true }- | { success: false; errorCode: string; message: string }- > => ipcRenderer.invoke('skillhub:uninstall', { absolutePath }),+ uninstall: (+ absolutePath: string,+ ): Promise<{ success: true } | { success: false; errorCode: string; message: string }> =>+ ipcRenderer.invoke('skillhub:uninstall', { absolutePath }),/** 在 main 内选择并检查本地包,成功时签发绑定当前 renderer 的短期导入授权。 */pickLocal: (): Promise<@@ -2630,7 +2838,14 @@ contextBridge.exposeInMainWorld('electronAPI', {// 订阅 install 进度事件onInstallProgress: (cb: (event: {- phase: 'fetching-info' | 'downloading' | 'verifying' | 'extracting' | 'registering' | 'done' | 'failed';+ phase:+ | 'fetching-info'+ | 'downloading'+ | 'verifying'+ | 'extracting'+ | 'registering'+ | 'done'+ | 'failed';name: string;version?: string;absolutePath?: string;@@ -2647,7 +2862,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── SkillHub Registry(v0.6 新增) ────────────────────────────────────────registry: {/** 按 skillName 读取整个 registry manifest(含所有 install 条目)。 */- getByName: (params: { name: string }): Promise<{+ getByName: (params: {+ name: string;+ }): Promise<{success: boolean;manifest?: StoredManifest | null;error?: string;@@ -2657,7 +2874,13 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 一次性补齐:把 server 权威 authorId 写回本地 registry。* added = 新建 install 条数;flipped = 把已有 authorId 错或为空的覆盖更新数。 */reconcileMineRegistry: (- items: Array<{ name: string; absolutePath: string; version: string; authorId: string; folderHash?: string }>,+ items: Array<{+ name: string;+ absolutePath: string;+ version: string;+ authorId: string;+ folderHash?: string;+ }>,): Promise<{success: boolean;added: number;@@ -2669,7 +2892,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── Dialog(v0.6 新增) ───────────────────────────────────────────────────dialog: {/** 打开系统目录选择对话框,返回用户选中的目录路径(取消时 path=null)。 */- showOpenDirectory: (params?: { defaultPath?: string }): Promise<{+ showOpenDirectory: (params?: {+ defaultPath?: string;+ }): Promise<{success: boolean;path: string | null;}> => ipcRenderer.invoke('dialog:show-open-directory', params ?? {}),@@ -2682,7 +2907,9 @@ contextBridge.exposeInMainWorld('electronAPI', {path: string | null;}> => ipcRenderer.invoke('dialog:show-open-file', params ?? {}),/** 打开 @ 资源系统选择器;macOS 可选文件或目录,Windows/Linux 选择文件。 */- showOpenResource: (params?: { defaultPath?: string }): Promise<{+ showOpenResource: (params?: {+ defaultPath?: string;+ }): Promise<{success: true;path: string | null;kind: 'file' | 'directory' | null;@@ -2693,8 +2920,7 @@ contextBridge.exposeInMainWorld('electronAPI', {openExternal: (url: string): Promise<{ success: boolean }> =>ipcRenderer.invoke('shell:open-external', url),/** 打开本机 ChatGPT Desktop;main 端固定使用受限的 codex: 协议,不接收 URL。 */- openChatGPTApp: (): Promise<{ success: boolean }> =>- ipcRenderer.invoke('shell:open-chatgpt-app'),+ openChatGPTApp: (): Promise<{ success: boolean }> => ipcRenderer.invoke('shell:open-chatgpt-app'),// file-chip 传绝对路径;内置浏览器传完整本地 file:// URL 以保留 query/hash。// main 端统一解析并做扩展名白名单与 isPathAllowed 安全校验。@@ -2710,8 +2936,7 @@ contextBridge.exposeInMainWorld('electronAPI', {title: string;kind: 'done' | 'error' | 'needs-reply';channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };- }): Promise<void> =>- ipcRenderer.invoke('notification:show-session-event', payload),+ }): Promise<void> => ipcRenderer.invoke('notification:show-session-event', payload),notificationSetDesktopEnabled: (enabled: boolean): Promise<{ ok: true }> =>ipcRenderer.invoke('notification:set-desktop-enabled', enabled),wecomGroupNotification: {@@ -2735,8 +2960,10 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('notification:mark-session-attention', sessionId),// intent:'explicit' = 用户真实看到了内容(报错 banner 聚焦驻留 / 全部标为已读等);// 省略或 'passive' = 导航 / 聚焦类被动信号,main 侧对未读 error 免疫(fail-safe 默认)。- notificationClearSessionAttention: (sessionId: string, intent?: 'explicit' | 'passive'): Promise<void> =>- ipcRenderer.invoke('notification:clear-session-attention', sessionId, intent),+ notificationClearSessionAttention: (+ sessionId: string,+ intent?: 'explicit' | 'passive',+ ): Promise<void> => ipcRenderer.invoke('notification:clear-session-attention', sessionId, intent),// main → renderer 的会话已读广播(含远程控制端发起的清除),payload:{ sessionId, intent }。onSessionAttentionCleared: fanOutSessionAttentionCleared,onNotificationFocusSession: fanOutNotificationFocusSession,@@ -2787,7 +3014,8 @@ contextBridge.exposeInMainWorld('electronAPI', {// RSB web-browser plugin:guest webview 内浏览器级快捷键(导航 + ⌘W 关 tab)。onRsbBrowserCommand: (callback: (payload: {- command: 'go-back' | 'go-forward' | 'reload' | 'close-tab' | 'right-tab-prev' | 'right-tab-next';+ command:+ 'go-back' | 'go-forward' | 'reload' | 'close-tab' | 'right-tab-prev' | 'right-tab-next';}) => void,): (() => void) =>fanOutRsbBrowserCommand((payload) => {@@ -2970,9 +3198,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('media:open-with-default-app', params),// 另存为:弹系统保存对话框;用户取消返回 { canceled: true },不算错误。- saveMediaAs: (params: {- url: string;- }): Promise<{ canceled: boolean; savedPath?: string }> =>+ saveMediaAs: (params: { url: string }): Promise<{ canceled: boolean; savedPath?: string }> =>ipcRenderer.invoke('media:save-as', params),// "发送到对话":把图片复制成目标会话的一份新 xdt-image:// 缓存(draft@@ -2984,9 +3210,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('media:cache-for-session', params),// renderer 字节层:http / cindy-remote-media 图取字节(标注烧录、位图复制)。- readImageBytes: (params: {- url: string;- }): Promise<{ base64: string; mimeType: string }> =>+ readImageBytes: (params: { url: string }): Promise<{ base64: string; mimeType: string }> =>ipcRenderer.invoke('media:read-image-bytes', params),// 附件卡缩略图:本机文件交给系统缩略图服务(macOS QuickLook / Windows Shell)@@ -3021,7 +3245,10 @@ contextBridge.exposeInMainWorld('electronAPI', {hrefs: string[];workingDir: string;}): Promise<- Record<string, { status: 'unique' | 'multiple' | 'none'; candidates: string[]; kind?: 'file' | 'directory' }>+ Record<+ string,+ { status: 'unique' | 'multiple' | 'none'; candidates: string[]; kind?: 'file' | 'directory' }+ >> => ipcRenderer.invoke('fs:resolve-path-batch', params),// 本机文件系统目录浏览(项目选择器「添加远程项目」)。device-link 经隧道在被控端执行@@ -3035,9 +3262,7 @@ contextBridge.exposeInMainWorld('electronAPI', {entries: { name: string; kind: 'dir' | 'symlink'; path: string }[];parent: string | null;}> => ipcRenderer.invoke('fs:list-dir', { path }),- statPath: (- path: string,- ): Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }> =>+ statPath: (path: string): Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }> =>ipcRenderer.invoke('fs:stat-path', { path }),mkdirP: (path: string): Promise<{ resolvedPath: string }> =>ipcRenderer.invoke('fs:mkdir-p', { path }),@@ -3156,7 +3381,9 @@ contextBridge.exposeInMainWorld('electronAPI', {}>;}> => ipcRenderer.invoke('cindy-media:storage-stats'),- scan: (params: { draftUrls: string[] }): Promise<{+ scan: (params: {+ draftUrls: string[];+ }): Promise<{success: boolean;error?: string;zeroRef: { count: number; bytes: number; hashes: string[]; protectedCount: number };@@ -3223,7 +3450,8 @@ contextBridge.exposeInMainWorld('electronAPI', {onUpdateStatus: fanOutUpdateStatus,checkForUpdate: (): Promise<{- result: 'ready' | 'idle' | 'downloading' | 'manifest_failed' | 'download_failed' | 'manual_download';+ result:+ 'ready' | 'idle' | 'downloading' | 'manifest_failed' | 'download_failed' | 'manual_download';}> => ipcRenderer.invoke('update-check-now'),/**@@ -3246,7 +3474,9 @@ contextBridge.exposeInMainWorld('electronAPI', {* Apply a startup-discovered update only after main rechecks the complete* unattended-relaunch policy at the actual execution boundary.*/- autoRelaunchToUpdate: (theme: 'light' | 'dark'): Promise<{+ autoRelaunchToUpdate: (+ theme: 'light' | 'dark',+ ): Promise<{accepted: boolean;blockReason?: string;}> => ipcRenderer.invoke('update-relaunch-auto', theme),@@ -3269,9 +3499,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// Platform is resolved in main via getPlatformKey() to keep the CDN path// axis identical to the hot-update manifest.// Returns null on 404 / network / parse error — caller decides UX.- fetchReleaseNotes: (- version: string,- ): Promise<RawReleaseNotesPayload | null> =>+ fetchReleaseNotes: (version: string): Promise<RawReleaseNotesPayload | null> =>ipcRenderer.invoke('release-notes:fetch', version),// Sorted ascending list of every version with a notice on the CDN. Renderer@@ -3336,7 +3564,10 @@ contextBridge.exposeInMainWorld('electronAPI', {isSelf: boolean;}>;}> => ipcRenderer.invoke('device-link:list-devices'),- renameDevice: (deviceId: string, name: string | null): Promise<{ deviceId: string; name: string; manualName?: string | null }> =>+ renameDevice: (+ deviceId: string,+ name: string | null,+ ): Promise<{ deviceId: string; name: string; manualName?: string | null }> =>ipcRenderer.invoke('device-link:rename-device', { deviceId, name }),deleteDevice: (deviceId: string): Promise<{ deviceId: string; deleted: boolean }> =>ipcRenderer.invoke('device-link:delete-device', { deviceId }),@@ -3355,8 +3586,7 @@ contextBridge.exposeInMainWorld('electronAPI', {unsubscribe: (deviceId: string, topics: string[]): Promise<{ ok: true }> =>ipcRenderer.invoke('device-link:topic-unsubscribe', { deviceId, topics }),/** 被控端:一键断开当前所有控制链路 */- disconnectAll: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('device-link:disconnect-all'),+ disconnectAll: (): Promise<{ ok: true }> => ipcRenderer.invoke('device-link:disconnect-all'),/** 被控端:撤销某控制端的访问权限(逐设备黑名单) */revoke: (deviceId: string): Promise<{ ok: true }> =>ipcRenderer.invoke('device-link:revoke', { deviceId }),@@ -3449,7 +3679,8 @@ contextBridge.exposeInMainWorld('electronAPI', {identityFile?: string;source: 'ssh-config' | 'manual';};- status: 'disconnected' | 'connecting' | 'authenticating' | 'ready' | 'reconnecting' | 'failed';+ status:+ 'disconnected' | 'connecting' | 'authenticating' | 'ready' | 'reconnecting' | 'failed';lastError?: string;statusChangedAt: number;/** Phase D — 启动时是否自动连接 (本地 prefs, 不写入 ~/.ssh/config). */@@ -3489,7 +3720,10 @@ contextBridge.exposeInMainWorld('electronAPI', {onStatusChanged: fanOutRemoteSshStatus,// ── Phase B: agent on remote ──────────────────────────────────────────- probeAgent: (id: string, agentKind: 'claude-code' | 'codex'): Promise<{+ probeAgent: (+ id: string,+ agentKind: 'claude-code' | 'codex',+ ): Promise<{probe: {agentKind: 'claude-code' | 'codex';nodeReady: boolean;@@ -3502,7 +3736,10 @@ contextBridge.exposeInMainWorld('electronAPI', {};}> => ipcRenderer.invoke('maker:remote-ssh:probe-agent', { id, agentKind }),- installAgent: (id: string, agentKind: 'claude-code' | 'codex'): Promise<{+ installAgent: (+ id: string,+ agentKind: 'claude-code' | 'codex',+ ): Promise<{result: {agentKind: 'claude-code' | 'codex';ready: boolean;@@ -3536,21 +3773,33 @@ contextBridge.exposeInMainWorld('electronAPI', {// Reusable by a future remote file browser; currently used by// StartRemoteSessionPanel for "workdir doesn't exist → confirm + mkdir".// Both accept `~` / `~/...` and let the remote bash expand to $HOME.- statRemotePath: (id: string, path: string): Promise<{+ statRemotePath: (+ id: string,+ path: string,+ ): Promise<{kind: 'dir' | 'file' | 'missing';resolvedPath: string;}> => ipcRenderer.invoke('maker:remote-ssh:stat-remote-path', { id, path }),- mkdirPRemote: (id: string, path: string): Promise<{+ mkdirPRemote: (+ id: string,+ path: string,+ ): Promise<{resolvedPath: string;}> => ipcRenderer.invoke('maker:remote-ssh:mkdir-p-remote', { id, path }),// ── Phase D: autoConnect 偏好 + 远端目录浏览 ──────────────────────────- setAutoConnect: (id: string, autoConnect: boolean): Promise<{ ok: true; autoConnect: boolean }> =>+ setAutoConnect: (+ id: string,+ autoConnect: boolean,+ ): Promise<{ ok: true; autoConnect: boolean }> =>ipcRenderer.invoke('maker:remote-ssh:set-auto-connect', { id, autoConnect }),hasAnyAutoConnectHost: (): Promise<{ hasAny: boolean }> =>ipcRenderer.invoke('maker:remote-ssh:has-any-auto-connect-host'),- listRemoteDir: (id: string, path: string): Promise<{+ listRemoteDir: (+ id: string,+ path: string,+ ): Promise<{resolvedPath: string;entries: Array<{ name: string; kind: 'dir' | 'symlink' }>;}> => ipcRenderer.invoke('maker:remote-ssh:list-remote-dir', { id, path }),@@ -3565,7 +3814,10 @@ contextBridge.exposeInMainWorld('electronAPI', {// sessionId 是触发 upgrade 的 banner-clicker session — main 端只 soft-close// 它一个 (有 UpgradeBanner retry snapshot), 其它同 host session 不动避免// in-flight turn 静默丢。- ccMgrForceUpgrade: (hostId: string, sessionId?: string): Promise<{ ok: true; daemonReady: boolean }> =>+ ccMgrForceUpgrade: (+ hostId: string,+ sessionId?: string,+ ): Promise<{ ok: true; daemonReady: boolean }> =>ipcRenderer.invoke('maker:remote-ssh:cc-mgr-force-upgrade', { hostId, sessionId }),ccMgrListPendingUpgrades: (): Promise<{pending: Array<{ hostId: string; currentVersion: string; availableVersion: string }>;@@ -3577,7 +3829,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// Two-step UX: check first (so renderer can build the right confirm// dialog), then sync explicitly after user confirmation. The renderer// is the trust boundary — sync handler does NOT itself prompt.- checkCodexAuth: (id: string): Promise<{+ checkCodexAuth: (+ id: string,+ ): Promise<{localExists: boolean;remoteExists: boolean;remoteMtime: string | null;@@ -3636,11 +3890,13 @@ contextBridge.exposeInMainWorld('electronAPI', {}> => ipcRenderer.invoke('maker:remote-ssh:add-key-to-agent', params),readPubkey: (pubkeyPath: string): Promise<{ content: string }> =>ipcRenderer.invoke('maker:remote-ssh:read-pubkey', { pubkeyPath }),- buildInstallCmd: (id: string, pubkeyPath: string): Promise<{+ buildInstallCmd: (+ id: string,+ pubkeyPath: string,+ ): Promise<{command: string;platform: NodeJS.Platform;- }> =>- ipcRenderer.invoke('maker:remote-ssh:build-install-cmd', { id, pubkeyPath }),+ }> => ipcRenderer.invoke('maker:remote-ssh:build-install-cmd', { id, pubkeyPath }),/*** Inline variant — caller passes user/hostname/port directly instead of a* pool host id. Used by the in-form key-picker dialog where the host@@ -3654,8 +3910,7 @@ contextBridge.exposeInMainWorld('electronAPI', {}): Promise<{command: string;platform: NodeJS.Platform;- }> =>- ipcRenderer.invoke('maker:remote-ssh:build-install-cmd-inline', params),+ }> => ipcRenderer.invoke('maker:remote-ssh:build-install-cmd-inline', params),},worktreeCreate: (req: {@@ -3668,8 +3923,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('worktree:detect-cwd', req),worktreeGetForSession: (sessionId: string): Promise<unknown> =>ipcRenderer.invoke('worktree:get-for-session', sessionId),- worktreeListAll: (): Promise<unknown> =>- ipcRenderer.invoke('worktree:list-all'),+ worktreeListAll: (): Promise<unknown> => ipcRenderer.invoke('worktree:list-all'),worktreeReveal: (req: { path: string }): Promise<unknown> =>ipcRenderer.invoke('worktree:reveal', req),worktreeSuggestName: (req: { baseRepo: string }): Promise<unknown> =>@@ -3682,7 +3936,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// P1: worktree 被回收后的可恢复状态 + 一键恢复(分支重建 + 快照 apply)worktreeRestoreStatus: (sessionId: string): Promise<unknown> =>ipcRenderer.invoke('worktree:restore-status', sessionId),- worktreeRestoreForSession: (sessionId: string): Promise<{ ok: boolean; snapshotApplied?: boolean; message?: string }> =>+ worktreeRestoreForSession: (+ sessionId: string,+ ): Promise<{ ok: boolean; snapshotApplied?: boolean; message?: string }> =>ipcRenderer.invoke('worktree:restore-for-session', sessionId),/*** 订阅「worktree 回收链已跑完」。payload: { sessionId }。@@ -3714,10 +3970,8 @@ contextBridge.exposeInMainWorld('electronAPI', {): Promise<{ hook: unknown }> =>ipcRenderer.invoke('maker:hook-control:set-provider-default-workspace', { provider, alias }),// SIWS OIDC 绑定: 无参数; main 发 bind.start, server 回 pending + 授权链接- bindStart: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('maker:hook-control:bind-start', {}),- bindRevoke: (): Promise<{ ok: true }> =>- ipcRenderer.invoke('maker:hook-control:bind-revoke'),+ bindStart: (): Promise<{ ok: true }> => ipcRenderer.invoke('maker:hook-control:bind-start', {}),+ bindRevoke: (): Promise<{ ok: true }> => ipcRenderer.invoke('maker:hook-control:bind-revoke'),// (multi-team)多 workspace 绑定动作: 添加 / 重绑指定 team / 解绑指定 team /// 取消在途授权 —— server 宣告 multi-team 能力后才可用(renderer 按快照隐藏入口)addBinding: (): Promise<{ hook: unknown }> =>@@ -3800,8 +4054,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── session-git-pr-context: 会话分支感知 + PR 关联状态 ──gitContext: {/** 读 workdir 当前分支(非 git 目录返回 head=null)。 */- get: (workdir: string): Promise<unknown> =>- ipcRenderer.invoke('git-context:get', workdir),+ get: (workdir: string): Promise<unknown> => ipcRenderer.invoke('git-context:get', workdir),/** 按 session 解析「对话真实工作目录」+ HEAD + 来源(遥测/worktree/working_dir)。 */getForSession: (input: {sessionId: string;@@ -3809,16 +4062,13 @@ contextBridge.exposeInMainWorld('electronAPI', {worktreePath: string | null;}): Promise<unknown> => ipcRenderer.invoke('git-context:get-for-session', input),/** 开始监听该 workdir 的 HEAD 变化(refcount;变化经 onChanged 推送)。 */- watch: (workdir: string): Promise<void> =>- ipcRenderer.invoke('git-context:watch', workdir),- unwatch: (workdir: string): Promise<void> =>- ipcRenderer.invoke('git-context:unwatch', workdir),+ watch: (workdir: string): Promise<void> => ipcRenderer.invoke('git-context:watch', workdir),+ unwatch: (workdir: string): Promise<void> => ipcRenderer.invoke('git-context:unwatch', workdir),/** 某 session 关联的 PR 引用列表(lastSeenAt 降序)。 */listPrRefs: (sessionId: string): Promise<unknown> =>ipcRenderer.invoke('git-context:pr-refs:list', sessionId),/** 全部会话的 PR 引用(sidebar hover tips 启动期建缓存用)。 */- listAllPrRefs: (): Promise<unknown> =>- ipcRenderer.invoke('git-context:pr-refs:list-all'),+ listAllPrRefs: (): Promise<unknown> => ipcRenderer.invoke('git-context:pr-refs:list-all'),/** 批量查 PR 实时状态(main 侧 60s TTL 缓存;未配 PAT 返回 no-token)。 */getPrStatuses: (queries: Array<{ owner: string; repo: string; prNumber: number }>,@@ -3834,25 +4084,51 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('git-review:get', params),summary: (params: { sessionId: string }): Promise<ReviewDirtySummary> =>ipcRenderer.invoke('git-review:summary', params),- commits: (params: { sessionId: string; baseRef?: string | null }): Promise<ReviewCommitListData> =>- ipcRenderer.invoke('git-review:commits', params),- commitDiff: (params: { sessionId: string; oid: string; ignoreWhitespace?: boolean }): Promise<ReviewCommitDiffData> =>- ipcRenderer.invoke('git-review:commit-diff', params),- branchDiff: (params: { sessionId: string; baseRef?: string | null; ignoreWhitespace?: boolean }): Promise<ReviewBranchDiffData> =>- ipcRenderer.invoke('git-review:branch-diff', params),- fileDiff: (params: { sessionId: string } & ReviewFileDiffRequest): Promise<ReviewFileDiffData> =>- ipcRenderer.invoke('git-review:file-diff', params),- imagePreview: (params: { sessionId: string; diff: FileDiff; commitOid?: string | null; branchBaseRef?: string | null }): Promise<ReviewImagePreviewData> =>- ipcRenderer.invoke('git-review:image-preview', params),- markdownPreview: (params: { sessionId: string; diff: FileDiff; commitOid?: string | null; branchBaseRef?: string | null }): Promise<ReviewMarkdownPreviewData> =>+ commits: (params: {+ sessionId: string;+ baseRef?: string | null;+ }): Promise<ReviewCommitListData> => ipcRenderer.invoke('git-review:commits', params),+ commitDiff: (params: {+ sessionId: string;+ oid: string;+ ignoreWhitespace?: boolean;+ }): Promise<ReviewCommitDiffData> => ipcRenderer.invoke('git-review:commit-diff', params),+ branchDiff: (params: {+ sessionId: string;+ baseRef?: string | null;+ ignoreWhitespace?: boolean;+ }): Promise<ReviewBranchDiffData> => ipcRenderer.invoke('git-review:branch-diff', params),+ fileDiff: (+ params: { sessionId: string } & ReviewFileDiffRequest,+ ): Promise<ReviewFileDiffData> => ipcRenderer.invoke('git-review:file-diff', params),+ imagePreview: (params: {+ sessionId: string;+ diff: FileDiff;+ commitOid?: string | null;+ branchBaseRef?: string | null;+ }): Promise<ReviewImagePreviewData> => ipcRenderer.invoke('git-review:image-preview', params),+ markdownPreview: (params: {+ sessionId: string;+ diff: FileDiff;+ commitOid?: string | null;+ branchBaseRef?: string | null;+ }): Promise<ReviewMarkdownPreviewData> =>ipcRenderer.invoke('git-review:markdown-preview', params),openFile: (params: { sessionId: string; path: string }): Promise<void> =>ipcRenderer.invoke('git-review:open-file', params),- stageFile: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>- ipcRenderer.invoke('git-review:stage-file', params),- unstageFile: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>+ stageFile: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> => ipcRenderer.invoke('git-review:stage-file', params),+ unstageFile: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> =>ipcRenderer.invoke('git-review:unstage-file', params),- discardFile: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>+ discardFile: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> =>ipcRenderer.invoke('git-review:discard-file', params),stageHunk: (params: ReviewHunkOperationRequest): Promise<ReviewStageOperationResult> =>ipcRenderer.invoke('git-review:stage-hunk', params),@@ -3860,16 +4136,24 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('git-review:unstage-hunk', params),discardHunk: (params: ReviewHunkOperationRequest): Promise<ReviewStageOperationResult> =>ipcRenderer.invoke('git-review:discard-hunk', params),- stageAll: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>- ipcRenderer.invoke('git-review:stage-all', params),- unstageAll: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>- ipcRenderer.invoke('git-review:unstage-all', params),- discardAll: (params: { sessionId: string; targets: ReviewFileTarget[] }): Promise<ReviewStageOperationResult> =>- ipcRenderer.invoke('git-review:discard-all', params),+ stageAll: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> => ipcRenderer.invoke('git-review:stage-all', params),+ unstageAll: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> => ipcRenderer.invoke('git-review:unstage-all', params),+ discardAll: (params: {+ sessionId: string;+ targets: ReviewFileTarget[];+ }): Promise<ReviewStageOperationResult> => ipcRenderer.invoke('git-review:discard-all', params),commit: (params: ReviewCommitRequest): Promise<ReviewCommitResult> =>ipcRenderer.invoke('git-review:commit', params),- push: (params: { sessionId: string; confirmForce?: ReviewPushConfirmForce }): Promise<ReviewPushResult> =>- ipcRenderer.invoke('git-review:push', params),+ push: (params: {+ sessionId: string;+ confirmForce?: ReviewPushConfirmForce;+ }): Promise<ReviewPushResult> => ipcRenderer.invoke('git-review:push', params),},// sidebar 偏好(置顶手动顺序)走 main 进程 electron-store,跨 dev / installed 共享@@ -3911,20 +4195,10 @@ contextBridge.exposeInMainWorld('electronAPI', {remotePrecreatedWorktreeLedger: {list: (): Promise<RemotePrecreatedWorktreeLedgerSnapshot> =>ipcRenderer.invoke(REMOTE_PRECREATED_WORKTREE_LEDGER_CHANNELS.LIST),- register: (- record: PendingRemotePrecreatedWorktree,- ): Promise<{ persisted: boolean }> =>- ipcRenderer.invoke(- REMOTE_PRECREATED_WORKTREE_LEDGER_CHANNELS.REGISTER,- record,- ),- forget: (- target: PendingRemotePrecreatedWorktreeTarget,- ): Promise<{ persisted: boolean }> =>- ipcRenderer.invoke(- REMOTE_PRECREATED_WORKTREE_LEDGER_CHANNELS.FORGET,- target,- ),+ register: (record: PendingRemotePrecreatedWorktree): Promise<{ persisted: boolean }> =>+ ipcRenderer.invoke(REMOTE_PRECREATED_WORKTREE_LEDGER_CHANNELS.REGISTER, record),+ forget: (target: PendingRemotePrecreatedWorktreeTarget): Promise<{ persisted: boolean }> =>+ ipcRenderer.invoke(REMOTE_PRECREATED_WORKTREE_LEDGER_CHANNELS.FORGET, target),},// ── session 级"终身累计 cost"变化 (per-session, 不是 today-aggregate) ──@@ -3956,17 +4230,14 @@ contextBridge.exposeInMainWorld('electronAPI', {localDb: {ensureReady: (userId: string,- ): Promise<- | { ready: true }- | { ready: false; error: { code: string; message: string } }- > => ipcRenderer.invoke('local-db:ensure-ready', userId),+ ): Promise<{ ready: true } | { ready: false; error: { code: string; message: string } }> =>+ ipcRenderer.invoke('local-db:ensure-ready', userId),sessions: {list: (limit?: number, status?: string): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:list', limit, status),create: (body?: unknown): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:create', body),- get: (id: string): Promise<unknown> =>- ipcRenderer.invoke('local-db:sessions:get', id),+ get: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get', id),resolveReferences: (sessionIds: string[]): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:resolve-references', sessionIds),restoreIfArchived: (id: string, expected: unknown): Promise<unknown> =>@@ -4000,8 +4271,7 @@ contextBridge.exposeInMainWorld('electronAPI', {},recentWorkdirs: {/** 列出"最近工作目录"按 lastUsedAt desc;sessions 归档/删除不影响本表。 */- list: (): Promise<unknown> =>- ipcRenderer.invoke('local-db:recent-workdirs:list'),+ list: (): Promise<unknown> => ipcRenderer.invoke('local-db:recent-workdirs:list'),/** 从最近列表移除一条(列表卫生,不动 sessions / 磁盘;再次使用会重新入列)。 */remove: (input: { path: string }): Promise<unknown> =>ipcRenderer.invoke('local-db:recent-workdirs:remove', input),@@ -4019,8 +4289,7 @@ contextBridge.exposeInMainWorld('electronAPI', {kind: string;position: number;state?: unknown;- }): Promise<unknown> =>- ipcRenderer.invoke('local-db:right-sidebar-tabs:upsert', input),+ }): Promise<unknown> => ipcRenderer.invoke('local-db:right-sidebar-tabs:upsert', input),/** 删除单个 tab(不删 active flag,setActive 负责切换激活态)。 */close: (input: { id: string }): Promise<unknown> =>ipcRenderer.invoke('local-db:right-sidebar-tabs:close', input),@@ -4032,8 +4301,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('local-db:right-sidebar-tabs:reorder', input),},projectAliases: {- list: (): Promise<unknown> =>- ipcRenderer.invoke('local-db:project-aliases:list'),+ list: (): Promise<unknown> => ipcRenderer.invoke('local-db:project-aliases:list'),set: (input: { projectKey: string; alias: string }): Promise<unknown> =>ipcRenderer.invoke('local-db:project-aliases:set', input),delete: (projectKey: string): Promise<void> =>@@ -4043,8 +4311,9 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionImport: {scan: (request?: { force?: boolean }): Promise<unknown> =>ipcRenderer.invoke('local-db:session-import:scan', request),- importSelected: (items: Array<{ source: 'codex' | 'claude'; id: string }>): Promise<unknown> =>- ipcRenderer.invoke('local-db:session-import:import', { items }),+ importSelected: (+ items: Array<{ source: 'codex' | 'claude'; id: string }>,+ ): Promise<unknown> => ipcRenderer.invoke('local-db:session-import:import', { items }),linkCodexProject: (workingDir: string): Promise<unknown> =>ipcRenderer.invoke('local-db:session-import:link-codex-project', { workingDir }),},@@ -4089,27 +4358,24 @@ contextBridge.exposeInMainWorld('electronAPI', {getByLeadSession: (leadSessionId: string): Promise<unknown> =>ipcRenderer.invoke('local-db:orca-workflows:get-by-lead', leadSessionId),getByWorkerSession: (workerSessionId: string): Promise<unknown> =>- ipcRenderer.invoke(- 'local-db:orca-workflows:get-by-worker-session',- workerSessionId,- ),+ ipcRenderer.invoke('local-db:orca-workflows:get-by-worker-session', workerSessionId),listWorkersByLead: (leadSessionId: string): Promise<unknown> =>ipcRenderer.invoke('local-db:orca-workflows:list-workers-by-lead', leadSessionId),listWorkersByLeads: (leadSessionIds: string[]): Promise<unknown> =>ipcRenderer.invoke('local-db:orca-workflows:list-workers-by-leads', leadSessionIds),updateWorkerStatus: (workerId: string, status: string): Promise<void> =>- ipcRenderer.invoke(- 'local-db:orca-workflows:update-worker-status',- workerId,- status,- ),+ ipcRenderer.invoke('local-db:orca-workflows:update-worker-status', workerId, status),onOrcaWorkerChanged: (cb: (payload: unknown) => void) =>fanOutOrcaWorkerChanged(cb as IpcCallback),createWorker: (input: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('maker:worker:create', input),switchFocus: (input: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('maker:worker:switch-focus', input),- idleWorker: (leadSessionId: string, workerId: string, expectedStatus?: 'done'): Promise<unknown> => {+ idleWorker: (+ leadSessionId: string,+ workerId: string,+ expectedStatus?: 'done',+ ): Promise<unknown> => {if (expectedStatus === 'done') {return ipcRenderer.invoke('maker:worker:acknowledge-done', { leadSessionId, workerId });}@@ -4134,11 +4400,8 @@ contextBridge.exposeInMainWorld('electronAPI', {list: (sessionId: string,opts?: { limit?: number; before?: string; beforeTs?: number },- ): Promise<unknown> =>- ipcRenderer.invoke('local-db:messages:list', sessionId, opts),- estimatedSessionValue: (- sessionId: string,- ): Promise<unknown> =>+ ): Promise<unknown> => ipcRenderer.invoke('local-db:messages:list', sessionId, opts),+ estimatedSessionValue: (sessionId: string): Promise<unknown> =>ipcRenderer.invoke('local-db:messages:estimatedSessionValue', sessionId),around: (sessionId: string,@@ -4154,17 +4417,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('local-db:messages:around-client-id', sessionId, clientId, opts),create: (sessionId: string, body: unknown): Promise<unknown> =>ipcRenderer.invoke('local-db:messages:create', sessionId, body),- updateContent: (- sessionId: string,- clientId: string,- content: unknown,- ): Promise<unknown> =>- ipcRenderer.invoke(- 'local-db:messages:updateContent',- sessionId,- clientId,- content,- ),+ updateContent: (sessionId: string, clientId: string, content: unknown): Promise<unknown> =>+ ipcRenderer.invoke('local-db:messages:updateContent', sessionId, clientId, content),/** error-tail-banner:忽略错误行(main 侧 merge dismissed:true,保留原字段)。 */dismissError: (sessionId: string, clientId: string): Promise<unknown> =>ipcRenderer.invoke('local-db:messages:dismiss-error', sessionId, clientId),@@ -4214,9 +4468,7 @@ contextBridge.exposeInMainWorld('electronAPI', {captureScreenshot: (input: { tabId: string }): Promise<unknown> =>ipcRenderer.invoke('rsb-browser-bridge:capture-screenshot', input),/** 页面评论:main 端 capturePage 后把 PNG 字节返回(不写剪贴板)。 */- captureScreenshotData: (input: {- tabId: string;- }): Promise<{ ok: true; data: Uint8Array }> =>+ captureScreenshotData: (input: { tabId: string }): Promise<{ ok: true; data: Uint8Array }> =>ipcRenderer.invoke('rsb-browser-bridge:capture-screenshot-data', input),onPin: (cb: (payload: { tabId: string }) => void) =>fanOutRsbBrowserBridgePin(cb as IpcCallback),@@ -4320,8 +4572,7 @@ contextBridge.exposeInMainWorld('electronAPI', {ownerGeneration: number;providers: import('@cindy/model-providers').ProviderView[];providerOrder: string[];- }> =>- ipcRenderer.invoke('maker:provider:list'),+ }> => ipcRenderer.invoke('maker:provider:list'),/** Refresh one built-in provider through its existing main-process discovery source. */refreshBuiltinProviderModels: (providerId: import('../shared/providerModelRefresh').BuiltinRefreshableProviderId,@@ -4337,8 +4588,7 @@ contextBridge.exposeInMainWorld('electronAPI', {createCustomProvider: (config: import('@cindy/model-providers').CustomProviderConfig,keys: Partial<Record<'claude-code' | 'codex' | 'pi', string>>,- ): Promise<{ ok: true }> =>- ipcRenderer.invoke('maker:provider:custom:create', config, keys),+ ): Promise<{ ok: true }> => ipcRenderer.invoke('maker:provider:custom:create', config, keys),updateCustomProvider: (config: import('@cindy/model-providers').CustomProviderConfig,keys: Partial<Record<'claude-code' | 'codex' | 'pi', string>>,@@ -4346,8 +4596,9 @@ contextBridge.exposeInMainWorld('electronAPI', {deleteCustomProvider: (providerId: string): Promise<{ ok: true }> =>ipcRenderer.invoke('maker:provider:custom:delete', providerId),/** 自定义供应商创建模板(目录 presets 段,纯 UI 模板数据)。 */- listProviderPresets: (): Promise<{ presets: import('@cindy/model-providers').ProviderPreset[] }> =>- ipcRenderer.invoke('maker:provider:presets'),+ listProviderPresets: (): Promise<{+ presets: import('@cindy/model-providers').ProviderPreset[];+ }> => ipcRenderer.invoke('maker:provider:presets'),/*** 供应商「测试连接」—— 与真实会话同路由口径的最小探测请求。* saved: 已保存供应商(key main 侧从 safeStorage 读);adhoc: 表单未保存值(key 仅内存透传)。@@ -4458,8 +4709,9 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 会话仍在运行的后台任务快照(挂载 / 重载后补回存量;实时增量走事件流)。 */listSessionBackgroundTasks: (sessionId: string,- ): Promise<{ tasks: Array<{ taskId: string; taskType?: string; toolUseId?: string; title?: string }> }> =>- ipcRenderer.invoke('maker:session-background-tasks:list', sessionId),+ ): Promise<{+ tasks: Array<{ taskId: string; taskType?: string; toolUseId?: string; title?: string }>;+ }> => ipcRenderer.invoke('maker:session-background-tasks:list', sessionId),/** 通用 OAuth 供应商(目录 auth.oauth 描述符驱动)登录 / 登出 / 取消。 */providerOAuthLogin: (providerId: string,@@ -4606,7 +4858,11 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string;objective: string;/** GUI 新建弹窗高级设置;缺省 → 走系统默认上限。 */- limits?: { maxTurns: number | null; budgetTokens: number | null; noProgressLimit: number | null };+ limits?: {+ maxTurns: number | null;+ budgetTokens: number | null;+ noProgressLimit: number | null;+ };}): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:goal:set', input),/** 用户清除会话目标(GoalIndicator ✕)。 */clearGoal: (sessionId: string): Promise<{ ok: boolean }> =>@@ -4620,9 +4876,13 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 更新当前目标的目标文本 / 上限;不写全局默认。 */updateGoal: (sessionId: string,- patch: { objective?: string; maxTurns?: number | null; budgetTokens?: number | null; noProgressLimit?: number | null },- ): Promise<{ ok: boolean }> =>- ipcRenderer.invoke('maker:goal:update', { sessionId, patch }),+ patch: {+ objective?: string;+ maxTurns?: number | null;+ budgetTokens?: number | null;+ noProgressLimit?: number | null;+ },+ ): Promise<{ ok: boolean }> => ipcRenderer.invoke('maker:goal:update', { sessionId, patch }),/** 取会话当前 goal 扁平状态;无 goal 返回 null。 */getGoalStatus: (sessionId: string,@@ -4707,8 +4967,13 @@ contextBridge.exposeInMainWorld('electronAPI', {*/remoteHostId?: string;vendorOptions?: Record<string, unknown>;- }): Promise<{ sessionId: string; agentKind: string; workDir: string; capabilities: unknown; usedProjectContext?: boolean }> =>- ipcRenderer.invoke('maker:create-session', opts),+ }): Promise<{+ sessionId: string;+ agentKind: string;+ workDir: string;+ capabilities: unknown;+ usedProjectContext?: boolean;+ }> => ipcRenderer.invoke('maker:create-session', opts),markOrcaRole: (sessionId: string, role: 'lead' | 'worker'): Promise<void> =>ipcRenderer.invoke('maker:mark-orca-role', sessionId, role),@@ -4751,7 +5016,8 @@ contextBridge.exposeInMainWorld('electronAPI', {*/send: (sessionId: string,- message: string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },+ message:+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },createOpts?: {agentKind: 'claude-code' | 'codex' | 'pi';workingDir: string;@@ -4785,7 +5051,8 @@ contextBridge.exposeInMainWorld('electronAPI', {steer: (sessionId: string,- message: string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },+ message:+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },sendOpts?: {/** 这条消息的 SDK uuid (renderer 与 messages.agent_meta.uuid 同源, rewind 锚点)。 */messageUuid?: string;@@ -4832,13 +5099,15 @@ contextBridge.exposeInMainWorld('electronAPI', {): Promise<{ sessionId: string; clientId: string; clientIds: string[] }> =>ipcRenderer.invoke('maker:message:delete', sessionId, clientId),- listActive: (): Promise<Array<{- sessionId: string;- agentKind: 'claude-code' | 'codex' | 'pi';- workDir: string;- capabilities: unknown;- isTurnRunning: boolean;- }>> => ipcRenderer.invoke('maker:list-active'),+ listActive: (): Promise<+ Array<{+ sessionId: string;+ agentKind: 'claude-code' | 'codex' | 'pi';+ workDir: string;+ capabilities: unknown;+ isTurnRunning: boolean;+ }>+ > => ipcRenderer.invoke('maker:list-active'),resolveInteraction: (requestId: string,@@ -4858,8 +5127,12 @@ contextBridge.exposeInMainWorld('electronAPI', {// —— pending 状态原本只由实时 INTERACTION_REQUEST push 设置,后加入的窗口靠它补回。getPendingInteractions: (sessionId: string,- ): Promise<Array<{ request: { kind: string; requestId: string; [k: string]: unknown }; persistId?: string }>> =>- ipcRenderer.invoke('maker:get-pending-interactions', sessionId),+ ): Promise<+ Array<{+ request: { kind: string; requestId: string; [k: string]: unknown };+ persistId?: string;+ }>+ > => ipcRenderer.invoke('maker:get-pending-interactions', sessionId),// ── 运行时切换 (Stage 2 B) ─────────────────────────────────────────────// session 不存在(没 send 过/已 close)时 main 侧 no-op,renderer 可乐观调用。@@ -4896,8 +5169,24 @@ contextBridge.exposeInMainWorld('electronAPI', {providerId?: string | null,effort?: string,fastMode?: boolean,- ): Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex' | 'pi'; model: string; engineReady: boolean; deferred?: boolean; sameEngineRevision?: number; sameEngineSuperseded?: boolean }> =>- ipcRenderer.invoke('maker:switch-session-agent', sessionId, targetAgentKind, model, providerId, effort, fastMode),+ ): Promise<{+ switched: boolean;+ agentKind: 'claude-code' | 'codex' | 'pi';+ model: string;+ engineReady: boolean;+ deferred?: boolean;+ sameEngineRevision?: number;+ sameEngineSuperseded?: boolean;+ }> =>+ ipcRenderer.invoke(+ 'maker:switch-session-agent',+ sessionId,+ targetAgentKind,+ model,+ providerId,+ effort,+ fastMode,+ ),// 读 main 权威的 pending 切换意图(内存态,不落库)。重开视图 / 远程会话重连后// 用它恢复乐观显示——否则用户登记的意图在 UI 上凭空消失,下一条消息却按意图切换。getSessionAgentSwitchIntent: (@@ -4932,8 +5221,7 @@ contextBridge.exposeInMainWorld('electronAPI', {instructions?: string,): Promise<{ tokensBefore?: number; estimatedTokensAfter?: number; noop?: boolean } | null> =>ipcRenderer.invoke('maker:compact-session', sessionId, instructions),- getSessionTree: (sessionId: string) =>- ipcRenderer.invoke('maker:get-session-tree', sessionId),+ getSessionTree: (sessionId: string) => ipcRenderer.invoke('maker:get-session-tree', sessionId),navigateSessionTree: (sessionId: string,entryId: string,@@ -4947,7 +5235,9 @@ contextBridge.exposeInMainWorld('electronAPI', {// Memory 控制 (Personalization → Memory section)。// 由 BaseAgent 子类落地; UI 层负责 Reset 前 confirm dialog。- memoryGet: (agentKind: 'claude-code' | 'codex' | 'pi'): Promise<{+ memoryGet: (+ agentKind: 'claude-code' | 'codex' | 'pi',+ ): Promise<{enabled: boolean;source: 'agent-default' | 'host-runtime' | 'user-config';stats?: { entryCount?: number; sizeBytes?: number; storagePath?: string };@@ -4960,9 +5250,10 @@ contextBridge.exposeInMainWorld('electronAPI', {isCustomized: boolean;customizedKeys: string[];defaults: { maker: boolean; claudeCode: boolean; codex: boolean; pi: boolean };- }> =>- ipcRenderer.invoke('maker:memory:set', agentKind, enabled),- memoryReset: (agentKind: 'claude-code' | 'codex' | 'pi'): Promise<{+ }> => ipcRenderer.invoke('maker:memory:set', agentKind, enabled),+ memoryReset: (+ agentKind: 'claude-code' | 'codex' | 'pi',+ ): Promise<{removedEntries?: number;removedBytes?: number;}> => ipcRenderer.invoke('maker:memory:reset', agentKind),@@ -4974,14 +5265,15 @@ contextBridge.exposeInMainWorld('electronAPI', {* codexRestartDeferred: true = 本地 Codex 会话正忙, 存活会话的软重启延迟到* 任务结束后自动补做 (设置本身已生效, UI 据此提示生效时机)。*/- makerMemorySetEnabled: (enabled: boolean): Promise<{+ makerMemorySetEnabled: (+ enabled: boolean,+ ): Promise<{effective: 'next-session';isCustomized: boolean;customizedKeys: string[];defaults: { maker: boolean; claudeCode: boolean; codex: boolean; pi: boolean };codexRestartDeferred: boolean;- }> =>- ipcRenderer.invoke('maker:maker-memory:set-enabled', enabled),+ }> => ipcRenderer.invoke('maker:maker-memory:set-enabled', enabled),/** Maker Memory 整库重置: 删 <userData>/maker-memory/ 全部 workdir 目录 + close db pool */makerMemoryReset: (): Promise<{ removedCount: number }> =>@@ -4991,8 +5283,12 @@ contextBridge.exposeInMainWorld('electronAPI', {* 启动期同步三个 memory 开关的真实持久化值 (main <userData>/memory-settings.json)。* renderer localStorage 只是 UI 即时态镜像 — 启动时调一次, main 是 source of truth。*/- memoryGetSettings: (): Promise<{ maker: boolean; claudeCode: boolean; codex: boolean; pi: boolean }> =>- ipcRenderer.invoke('maker:memory:get-settings'),+ memoryGetSettings: (): Promise<{+ maker: boolean;+ claudeCode: boolean;+ codex: boolean;+ pi: boolean;+ }> => ipcRenderer.invoke('maker:memory:get-settings'),memoryGetSettingsState: (): Promise<{maker: boolean;claudeCode: boolean;@@ -5001,16 +5297,16 @@ contextBridge.exposeInMainWorld('electronAPI', {isCustomized: boolean;customizedKeys: string[];defaults: { maker: boolean; claudeCode: boolean; codex: boolean; pi: boolean };- }> =>- ipcRenderer.invoke('maker:memory:get-settings-state'),+ }> => ipcRenderer.invoke('maker:memory:get-settings-state'),/** 启动期迁移旧版 renderer/native memory opt-out;null 表示 renderer marker 缺失。 */- memoryPreserveLegacyMakerDisabled: (legacyRendererValue: boolean | null): Promise<{+ memoryPreserveLegacyMakerDisabled: (+ legacyRendererValue: boolean | null,+ ): Promise<{maker: boolean;claudeCode: boolean;codex: boolean;pi: boolean;- }> =>- ipcRenderer.invoke('maker:memory:preserve-legacy-maker-disabled', legacyRendererValue),+ }> => ipcRenderer.invoke('maker:memory:preserve-legacy-maker-disabled', legacyRendererValue),memoryResetSettings: (): Promise<{maker: boolean;claudeCode: boolean;@@ -5020,8 +5316,7 @@ contextBridge.exposeInMainWorld('electronAPI', {customizedKeys: string[];defaults: { maker: boolean; claudeCode: boolean; codex: boolean; pi: boolean };codexRestartDeferred: boolean;- }> =>- ipcRenderer.invoke('maker:memory:reset-settings'),+ }> => ipcRenderer.invoke('maker:memory:reset-settings'),/** IM 新会话默认 agent/model/effort/provider。传 channel 时按渠道独立读写。 */imDefaultSettingsGet: (channel?: ImDefaultSettingsChannel): Promise<ImDefaultSettingsState> =>@@ -5058,38 +5353,59 @@ contextBridge.exposeInMainWorld('electronAPI', {agentResourceSettingsReset: (): Promise<unknown> =>ipcRenderer.invoke('maker:agent-resource-settings:reset'),- silentEncryptedRetryGet: (): Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }> =>- ipcRenderer.invoke('maker:silent-encrypted-retry:get'),- silentEncryptedRetrySet: (enabled: boolean): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean; effective: 'immediate' }> =>- ipcRenderer.invoke('maker:silent-encrypted-retry:set', enabled),- silentEncryptedRetryReset: (): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean; effective: 'immediate' }> =>- ipcRenderer.invoke('maker:silent-encrypted-retry:reset'),+ silentEncryptedRetryGet: (): Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }> => ipcRenderer.invoke('maker:silent-encrypted-retry:get'),+ silentEncryptedRetrySet: (+ enabled: boolean,+ ): Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }> => ipcRenderer.invoke('maker:silent-encrypted-retry:set', enabled),+ silentEncryptedRetryReset: (): Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }> => ipcRenderer.invoke('maker:silent-encrypted-retry:reset'),// Claude Code 自动上下文压缩阈值。仅对新建会话生效。- compactionGetPct: (): Promise<number> =>- ipcRenderer.invoke('maker:compaction:get-pct'),+ compactionGetPct: (): Promise<number> => ipcRenderer.invoke('maker:compaction:get-pct'),compactionGetState: (): Promise<{ pct: number; isCustomized: boolean; defaultPct: number }> =>ipcRenderer.invoke('maker:compaction:get-state'),- compactionSetPct: (pct: number): Promise<{ pct: number; isCustomized: boolean; defaultPct: number }> =>+ compactionSetPct: (+ pct: number,+ ): Promise<{ pct: number; isCustomized: boolean; defaultPct: number }> =>ipcRenderer.invoke('maker:compaction:set-pct', pct),compactionResetPct: (): Promise<{ pct: number; isCustomized: boolean; defaultPct: number }> =>ipcRenderer.invoke('maker:compaction:reset-pct'),// LSP Beta 开关 —— 控制 mcp providers 是否注入 lsp_* 工具 (Phase 1 Beta)。// 默认 false; 仅对**新 session** 生效, 已开 session 工具列表已固化, 不变。- lspModeGet: (): Promise<{ enabled: boolean }> =>- ipcRenderer.invoke('maker:lsp-mode:get'),+ lspModeGet: (): Promise<{ enabled: boolean }> => ipcRenderer.invoke('maker:lsp-mode:get'),lspModeSet: (enabled: boolean): Promise<{ effective: 'next-session' }> =>ipcRenderer.invoke('maker:lsp-mode:set', enabled),// 聊天嵌入开关 —— 控制 chat-history-embedder 是否对新消息入队嵌入。// 默认 false; 关闭状态下零成本 (createMessage hook 在 enabled 守卫处直接 return)。- chatEmbeddingGet: (): Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }> =>- ipcRenderer.invoke('maker:chat-embedding:get'),- chatEmbeddingSet: (enabled: boolean): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }> =>+ chatEmbeddingGet: (): Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }> => ipcRenderer.invoke('maker:chat-embedding:get'),+ chatEmbeddingSet: (+ enabled: boolean,+ ): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }> =>ipcRenderer.invoke('maker:chat-embedding:set', enabled),- chatEmbeddingReset: (): Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }> =>- ipcRenderer.invoke('maker:chat-embedding:reset'),+ chatEmbeddingReset: (): Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ }> => ipcRenderer.invoke('maker:chat-embedding:reset'),// Git safety workflow —— 控制 turn end 自动 XDT snapshot commit。// 默认 false; Codex rewind 按钮跟随该开关显示。@@ -5098,7 +5414,9 @@ contextBridge.exposeInMainWorld('electronAPI', {isCustomized: boolean;defaultAutoSnapshotEnabled: boolean;}> => ipcRenderer.invoke('maker:git-safety:get'),- gitSafetySet: (enabled: boolean): Promise<{+ gitSafetySet: (+ enabled: boolean,+ ): Promise<{autoSnapshotEnabled: boolean;isCustomized: boolean;defaultAutoSnapshotEnabled: boolean;@@ -5119,18 +5437,18 @@ contextBridge.exposeInMainWorld('electronAPI', {// codexMcpRefreshed:false = 开关已落盘但 Codex 失效失败(会话正忙), 对 Codex 延迟生效settingsSet: (enabled: boolean): Promise<{ enabled: boolean; codexMcpRefreshed?: boolean }> =>ipcRenderer.invoke('maker:contacts:settings:set', enabled),- syncStatusGet: (): Promise<unknown> =>- ipcRenderer.invoke('maker:contacts:sync:status:get'),+ syncStatusGet: (): Promise<unknown> => ipcRenderer.invoke('maker:contacts:sync:status:get'),syncEnabledSet: (enabled: boolean): Promise<unknown> =>ipcRenderer.invoke('maker:contacts:sync:enabled:set', enabled),- syncNow: (): Promise<unknown> =>- ipcRenderer.invoke('maker:contacts:sync:now'),+ syncNow: (): Promise<unknown> => ipcRenderer.invoke('maker:contacts:sync:now'),list: (opts?: unknown): Promise<unknown[]> => ipcRenderer.invoke('maker:contacts:list', opts),get: (id: string): Promise<unknown> => ipcRenderer.invoke('maker:contacts:get', id),- create: (input: unknown): Promise<unknown> => ipcRenderer.invoke('maker:contacts:create', input),+ create: (input: unknown): Promise<unknown> =>+ ipcRenderer.invoke('maker:contacts:create', input),update: (id: string, patch: unknown): Promise<unknown> =>ipcRenderer.invoke('maker:contacts:update', id, patch),- delete: (id: string): Promise<{ deleted: boolean }> => ipcRenderer.invoke('maker:contacts:delete', id),+ delete: (id: string): Promise<{ deleted: boolean }> =>+ ipcRenderer.invoke('maker:contacts:delete', id),merge: (targetId: string, sourceId: string): Promise<unknown> =>ipcRenderer.invoke('maker:contacts:merge', targetId, sourceId),resolve: (value: string, opts?: unknown): Promise<unknown[]> =>@@ -5163,9 +5481,11 @@ contextBridge.exposeInMainWorld('electronAPI', {payload: { add?: string[]; remove?: string[] },): Promise<{ added: number; removed: number }> =>ipcRenderer.invoke('maker:contacts:groups:set-members', groupId, payload),- resetAll: (): Promise<{ removedCount: number }> => ipcRenderer.invoke('maker:contacts:reset-all'),+ resetAll: (): Promise<{ removedCount: number }> =>+ ipcRenderer.invoke('maker:contacts:reset-all'),systemRead: (): Promise<unknown[]> => ipcRenderer.invoke('maker:contacts:system-read'),- parseVcf: (text: string): Promise<unknown[]> => ipcRenderer.invoke('maker:contacts:parse-vcf', text),+ parseVcf: (text: string): Promise<unknown[]> =>+ ipcRenderer.invoke('maker:contacts:parse-vcf', text),import: (records: unknown[], opts?: { groupId?: string }): Promise<unknown> =>ipcRenderer.invoke('maker:contacts:import', records, opts),onChanged: createIpcFanOut('maker:contacts:changed'),@@ -5228,68 +5548,116 @@ contextBridge.exposeInMainWorld('electronAPI', {},input: {- getProjection: (sessionId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ getProjection: (+ sessionId: string,+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:get-projection', sessionId),enqueue: (sessionId: string,item: import('../shared/agentInputQueue').AgentInputQueuedMessage,- opts?: { sendAtMs?: number },+ opts?: { sendAtMs?: number; expectedClearBoundaryMs?: number | null },): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:enqueue', sessionId, item, opts),compact: (sessionId: string,createOpts: import('../shared/agentInputQueue').AgentInputCreateOpts,- opts?: { userName?: string },+ opts?: { userName?: string; expectedClearBoundaryMs?: number | null },): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:compact', sessionId, createOpts, opts),steer: (sessionId: string,item: import('../shared/agentInputQueue').AgentInputQueuedMessage,- opts?: { removeFromQueue?: boolean; touchUserSend?: boolean },- ): Promise<boolean> =>- ipcRenderer.invoke('maker:input:steer', sessionId, item, opts),+ opts?: {+ removeFromQueue?: boolean;+ touchUserSend?: boolean;+ expectedClearBoundaryMs?: number | null;+ },+ ): Promise<boolean> => ipcRenderer.invoke('maker:input:steer', sessionId, item, opts),stop: (sessionId: string,- opts?: { keepQueue?: boolean; pauseQueue?: boolean },+ opts?: {+ keepQueue?: boolean;+ pauseQueue?: boolean;+ expectedClearBoundaryMs?: number | null;+ },): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>ipcRenderer.invoke('maker:input:stop', sessionId, opts),- resume: (sessionId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>- ipcRenderer.invoke('maker:input:resume', sessionId),- retryLastError: (sessionId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>- ipcRenderer.invoke('maker:input:retry-last-error', sessionId),- clearError: (sessionId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>- ipcRenderer.invoke('maker:input:clear-error', sessionId),- persistTurnErrorDeferred: (sessionId: string, errData: Record<string, unknown> | null, agentMeta?: import('../renderer/lib/ccAgent.types').AgentMeta | null): Promise<void> =>- ipcRenderer.invoke('maker:persist-turn-error-deferred', sessionId, errData, agentMeta ?? null),- remove: (sessionId: string, clientId: string): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>- ipcRenderer.invoke('maker:input:remove', sessionId, clientId),+ resume: (+ sessionId: string,+ opts?: { expectedClearBoundaryMs?: number | null },+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ ipcRenderer.invoke('maker:input:resume', sessionId, opts),+ retryLastError: (+ sessionId: string,+ opts?: { expectedClearBoundaryMs?: number | null },+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ ipcRenderer.invoke('maker:input:retry-last-error', sessionId, opts),+ clearError: (+ sessionId: string,+ opts?: { expectedClearBoundaryMs?: number | null },+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ ipcRenderer.invoke('maker:input:clear-error', sessionId, opts),+ persistTurnErrorDeferred: (+ sessionId: string,+ errData: Record<string, unknown> | null,+ agentMeta?: import('../renderer/lib/ccAgent.types').AgentMeta | null,+ ): Promise<void> =>+ ipcRenderer.invoke(+ 'maker:persist-turn-error-deferred',+ sessionId,+ errData,+ agentMeta ?? null,+ ),+ remove: (+ sessionId: string,+ clientId: string,+ opts?: { expectedClearBoundaryMs?: number | null },+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ ipcRenderer.invoke('maker:input:remove', sessionId, clientId, opts),updateText: (sessionId: string,clientId: string,newText: string,sessionRefs?: import('../shared/agentInputQueue').AgentInputSessionRef[],+ trustedContexts?: import('../shared/agentInputQueue').AgentInputSessionReferenceContext[],+ opts?: { expectedClearBoundaryMs?: number | null },): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>- ipcRenderer.invoke('maker:input:update-text', sessionId, clientId, newText, sessionRefs),+ ipcRenderer.invoke(+ 'maker:input:update-text',+ sessionId,+ clientId,+ newText,+ sessionRefs,+ trustedContexts,+ opts,+ ),move: (sessionId: string,clientId: string,targetIndex: number,+ opts?: { expectedClearBoundaryMs?: number | null },+ ): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>+ ipcRenderer.invoke('maker:input:move', sessionId, clientId, targetIndex, opts),+ setExpanded: (+ sessionId: string,+ expanded: boolean,+ opts?: { expectedClearBoundaryMs?: number | null },): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>- ipcRenderer.invoke('maker:input:move', sessionId, clientId, targetIndex),- setExpanded: (sessionId: string, expanded: boolean): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>- ipcRenderer.invoke('maker:input:set-expanded', sessionId, expanded),+ ipcRenderer.invoke('maker:input:set-expanded', sessionId, expanded, opts),setInteractionLock: (sessionId: string,lockId: string,locked: boolean,+ opts?: { expectedClearBoundaryMs?: number | null },): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>- ipcRenderer.invoke('maker:input:set-interaction-lock', sessionId, lockId, locked),+ ipcRenderer.invoke('maker:input:set-interaction-lock', sessionId, lockId, locked, opts),setEditLock: (sessionId: string,clientId: string,locked: boolean,+ opts?: { expectedClearBoundaryMs?: number | null },): Promise<import('../shared/agentInputQueue').AgentInputProjection> =>- ipcRenderer.invoke('maker:input:set-edit-lock', sessionId, clientId, locked),+ ipcRenderer.invoke('maker:input:set-edit-lock', sessionId, clientId, locked, opts),clearSession: (sessionId: string,clearedAt?: string,@@ -5298,7 +5666,11 @@ contextBridge.exposeInMainWorld('electronAPI', {},// Stage 2 C1: chat utility (前身 cc-agent:generate-title / cc-agent:plan-file-write)- generateTitle: (message: string, agentKind: 'claude-code' | 'codex' | 'pi', sessionId?: string): Promise<{ title: string | null }> =>+ generateTitle: (+ message: string,+ agentKind: 'claude-code' | 'codex' | 'pi',+ sessionId?: string,+ ): Promise<{ title: string | null }> =>ipcRenderer.invoke('maker:generate-title', { message, agentKind, sessionId }),// 重命名输入框 Magic 按钮:按会话最新对话内容重新生成标题(素材由 main 读 DB)regenerateSessionTitle: (sessionId: string): Promise<{ title: string | null }> =>@@ -5323,9 +5695,9 @@ contextBridge.exposeInMainWorld('electronAPI', {getMyIssuesSnapshot: (): Promise<import('../shared/myIssues').MyIssuesSnapshot | null> =>ipcRenderer.invoke('maker:issues:snapshot-mine'),// /issues 页面的「我的 Issue」列表;force=true 绕过 main 侧 60s TTL(手动刷新)。- listMyIssues: (- options?: { force?: boolean },- ): Promise<+ listMyIssues: (options?: {+ force?: boolean;+ }): Promise<| ({ success: true } & import('../shared/myIssues').MyIssuesResult)| {success: false;@@ -5360,8 +5732,7 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string,clientId: string,opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean },- ): Promise<unknown> =>- ipcRenderer.invoke('maker:rewind:commit', sessionId, clientId, opts),+ ): Promise<unknown> => ipcRenderer.invoke('maker:rewind:commit', sessionId, clientId, opts),fork: (sourceSessionId: string, messageClientId: string): Promise<unknown> =>ipcRenderer.invoke('maker:fork', sourceSessionId, messageClientId),forkStripEncrypted: (sourceSessionId: string): Promise<unknown> =>@@ -5374,13 +5745,11 @@ contextBridge.exposeInMainWorld('electronAPI', {triggerLogin: (agentKind: 'claude-code' | 'codex' | 'pi',options?: { mode?: 'browser' | 'device-code'; ownerId?: string },- ): Promise<unknown> =>- ipcRenderer.invoke('maker:auth:trigger-login', agentKind, options),+ ): Promise<unknown> => ipcRenderer.invoke('maker:auth:trigger-login', agentKind, options),cancelLogin: (agentKind: 'claude-code' | 'codex' | 'pi',options?: { releaseOwner?: boolean; ownerId?: string },- ): Promise<void> =>- ipcRenderer.invoke('maker:auth:cancel-login', agentKind, options),+ ): Promise<void> => ipcRenderer.invoke('maker:auth:cancel-login', agentKind, options),logout: (agentKind: 'claude-code' | 'codex' | 'pi'): Promise<void> =>ipcRenderer.invoke('maker:auth:logout', agentKind),onStateChanged: fanOutMakerAuthStateChanged,@@ -5392,7 +5761,9 @@ contextBridge.exposeInMainWorld('electronAPI', {getStatus: (agentKind: 'claude-code' | 'codex' | 'pi'): Promise<unknown> =>ipcRenderer.invoke('maker:agent:status', agentKind),/** spawn 当前应用使用的 binary `--version`, 进程内缓存。About 面板用。 */- getBinaryVersion: (agentKind: 'claude-code' | 'codex' | 'pi'): Promise<{+ getBinaryVersion: (+ agentKind: 'claude-code' | 'codex' | 'pi',+ ): Promise<{kind: 'claude-code' | 'codex' | 'pi';binaryPath: string | null;version: string | null;@@ -5444,31 +5815,29 @@ contextBridge.exposeInMainWorld('electronAPI', {schedule: {list: (filter?: { status?: 'active' | 'paused' | 'expired' }): Promise<unknown[]> =>ipcRenderer.invoke('maker:schedule:list', filter),- listTemplates: (): Promise<unknown[]> =>- ipcRenderer.invoke('maker:schedule:list-templates'),+ listTemplates: (): Promise<unknown[]> => ipcRenderer.invoke('maker:schedule:list-templates'),createFromTemplate: (params: {templateId: string;paramValues?: Record<string, string>;overrides?: unknown;- }): Promise<unknown> =>- ipcRenderer.invoke('maker:schedule:create-from-template', params),- get: (id: string): Promise<unknown | null> =>- ipcRenderer.invoke('maker:schedule:get', id),+ }): Promise<unknown> => ipcRenderer.invoke('maker:schedule:create-from-template', params),+ get: (id: string): Promise<unknown | null> => ipcRenderer.invoke('maker:schedule:get', id),create: (input: unknown): Promise<unknown> =>ipcRenderer.invoke('maker:schedule:create', input),update: (id: string, patch: unknown): Promise<unknown> =>ipcRenderer.invoke('maker:schedule:update', id, patch),- delete: (id: string): Promise<void> =>- ipcRenderer.invoke('maker:schedule:delete', id),- pause: (id: string): Promise<unknown> =>- ipcRenderer.invoke('maker:schedule:pause', id),- resume: (id: string): Promise<unknown> =>- ipcRenderer.invoke('maker:schedule:resume', id),+ delete: (id: string): Promise<void> => ipcRenderer.invoke('maker:schedule:delete', id),+ pause: (id: string): Promise<unknown> => ipcRenderer.invoke('maker:schedule:pause', id),+ resume: (id: string): Promise<unknown> => ipcRenderer.invoke('maker:schedule:resume', id),runNow: (id: string): Promise<{ runId: string }> =>ipcRenderer.invoke('maker:schedule:run-now', id),/** script 任务能力选择器:各能力的运行时可用性(依赖意识的装入/唤醒态)。 */scriptCapabilityStatus: (): Promise<{- statuses: Array<{ capability: string; state: 'ok' | 'ghost-missing' | 'ghost-asleep'; ghostName?: string }>;+ statuses: Array<{+ capability: string;+ state: 'ok' | 'ghost-missing' | 'ghost-asleep';+ ghostName?: string;+ }>;}> => ipcRenderer.invoke('maker:schedule:script-capability-status'),/** 表单「测试运行」:立即执行一次前置检查脚本,返回判定 / exit code / 输出 / 耗时。 */testPreRunHook: (params: {@@ -5503,26 +5872,29 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 绑定会话任务:workingDir 空时 main 按会话 meta.workDir 解析落盘/自测目录。 */targetSessionId?: string;currentCommand?: string;- }): Promise<{- ok: true;- command: string;- filePath: string;- content: string;- test: {- status: 'passed' | 'skipped' | 'failed' | 'timed_out' | 'aborted';- decision: 'run' | 'skip' | 'block';- exitCode: number | null;- durationMs: number;- stdout: string;- stderr: string;- stdoutTruncated: boolean;- stderrTruncated: boolean;- timedOut: boolean;- aborted: boolean;- spawnError?: string;- error?: string;- };- } | UtilityTextFailure> => ipcRenderer.invoke('maker:schedule:generate-pre-run-hook', params),+ }): Promise<+ | {+ ok: true;+ command: string;+ filePath: string;+ content: string;+ test: {+ status: 'passed' | 'skipped' | 'failed' | 'timed_out' | 'aborted';+ decision: 'run' | 'skip' | 'block';+ exitCode: number | null;+ durationMs: number;+ stdout: string;+ stderr: string;+ stdoutTruncated: boolean;+ stderrTruncated: boolean;+ timedOut: boolean;+ aborted: boolean;+ spawnError?: string;+ error?: string;+ };+ }+ | UtilityTextFailure+ > => ipcRenderer.invoke('maker:schedule:generate-pre-run-hook', params),listRuns: (id: string, limit?: number): Promise<unknown[]> =>ipcRenderer.invoke('maker:schedule:list-runs', id, limit),// 回传 { runs, inflightRunIds }:后者是引擎内存里的权威 in-flight 集合,renderer 的@@ -5587,8 +5959,12 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:cross-agent:detect', workingDir, agentKind),convert: (items: CrossAgentMigrationItem[],- ): Promise<{ total: number; successCount: number; skippedCount: number; failedCount: number }> =>- ipcRenderer.invoke('maker:cross-agent:convert', items),+ ): Promise<{+ total: number;+ successCount: number;+ skippedCount: number;+ failedCount: number;+ }> => ipcRenderer.invoke('maker:cross-agent:convert', items),onStep: fanOutCrossAgentStep,},@@ -5614,17 +5990,17 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── Browser automation (Settings →「电脑使用」) ──────────────────────browser: {- status: (): Promise<BrowserAvailability> =>- ipcRenderer.invoke('maker:browser:status'),+ status: (): Promise<BrowserAvailability> => ipcRenderer.invoke('maker:browser:status'),openForLogin: (): Promise<{ launched: boolean }> =>ipcRenderer.invoke('maker:browser:open-for-login'),},android: {- status: (): Promise<AndroidStatusSummary> =>- ipcRenderer.invoke('maker:android:status'),+ status: (): Promise<AndroidStatusSummary> => ipcRenderer.invoke('maker:android:status'),getConfig: (): Promise<AndroidAutomationConfigState> =>ipcRenderer.invoke('maker:android:get-config'),- setDefaultDevice: (defaultDeviceSerial: string | null): Promise<AndroidAutomationConfigState> =>+ setDefaultDevice: (+ defaultDeviceSerial: string | null,+ ): Promise<AndroidAutomationConfigState> =>ipcRenderer.invoke('maker:android:set-default-device', { defaultDeviceSerial }),setAdbPath: (adbPathOverride: string | null): Promise<AndroidAutomationConfigState> =>ipcRenderer.invoke('maker:android:set-adb-path', { adbPathOverride }),@@ -5655,15 +6031,15 @@ contextBridge.exposeInMainWorld('electronAPI', {fanOutComputerPermissionGuideCancelled(callback),onPermissionGuideStatusChanged: (callback: (status: ComputerDriverStatus) => void,- ): (() => void) => fanOutComputerPermissionGuideStatusChanged(- (data: unknown) => callback(data as ComputerDriverStatus),- ),+ ): (() => void) =>+ fanOutComputerPermissionGuideStatusChanged((data: unknown) =>+ callback(data as ComputerDriverStatus),+ ),checkUpdate: (): Promise<ComputerDriverUpdateCheck> =>ipcRenderer.invoke('maker:computer:check-update'),updateDriver: (opts?: { joinOnly?: boolean }): Promise<ComputerDriverInstallResult> =>ipcRenderer.invoke('maker:computer:update-driver', opts),onUpdateProgress: fanOutComputerDriverUpdateProgress,-},},diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex e1b60ad71c..99bf94ffc6 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -37,9 +37,7 @@ import {preloadLocalCatalogSnapshot,refreshLocalCatalogSnapshot,} from '@/lib/localCatalogSnapshot';-import {- useResyncAgentIslandSettingsAfterLogin,-} from '@/hooks/useAgentIslandSettings';+import { useResyncAgentIslandSettingsAfterLogin } from '@/hooks/useAgentIslandSettings';import {getDraftForPreferenceSync,subscribeDraft,@@ -75,10 +73,7 @@ function LoginHandoffHost({ children }: { children: React.ReactNode }) {{/* 认证恢复后已登录(直进受保护路由、LoginPage 不挂载)时结束首启亮色门,避免 renderer localStorage 被清空但主进程仍持有会话时整个已登录会话被永久锁亮色;未登录场景仍由 LoginPage 卸载结束门(见组件头注释)。 */}- <LoginFirstLaunchLightGateBridge- authResolved={!isInitializing}- canEnterApp={canEnterApp}- />+ <LoginFirstLaunchLightGateBridge authResolved={!isInitializing} canEnterApp={canEnterApp} />{children}</LoginHandoffProvider>);@@ -112,6 +107,12 @@ function MakerBootstrap() {return null;}+function OwnerScopedRouter() {+ const { dataOwnerId, dataOwnerRecoveryEpoch } = useAuth();+ const ownerKey = `${dataOwnerId ?? 'signed-out'}:${dataOwnerRecoveryEpoch}`;+ return <RouterProvider key={ownerKey} router={router} />;+}+export function App() {useDisableContextMenu();useDisableTab();@@ -192,7 +193,8 @@ export function App() {({ agent, providerId, modelId, active, effort, fast, markModelChoice }) => {const vendor = agentKindToVendor(agent);if (active) {- const patch = markModelChoice === false ? patchVendorPrefsPreservingModelChoice : patchVendorPrefs;+ const patch =+ markModelChoice === false ? patchVendorPrefsPreservingModelChoice : patchVendorPrefs;const shouldPatchActiveModel = markModelChoice !== false || effort !== undefined;if (shouldPatchActiveModel) {patch(vendor, {@@ -296,8 +298,12 @@ export function App() {{/* 副窗口(「在新窗口打开」)/ 右侧栏子窗口跳过 splash:env/热更检查由主窗启动时完成,附属窗 EnvCheckProvider 初始即 'passed',不需要也不应再走 splash 流程。 */}- {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && <LoginBrandStage />}- {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && <SplashScreen />}+ {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && (+ <LoginBrandStage />+ )}+ {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && (+ <SplashScreen />+ )}<EnvCheckGuard><MakerBootstrap /><ProjectAutomationNotifyBridge />@@ -305,13 +311,15 @@ export function App() {内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口都挂、谁收到谁弹,不按窗口类型 gate。 */}<GhostConfirmDialogHost />- <RouterProvider router={router} />+ <OwnerScopedRouter /></EnvCheckGuard></LoginHandoffHost><FindInPageBar /><ToastContainer />{/* 首登轻量数据迁移弹窗:只挂主窗(副窗/侧栏窗不重复弹) */}- {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && <LegacyMigrationDialog />}+ {!isSecondaryWindow() && !isSidebarWindow() && !isGhostPanelWindow() && (+ <LegacyMigrationDialog />+ )}</Tooltip.Provider></PrRefsProvider></WorktreeProvider>diff --git a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts b/apps/desktop/src/renderer/__tests__/authContextRace.test.tsindex 1540046b52..5c9d1c1144 100644--- a/apps/desktop/src/renderer/__tests__/authContextRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/authContextRace.test.ts@@ -1,6 +1,11 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it } from 'vitest';+import {+ __testing as dataOwnerTesting,+ isDataOwnerPushCurrent,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';/*** Guards renderer auth state transitions. 产品 role 二段式水合已随 /api/me@@ -12,6 +17,7 @@ describe('AuthContext auth-state races', () => {resolve(process.cwd(), 'src/renderer/contexts/AuthContext.tsx'),'utf8',);+ const appSource = readFileSync(resolve(process.cwd(), 'src/renderer/App.tsx'), 'utf8');it('applies identity synchronously and resets session snapshot on account switch', () => {expect(source).toContain('activeDataOwnerIdRef.current !== state.dataOwnerId');@@ -19,7 +25,7 @@ describe('AuthContext auth-state races', () => {expect(source).toContain('setUser(incoming);');// 防复活:renderer 不得再对业务 server 发起 role/资料水合请求。expect(source).not.toContain('meService');- expect(source).not.toContain("apiRequest<");+ expect(source).not.toContain('apiRequest<');expect(source).not.toContain('getMe(');});@@ -34,17 +40,37 @@ describe('AuthContext auth-state races', () => {});it('publishes a data-owner generation at every auth boundary', () => {- expect(source).toContain('setDataOwnerGeneration(dataOwnerId);');+ expect(source).toContain('cancelRemoteOptimisticSendsForDataOwnerBoundary();');+ expect(source).toContain('setDataOwnerGeneration(dataOwnerId, ownerGeneration);');expect(source).toContain('invalidateProvidersSnapshot();');- expect(source).toContain('publishDataOwnerGeneration(state.dataOwnerId);');- expect(source).toContain('// Invalidate in-flight remote sends before the confirmation dialog resolves.');+ expect(source).toContain(+ 'publishDataOwnerGeneration(state.dataOwnerId, state.ownerGeneration);',+ );+ expect(source).toContain(+ '// Invalidate in-flight remote sends before the confirmation dialog resolves.',+ );expect(source.match(/publishDataOwnerGeneration\(null\);/g)?.length).toBeGreaterThanOrEqual(2);+ expect(source.indexOf('cancelRemoteOptimisticSendsForDataOwnerBoundary();')).toBeLessThan(+ source.indexOf('setDataOwnerGeneration(dataOwnerId, ownerGeneration);'),+ );const enterLocal = source.indexOf('const enterLocalMode = useCallback');const exitLocal = source.indexOf('const exitLocalMode = useCallback');- expect(source.indexOf('publishDataOwnerGeneration(state.dataOwnerId);', enterLocal))- .toBeLessThan(exitLocal);- expect(source.indexOf('publishDataOwnerGeneration(state.dataOwnerId);', exitLocal))- .toBeGreaterThan(exitLocal);+ expect(+ source.indexOf(+ 'publishDataOwnerGeneration(state.dataOwnerId, state.ownerGeneration);',+ enterLocal,+ ),+ ).toBeLessThan(exitLocal);+ expect(+ source.indexOf(+ 'publishDataOwnerGeneration(state.dataOwnerId, state.ownerGeneration);',+ exitLocal,+ ),+ ).toBeGreaterThan(exitLocal);+ expect(source).toContain('activeDataOwnerGenerationRef.current');+ expect(source).toContain('setDataOwnerRecoveryEpoch((epoch) => epoch + 1);');+ expect(appSource).toContain("`${dataOwnerId ?? 'signed-out'}:${dataOwnerRecoveryEpoch}`");+ expect(appSource).toContain('<RouterProvider key={ownerKey} router={router} />');});it('projects browser waiting state before the main-process loopback request settles', () => {@@ -52,3 +78,30 @@ describe('AuthContext auth-state races', () => {expect(source).toContain("setLoginState({ step: 'browser-redirect', label: action.label });");});});++describe('data-owner live push fencing', () => {+ afterEach(() => {+ dataOwnerTesting.reset();+ });++ it('accepts legacy unstamped pushes and the exact current owner stamp', () => {+ setDataOwnerGeneration('owner-a', 4);++ expect(isDataOwnerPushCurrent(undefined)).toBe(true);+ expect(+ isDataOwnerPushCurrent({ dataOwnerId: 'owner-a', ownerGeneration: 4 }),+ ).toBe(true);+ });++ it('rejects stale, cross-owner, and malformed stamped pushes', () => {+ setDataOwnerGeneration('owner-b', 7);++ expect(+ isDataOwnerPushCurrent({ dataOwnerId: 'owner-b', ownerGeneration: 6 }),+ ).toBe(false);+ expect(+ isDataOwnerPushCurrent({ dataOwnerId: 'owner-a', ownerGeneration: 7 }),+ ).toBe(false);+ expect(isDataOwnerPushCurrent(null)).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsxindex 097fd24817..7bcb369e00 100644--- a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx+++ b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx@@ -103,6 +103,7 @@ function authState(id: string | null, isCanary = false) {user: id ? user(id) : null,mode: id ? ('cloud' as const) : ('signed-out' as const),dataOwnerId: id,+ ownerGeneration: id ? 1 : 2,canEnterApp: id !== null,isAuthenticated: id !== null,isCanary,@@ -117,6 +118,7 @@ function localAuthState() {user: null,mode: 'local' as const,dataOwnerId: 'local-v1',+ ownerGeneration: 3,canEnterApp: true,isAuthenticated: false,isCanary: false,@@ -127,9 +129,7 @@ function localAuthState() {}describe('AuthContext session cache boundaries', () => {- const wrapper = ({ children }: PropsWithChildren) => (- <AuthProvider>{children}</AuthProvider>- );+ const wrapper = ({ children }: PropsWithChildren) => <AuthProvider>{children}</AuthProvider>;beforeEach(() => {mocks.reset.mockClear();@@ -145,7 +145,9 @@ describe('AuthContext session cache boundaries', () => {mocks.service.logout.mockResolvedValue(undefined);mocks.service.enterLocalMode.mockResolvedValue(localAuthState());mocks.service.exitLocalMode.mockResolvedValue(authState(null));- (window as unknown as { electronAPI: { onAuthSessionExpired: typeof mocks.registerExpired } }).electronAPI = {+ (+ window as unknown as { electronAPI: { onAuthSessionExpired: typeof mocks.registerExpired } }+ ).electronAPI = {onAuthSessionExpired: mocks.registerExpired,};});@@ -199,12 +201,14 @@ describe('AuthContext session cache boundaries', () => {mocks.service[action].mockRejectedValueOnce(new Error(`${action} failed`));const view = renderHook(() => useAuth(), { wrapper });await waitFor(() => expect(view.result.current.dataOwnerId).toBe(expectedOwner));+ const recoveryEpochBeforeFailure = view.result.current.dataOwnerRecoveryEpoch;await act(async () => {await expect(view.result.current[action]()).rejects.toThrow(`${action} failed`);});expect(view.result.current.dataOwnerId).toBe(expectedOwner);+ expect(view.result.current.dataOwnerRecoveryEpoch).toBe(recoveryEpochBeforeFailure + 1);expect(getDataOwnerGeneration().dataOwnerId).toBe(expectedOwner);expect(mocks.preloadLocalCatalogSnapshot).toHaveBeenCalledOnce();},@@ -212,9 +216,11 @@ describe('AuthContext session cache boundaries', () => {it('keeps a newer pushed owner when an older auth boundary later rejects', async () => {let rejectLogout!: (error: Error) => void;- mocks.service.logout.mockReturnValueOnce(new Promise<void>((_resolve, reject) => {- rejectLogout = reject;- }));+ mocks.service.logout.mockReturnValueOnce(+ new Promise<void>((_resolve, reject) => {+ rejectLogout = reject;+ }),+ );const view = renderHook(() => useAuth(), { wrapper });await waitFor(() => expect(view.result.current.dataOwnerId).toBe('account-a'));@@ -237,12 +243,16 @@ describe('AuthContext session cache boundaries', () => {let rejectFirst!: (error: Error) => void;let rejectSecond!: (error: Error) => void;mocks.service.logout- .mockReturnValueOnce(new Promise<void>((_resolve, reject) => {- rejectFirst = reject;- }))- .mockReturnValueOnce(new Promise<void>((_resolve, reject) => {- rejectSecond = reject;- }));+ .mockReturnValueOnce(+ new Promise<void>((_resolve, reject) => {+ rejectFirst = reject;+ }),+ )+ .mockReturnValueOnce(+ new Promise<void>((_resolve, reject) => {+ rejectSecond = reject;+ }),+ );const view = renderHook(() => useAuth(), { wrapper });await waitFor(() => expect(view.result.current.dataOwnerId).toBe('account-a'));@@ -284,12 +294,16 @@ describe('AuthContext session cache boundaries', () => {let rejectSecond!: (error: Error) => void;mocks.service.initialize.mockResolvedValue(localAuthState());mocks.service.exitLocalMode- .mockReturnValueOnce(new Promise((resolve) => {- resolveFirst = resolve;- }))- .mockReturnValueOnce(new Promise((_resolve, reject) => {- rejectSecond = reject;- }));+ .mockReturnValueOnce(+ new Promise((resolve) => {+ resolveFirst = resolve;+ }),+ )+ .mockReturnValueOnce(+ new Promise((_resolve, reject) => {+ rejectSecond = reject;+ }),+ );const view = renderHook(() => useAuth(), { wrapper });await waitFor(() => expect(view.result.current.dataOwnerId).toBe('local-v1'));diff --git a/apps/desktop/src/renderer/__tests__/autoPermissionFallbackToast.test.ts b/apps/desktop/src/renderer/__tests__/autoPermissionFallbackToast.test.tsindex 1cac7a2d5f..403c517abd 100644--- a/apps/desktop/src/renderer/__tests__/autoPermissionFallbackToast.test.ts+++ b/apps/desktop/src/renderer/__tests__/autoPermissionFallbackToast.test.ts@@ -1,4 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ __testing as dataOwnerGenerationTesting,+ setDataOwnerGeneration,+} from '../contexts/dataOwnerGeneration';+import { __testing as remoteDataOwnerPushFenceTesting } from '../lib/remoteDataOwnerPushFence';const mocks = vi.hoisted(() => ({translate: vi.fn((key: string) => key),@@ -25,9 +30,14 @@ const payload: AutoPermissionFallbackPayload = {beforeEach(() => {mocks.translate.mockClear();mocks.warning.mockClear();+ dataOwnerGenerationTesting.reset();+ remoteDataOwnerPushFenceTesting.reset();+ setDataOwnerGeneration('owner-a', 1);});afterEach(() => {+ remoteDataOwnerPushFenceTesting.reset();+ dataOwnerGenerationTesting.reset();vi.unstubAllGlobals();});diff --git a/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.tsindex 194948e434..a3153eeef8 100644--- a/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts@@ -25,8 +25,8 @@ describe('ChatInput Ghost snapshot contract', () => {it('uses the latest installed snapshot and workdir at send time', () => {expect(source).toContain('const installedGhostsRef = useRef(installedGhosts);');expect(source).toContain('installedGhostsRef.current = installedGhosts;');- expect(source).toContain(- 'const eligibleGhosts = filterGhostsForWorkdir(\n installedGhostsRef.current,\n workingDirRef.current,\n );',+ expect(source).toMatch(+ /const eligibleGhosts\s*=\s*filterGhostsForWorkdir\(\s*installedGhostsRef\.current,\s*workingDirRef\.current,\s*\);[\s\S]*?expandGhostCommand\(text,\s*eligibleGhosts\)/,);});diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.tsindex 611c36378e..10634956b6 100644--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts@@ -42,20 +42,30 @@ describe('ChatInput session switch focus contract', () => {expect(chatInputSource).toContain('focusOnStorageKeyChange?: boolean;');expect(chatInputSource).toContain('focusOnStorageKeyChange = false');- expect(chatInputSource).toContain('const focusOnStorageKeyChangeRef = useRef(focusOnStorageKeyChange);');- expect(chatInputSource).toContain('focusOnStorageKeyChangeRef.current = focusOnStorageKeyChange;');+ expect(chatInputSource).toContain(+ 'const focusOnStorageKeyChangeRef = useRef(focusOnStorageKeyChange);',+ );+ expect(chatInputSource).toContain(+ 'focusOnStorageKeyChangeRef.current = focusOnStorageKeyChange;',+ );expect(chatInputSource).toContain('const storageKeyFocusAnchor = document.activeElement;');expect(restoreNextDraftBlock).toContain('if (!focusOnStorageKeyChangeRef.current) return;');- expect(restoreNextDraftBlock).toContain('if (disableAutofocusRef.current || disabledRef.current) return;');+ expect(restoreNextDraftBlock).toContain(+ 'if (disableAutofocusRef.current || disabledRef.current) return;',+ );expect(restoreNextDraftBlock).toContain('if (!isCurrentTransition()) return;');- expect(restoreNextDraftBlock).toContain('if (hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor)) return;');+ expect(restoreNextDraftBlock).toContain(+ 'if (hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor)) return;',+ );expect(restoreNextDraftBlock).toContain("editor.commands.focus('end');");expect(firstMountHydrationBlock).toContain('focusOnStorageKeyChangeRef.current');expect(firstMountHydrationBlock).toContain("editor.commands.focus('end');");});it('enables storageKey refocus for routed session and new-draft views', () => {- expect(sessionViewSource).toContain('const ownsRoute = !sessionIdProp && !isCompactRail && !isOrcaMode;');+ expect(sessionViewSource).toContain(+ 'const ownsRoute = !sessionIdProp && !isCompactRail && !isOrcaMode;',+ );expect(sessionViewSource).toContain('focusOnStorageKeyChange={ownsRoute}');expect(newMakerDraftRouteSource).toContain('focusOnStorageKeyChange');});@@ -73,9 +83,7 @@ describe('ChatInput session switch focus contract', () => {});it('keeps deferred editor mount autofocus at the draft end', () => {- expect(chatInputSource).toContain(- "autofocus: !disableAutofocus && !disabled ? 'end' : false",- );+ expect(chatInputSource).toContain("autofocus: !disableAutofocus && !disabled ? 'end' : false");});it('guards delayed storageKey focus against stealing from another focused control', () => {@@ -98,8 +106,8 @@ describe('ChatInput session switch focus contract', () => {it('records recent Plugin usage only after a successful direct or deferred send', () => {const successfulSendBlock = extractBetween(chatInputSource,- 'if (result === false) return;',- '// Suppress onUpdate',+ 'if (result === false) {',+ 'if (!optimisticallyClearRemoteComposer) clearSentComposer();',);const worktreeSendBlock = extractBetween(newMakerDraftRouteSource,@@ -114,6 +122,79 @@ describe('ChatInput session switch focus contract', () => {expect(worktreeSendBlock).toContain('if (accepted) opts?.onAccepted?.();');});+ it('optimistically clears device-link composer state before awaiting send and restores without dropping newer input', () => {+ const transitionBegin = chatInputSource.indexOf(+ 'makerChatStore.beginRemoteOptimisticComposerTransition(',+ );+ const optimisticClear = chatInputSource.indexOf(+ 'if (optimisticallyClearRemoteComposer) {',+ );+ const frozenReferenceHydration = chatInputSource.search(+ /agentReferences\s*=\s*await resolveSerializedSessionMessageReferencesForSend\(agentReferences\);/,+ );+ const onSend = chatInputSource.indexOf('result = await onSend(', optimisticClear);+ const failedRestore = chatInputSource.indexOf('restoreRemoteComposerAndRelease();', onSend);+ const restoreAndReleaseBlock = extractBetween(+ chatInputSource,+ 'const restoreRemoteComposerAndRelease = () => {',+ 'if (optimisticallyClearRemoteComposer) {',+ );++ expect(chatInputSource).toContain('deviceLinkDeviceId && sourceSessionId');+ expect(transitionBegin).toBeGreaterThanOrEqual(0);+ expect(optimisticClear).toBeGreaterThanOrEqual(0);+ expect(transitionBegin).toBeLessThan(optimisticClear);+ expect(frozenReferenceHydration).toBeGreaterThan(optimisticClear);+ expect(frozenReferenceHydration).toBeLessThan(onSend);+ expect(onSend).toBeGreaterThan(optimisticClear);+ expect(failedRestore).toBeGreaterThan(onSend);+ expect(chatInputSource).toContain('sourceSessionId,\n filesToSend,');+ expect(restoreAndReleaseBlock.indexOf('restoreOptimisticallyClearedComposer();')).toBeLessThan(+ restoreAndReleaseBlock.indexOf('releaseRemoteComposerTransition();'),+ );+ expect(chatInputSource).toContain('let optimisticComposerRestored = false;');+ expect(chatInputSource).toContain('restoreRemoteOptimisticDraft(');+ expect(chatInputSource).toContain('text: isEditorEmpty(editor) ? null : editor.getJSON()');+ expect(chatInputSource).toContain('attachments: latestAttachmentsRef.current');+ expect(chatInputSource).toContain('browserComments: browserCommentsRef.current');+ expect(chatInputSource).toContain("editor.commands.focus('end');");+ expect(chatInputSource).toContain('restoreFiles(restored.attachments);');+ expect(chatInputSource).toContain(+ 'latestStorageKeyRef.current === sourceStorageKey &&\n storageKeyForDraftRef.current === sourceStorageKey',+ );+ expect(chatInputSource).toContain('restoreRemoteOptimisticDraft(\n sourceStorageKey,');+ expect(chatInputSource).toContain('!isDataOwnerGenerationCurrent(dataOwnerAtOptimisticClear)');+ expect(chatInputSource).toContain('restoreOptimisticallyClearedComposer(clientId, {');+ expect(chatInputSource).toContain('isRemoteOptimisticDataOwnerBoundaryError(error)');+ expect(chatInputSource).toContain('isRemoteOptimisticSessionPurgedError(error)');+ expect(chatInputSource).toContain('optimisticComposerRestored = true;');+ expect(chatInputSource).toContain('isRemoteOptimisticComposerTransitionActive(');+ expect(chatInputSource).toContain('updateLive: !isDataOwnerBoundary');+ expect(chatInputSource).toContain('recoveryBatch: error as object');+ expect(chatInputSource).toContain('recoveryBatch ? { recoveryBatch } : undefined');+ expect(chatInputSource).toContain('if (!updateLive || !isCurrentComposer) return;');+ expect(chatInputSource).toContain('if (!isDataOwnerGenerationCurrent(dataOwnerAtEffect))');+ expect(chatInputSource).toContain(+ 'if (!isDataOwnerGenerationCurrent(dataOwnerAtSubscription)) return;',+ );+ expect(chatInputSource).toContain('browserCommentsRef.current = nextBrowserComments;');+ expect(chatInputSource).toContain('browserCommentsRef.current = restoredComments;');+ expect(chatInputSource).not.toContain('mergeComposerDocumentsForRestore(');+ });++ it('reuses the original voice-session recovery checkpoint until the editor owner switches', () => {+ expect(chatInputSource).toContain('useRef<RemoteOptimisticTransitionCheckpoint | null>(null)');+ expect(chatInputSource).toContain('getOrCreateRemoteOptimisticTransitionCheckpoint(');+ expect(chatInputSource).toContain('saveComposerTextAfterAsyncTransition(');+ expect(chatInputSource).toContain('recoveryCheckpoint!');+ expect(chatInputSource).toContain('if (pendingStopAndSend || voiceInputBusyRef.current)');+ expect(chatInputSource).toContain('}, [editor, storageKey]);');+ expect(chatInputSource).not.toContain('}, [editor, storageKey, voiceInput.isBusy]);');+ expect(chatInputSource.match(/storageKeyTransitionRecoveryRef\.current = null;/g)).toHaveLength(+ 2,+ );+ });+it('propagates the existing-session enqueue acceptance promise back to ChatInput', () => {const sendMessageBlock = extractBetween(useCCAgentChatSource,@@ -132,9 +213,7 @@ describe('ChatInput session switch focus contract', () => {expect(pluginPageSource).toMatch(/sortGhostPluginItemsByRecentUse\(installedItems, recentGhostIds\)/,);- expect(pluginPageSource).not.toContain(- 'sortGhostPluginItemsByRecentUse(\n ghosts',- );+ expect(pluginPageSource).not.toContain('sortGhostPluginItemsByRecentUse(\n ghosts');});});diff --git a/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.tsindex 3aab718155..e9acae68ca 100644--- a/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts@@ -73,8 +73,8 @@ describe('ChatInput steer shortcut contract', () => {// 回归防线:确认门相关符号不得重新出现在 ChatInput 里。const handleQueueSteerBlock = extractBetween(chatInputSource,- 'const handleQueueSteer = useCallback(async (clientId: string) => {',- "const handleClickSend = useCallback(async (deliveryMode: MessageDeliveryMode = 'queue') => {",+ 'const handleQueueSteer = useCallback(',+ 'const handleClickSend = useCallback(',);expect(handleQueueSteerBlock).toContain('return onQueueSteer(clientId);');@@ -83,8 +83,8 @@ describe('ChatInput steer shortcut contract', () => {expect(chatInputSource).not.toContain('confirmInterruptSteer');expect(chatInputSource).not.toContain('interruptConfirm');expect(pendingQueuePanelSource).toContain('turnRunning?: boolean;');- expect(pendingQueuePanelSource).toContain(- "const base = t(turnRunning ? 'newChat.pendingQueue.steerRunningTip' : 'newChat.pendingQueue.steerPausedTip');",+ expect(pendingQueuePanelSource).toMatch(+ /const base\s*=\s*t\(\s*turnRunning\s*\?\s*'newChat\.pendingQueue\.steerRunningTip'\s*:\s*'newChat\.pendingQueue\.steerPausedTip'/,);});diff --git a/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts b/apps/desktop/src/renderer/__tests__/composerListDocument.test.tsindex 65bc8879c2..4c12ebdb0b 100644--- a/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerListDocument.test.ts@@ -1,10 +1,26 @@import { describe, expect, it } from 'vitest';import {+ insertComposerDocumentForRestore,normalizeComposerDocumentJSON,plainTextToComposerDocument,} from '@/lib/composerListDocument';+const bulletListDocument = (text: string) => ({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text }] }],+ },+ ],+ },+ ],+});+describe('composer list document normalization', () => {it('promotes plain ordered rows into one structured list', () => {expect(plainTextToComposerDocument('1. first\n2. second')).toEqual({@@ -226,9 +242,7 @@ describe('composer list document normalization', () => {});it('does not promote marker-shaped lines inside fenced code', () => {- expect(- plainTextToComposerDocument('before\n```js\n1. literal\n```\n2. real'),- ).toEqual({+ expect(plainTextToComposerDocument('before\n```js\n1. literal\n```\n2. real')).toEqual({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: 'before' }] },@@ -288,4 +302,136 @@ describe('composer list document normalization', () => {};expect(normalizeComposerDocumentJSON(document)).toEqual(document);});++ it('restores a failed send before text entered while it was waiting', () => {+ expect(+ insertComposerDocumentForRestore(+ {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'failed send' }] }],+ },+ {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'new draft' }] }],+ },+ ).document,+ ).toEqual({+ type: 'doc',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'failed send' }] },+ { type: 'paragraph' },+ { type: 'paragraph', content: [{ type: 'text', text: 'new draft' }] },+ ],+ });+ });++ it('inserts consecutive failed sends at a stable FIFO cursor', () => {+ const current = {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'C' }] }],+ };+ const first = insertComposerDocumentForRestore(+ {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'A' }] }],+ },+ current,+ );+ const second = insertComposerDocumentForRestore(+ {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'B' }] }],+ },+ first.document,+ first.nextInsertAt,+ );++ expect(second.document.content).toEqual([+ { type: 'paragraph', content: [{ type: 'text', text: 'A' }] },+ { type: 'paragraph' },+ { type: 'paragraph', content: [{ type: 'text', text: 'B' }] },+ { type: 'paragraph' },+ { type: 'paragraph', content: [{ type: 'text', text: 'C' }] },+ ]);+ });++ it('keeps compatible lists separate across a recovery boundary', () => {+ expect(+ insertComposerDocumentForRestore(+ {+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [+ { type: 'paragraph', content: [{ type: 'text', text: 'failed item' }] },+ ],+ },+ ],+ },+ ],+ },+ {+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'new item' }] }],+ },+ ],+ },+ ],+ },+ ).document,+ ).toEqual({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'failed item' }] }],+ },+ ],+ },+ { type: 'paragraph' },+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'new item' }] }],+ },+ ],+ },+ ],+ });+ });++ it('keeps consecutive compatible list recoveries in FIFO order', () => {+ const first = insertComposerDocumentForRestore(+ bulletListDocument('A'),+ bulletListDocument('C'),+ );+ const second = insertComposerDocumentForRestore(+ bulletListDocument('B'),+ first.document,+ first.nextInsertAt,+ );++ expect(second.document.content).toEqual([+ bulletListDocument('A').content[0],+ { type: 'paragraph' },+ bulletListDocument('B').content[0],+ { type: 'paragraph' },+ bulletListDocument('C').content[0],+ ]);+ });});diff --git a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.tsindex 56dc475dfe..c1ec1381f4 100644--- a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts+++ b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts@@ -17,25 +17,47 @@ describe('controlled banner placement', () => {it('renders the controlled banner in the input status bar for routed chat or explicit opt-in', () => {expect(sessionViewSource).toContain('showControlledBanner?: boolean;');expect(sessionViewSource).toContain('showControlledBanner = false');- expect(sessionViewSource).toContain('const showInlineControlledBanner = ownsRoute || showControlledBanner;');- expect(sessionViewSource).toContain('centerSlot={showInlineControlledBanner ? <ControlledBanner placement="statusbar" /> : null}');- expect(sessionViewSource).toContain('<ControlledBanner placement="inline" maxWidth={controlledBannerMaxWidth} />');+ expect(sessionViewSource).toContain(+ 'const showInlineControlledBanner = ownsRoute || showControlledBanner;',+ );+ expect(sessionViewSource).toMatch(+ /centerSlot=\{\s*showInlineControlledBanner\s*\?\s*<ControlledBanner placement="statusbar" \/>\s*:\s*null\s*\}/,+ );+ expect(sessionViewSource).toContain(+ '<ControlledBanner placement="inline" maxWidth={controlledBannerMaxWidth} />',+ );});it('keeps the statusbar center slot geometrically centered above lower-priority side text', () => {expect(sessionViewSource).toContain('const STATUS_BAR_CENTER_SLOT_MAX_WIDTH = 420;');expect(sessionViewSource).toContain('const STATUS_BAR_CENTER_SLOT_WIDTH_RATIO = 0.5;');- expect(sessionViewSource).toContain('function getControlledBannerMaxWidth(inputWidth?: number): number');+ expect(sessionViewSource).toContain(+ 'function getControlledBannerMaxWidth(inputWidth?: number): number',+ );expect(sessionViewSource).toContain('(inputWidth - 16) * STATUS_BAR_CENTER_SLOT_WIDTH_RATIO');- expect(sessionViewSource).toContain('const centerSlotMaxWidth = getControlledBannerMaxWidth(inputWidth);');- expect(sessionViewSource).toContain('const controlledBannerMaxWidth = getControlledBannerMaxWidth(inputWidth);');+ expect(sessionViewSource).toContain(+ 'const centerSlotMaxWidth = getControlledBannerMaxWidth(inputWidth);',+ );+ expect(sessionViewSource).toContain(+ 'const controlledBannerMaxWidth = getControlledBannerMaxWidth(inputWidth);',+ );expect(sessionViewSource).toContain('grid-cols-[minmax(0,1fr)_minmax(0,auto)_minmax(0,1fr)]');- expect(sessionViewSource).toContain('className="z-10 flex min-w-0 max-w-full items-center justify-center px-2"');+ expect(sessionViewSource).toContain(+ 'className="z-10 flex min-w-0 max-w-full items-center justify-center px-2"',+ );expect(sessionViewSource).toContain('style={{ maxWidth: centerSlotMaxWidth }}');- expect(sessionViewSource).toContain('className="flex min-w-0 items-center justify-self-end gap-[6px]"');- expect(controlledBannerSource).toContain('flex min-w-0 max-w-full select-none items-center gap-2 overflow-hidden');- expect(controlledBannerSource).toContain('className="min-w-0 truncate text-[12px] text-[var(--text-primary)]"');- expect(controlledBannerSource).toContain('className="flex min-w-0 max-w-[45%] shrink items-center gap-1');+ expect(sessionViewSource).toContain(+ 'className="flex min-w-0 items-center justify-self-end gap-[6px]"',+ );+ expect(controlledBannerSource).toContain(+ 'flex min-w-0 max-w-full select-none items-center gap-2 overflow-hidden',+ );+ expect(controlledBannerSource).toContain(+ 'className="min-w-0 truncate text-[12px] text-[var(--text-primary)]"',+ );+ expect(controlledBannerSource).toContain(+ 'className="flex min-w-0 max-w-[45%] shrink items-center gap-1',+ );expect(controlledBannerSource).toContain('<span className="min-w-0 truncate">');expect(controlledBannerSource).not.toContain("placement === 'statusbar' && 'my-");expect(sessionViewSource).not.toContain('grid-cols-[1fr_auto_1fr]');@@ -45,11 +67,15 @@ describe('controlled banner placement', () => {it('uses the same width cap for the plan-review inline fallback', () => {expect(controlledBannerSource).toContain('maxWidth?: number;');expect(controlledBannerSource).toContain('style={maxWidth == null ? undefined : { maxWidth }}');- expect(sessionViewSource).toContain('<ControlledBanner placement="inline" maxWidth={controlledBannerMaxWidth} />');+ expect(sessionViewSource).toContain(+ '<ControlledBanner placement="inline" maxWidth={controlledBannerMaxWidth} />',+ );});it('opts in only route-owned chat views, not Worker panes or embedded doc rails', () => {- expect(sessionViewSource).toContain('const showInlineControlledBanner = ownsRoute || showControlledBanner;');+ expect(sessionViewSource).toContain(+ 'const showInlineControlledBanner = ownsRoute || showControlledBanner;',+ );expect(routeSource).not.toContain('<CCAgentSessionView');expect(routeSource).not.toContain('showControlledBanner');expect(splitViewSource).not.toContain('showLeadControlledBanner');@@ -60,8 +86,12 @@ describe('controlled banner placement', () => {});it('suppresses the global floating fallback on legacy Orca redirect pages', () => {- expect(mainLayoutSource).toContain('function hasInlineControlledBannerPath(pathname: string): boolean');- expect(mainLayoutSource).toContain("return parts.length === 3 && parts[1] === 'orca' && parts[2] !== 'new';");+ expect(mainLayoutSource).toContain(+ 'function hasInlineControlledBannerPath(pathname: string): boolean',+ );+ expect(mainLayoutSource).toContain(+ "return parts.length === 3 && parts[1] === 'orca' && parts[2] !== 'new';",+ );expect(mainLayoutSource).toContain('{!hasInlineControlledBanner && <ControlledBanner />}');});});diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.tsindex f90a2741c6..cc4fb78550 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts@@ -17,6 +17,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { Message, Session } from '@/lib/ccAgent.types';+import {+ __testing as dataOwnerTesting,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';vi.mock('@/lib/messageService', () => ({list: vi.fn(async () => []),@@ -40,6 +44,7 @@ vi.mock('@/lib/imageRef', () => ({}));vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({ type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }] }),}));@@ -48,7 +53,13 @@ import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore'// ─── 忠实的被控端内存替身(单一真相源)───────────────────────────────────────────-type RemotePush = { deviceId: string; channel: string; payload: unknown };+const TEST_OWNER_STAMP = { dataOwnerId: 'test-owner', ownerGeneration: 0 } as const;+type RemotePush = {+ deviceId: string;+ channel: string;+ payload: unknown;+ ownerStamp?: typeof TEST_OWNER_STAMP;+};function emptyProjection(sessionId: string) {return {@@ -107,7 +118,7 @@ function makeFakeHost(deviceId: string, deviceName: string) {invoke,/** 注册控制端 onRemotePush 回调(被控端经此向控制端转发广播)。 */registerPush(cb: (p: RemotePush) => void): () => void {- pushCb = cb;+ pushCb = (push) => cb({ ...push, ownerStamp: push.ownerStamp ?? TEST_OWNER_STAMP });return () => {pushCb = null;};@@ -176,6 +187,8 @@ const sid = () => `ctrl-scn-${n++}`;let host: FakeHost;beforeEach(() => {+ dataOwnerTesting.reset();+ setDataOwnerGeneration(TEST_OWNER_STAMP.dataOwnerId, TEST_OWNER_STAMP.ownerGeneration);host = makeFakeHost(DEVICE_ID, 'Mac A');stubElectronApi(host);makerChatStore.initGlobalListeners();@@ -186,6 +199,7 @@ afterEach(() => {remoteProjectsStore.clear();delete (globalThis as { window?: unknown }).window;vi.clearAllMocks();+ dataOwnerTesting.reset();});describe('device-link controller mirror — end-to-end scenarios', () => {diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex 0cfb573fad..77e1b1e868 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -19,6 +19,10 @@ import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import type { Session } from '@/lib/ccAgent.types';+import {+ __testing as dataOwnerTesting,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';vi.mock('@/lib/messageService', () => ({list: vi.fn(async () => []),@@ -41,6 +45,7 @@ vi.mock('@/lib/imageRef', () => ({}));vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],@@ -52,7 +57,13 @@ import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore'import * as messageService from '@/lib/messageService';import { getIssueConfirmDraft, saveIssueConfirmDraft } from '@/lib/issueConfirmDraftStore';-type RemotePush = { deviceId: string; channel: string; payload: unknown };+const TEST_OWNER_STAMP = { dataOwnerId: 'test-owner', ownerGeneration: 0 } as const;+type RemotePush = {+ deviceId: string;+ channel: string;+ payload: unknown;+ ownerStamp?: typeof TEST_OWNER_STAMP;+};type ResolveCall = { requestId: string; decision: Record<string, unknown> };/** 被控端内存替身:转发 interaction push,记录 resolve-interaction,并提供挂起交互快照。 */@@ -95,7 +106,7 @@ function makeFakeHost(deviceId: string) {pending.set(sessionId, arr);},registerPush(cb: (p: RemotePush) => void): () => void {- pushCb = cb;+ pushCb = (push) => cb({ ...push, ownerStamp: push.ownerStamp ?? TEST_OWNER_STAMP });return () => {pushCb = null;};@@ -207,6 +218,8 @@ function openRemoteSession(): string {}beforeEach(() => {+ dataOwnerTesting.reset();+ setDataOwnerGeneration(TEST_OWNER_STAMP.dataOwnerId, TEST_OWNER_STAMP.ownerGeneration);host = makeFakeHost(DEVICE_ID);local = stubElectronApi(host);makerChatStore.initGlobalListeners();@@ -217,6 +230,7 @@ afterEach(() => {remoteProjectsStore.clear();delete (globalThis as { window?: unknown }).window;vi.clearAllMocks();+ dataOwnerTesting.reset();});describe('device-link 远程交互往返 — permission', () => {@@ -775,7 +789,7 @@ describe('远程交互接线不变式', () => {it('makerChatStore 不向 device-link 远程 session 透传本地 Maker Memory 开关;SSH 跟随全局设置', () => {const src = read('lib/makerChatStore.ts');- expect(src).toContain('const deviceLinkRemote = isRemoteSession(sessionId);');+ expect(src).toContain('const deviceLinkRemote = isRemoteSessionSticky(sessionId);');// 该表达式可能被 prettier 折成多行:先把空白折叠成单空格,只锁 token 序列。// SSH remote 与本地同语义 (memory 按 hostId+远端路径 scope 存本机),// 不再出现 ssh 强制 false 的三元;device-link 仍整体省略该字段。@@ -868,7 +882,9 @@ describe('远程交互接线不变式', () => {const sync = body.indexOf('syncSessionDraftModelPrefs(');expect(atomic).toBeGreaterThan(-1);expect(fallback).toBeGreaterThan(atomic);- expect(persist).toBeGreaterThan(body.indexOf('await remoteMaker.setEffort(sessionId, newEffort);'));+ expect(persist).toBeGreaterThan(+ body.indexOf('await remoteMaker.setEffort(sessionId, newEffort);'),+ );expect(persist).toBeGreaterThan(-1);expect(sync).toBeGreaterThan(-1);expect(persist).toBeLessThan(sync);@@ -891,7 +907,9 @@ describe('远程交互接线不变式', () => {const finalize = body.indexOf('onModelDidChange?.(targetModel);');expect(atomic).toBeGreaterThan(-1);expect(fallback).toBeGreaterThan(atomic);- expect(persist).toBeGreaterThan(body.indexOf('await remoteMaker.setEffort(sessionId, targetEffort);'));+ expect(persist).toBeGreaterThan(+ body.indexOf('await remoteMaker.setEffort(sessionId, targetEffort);'),+ );expect(persist).toBeGreaterThan(-1);expect(sync).toBeGreaterThan(-1);expect(body.slice(persist, sync)).not.toContain('return;');@@ -904,8 +922,10 @@ describe('远程交互接线不变式', () => {it('会话同步 New Maker 草稿默认不应打 modelChosenByVendor 显式选择标记', () => {const chatInputSrc = read('components/new-chat/ChatInput.tsx');const syncStart = chatInputSrc.indexOf('const syncSessionDraftModelPrefs');+ const syncEnd = chatInputSrc.indexOf('const persistFastModeChange', syncStart);expect(syncStart).toBeGreaterThan(-1);- const syncBody = chatInputSrc.slice(syncStart, syncStart + 1900);+ expect(syncEnd).toBeGreaterThan(syncStart);+ const syncBody = chatInputSrc.slice(syncStart, syncEnd);expect(syncBody).toContain('patchVendorPrefsPreservingModelChoice');expect(syncBody).toContain('markModelChoice: false');expect(syncBody).toContain(@@ -993,8 +1013,15 @@ describe('远程交互接线不变式', () => {'makerChatStore.setFastMode(sessionId, enabled, sourceRemoteDeviceId)',);const storeSrc = read('lib/makerChatStore.ts');- expect(storeSrc).toContain('sourceRemoteDeviceId || isRemoteSession(sessionId)');- expect(storeSrc).toContain('makerApiForDevice(sourceRemoteDeviceId)');+ const setFastStart = storeSrc.indexOf('async function setFastMode(');+ const setFastEnd = storeSrc.indexOf('async function setPlanMode(', setFastStart);+ expect(setFastStart).toBeGreaterThan(-1);+ expect(setFastEnd).toBeGreaterThan(setFastStart);+ const setFastBody = storeSrc.slice(setFastStart, setFastEnd);+ expect(setFastBody).toContain(+ 'const remoteDeviceId = sourceRemoteDeviceId ?? getStickySessionDeviceId(sessionId);',+ );+ expect(setFastBody).toContain('makerApiForDevice(remoteDeviceId)');});it('effort 回调必须追踪 sticky deviceId 并向父级保留远程 scope', () => {@@ -1086,7 +1113,9 @@ describe('远程交互接线不变式', () => {expect(applyStart).toBeGreaterThan(-1);const applyBody = src.slice(applyStart, applyStart + 3200);expect(applyBody).toContain('modelMemory?.setFast(');- expect(applyBody).toContain('newProviderId,\n modelId,\n restoredFast,');+ expect(applyBody).toMatch(+ /modelMemory\?\.setFast\(\s*currentModelAgentKind,\s*newProviderId,\s*modelId,\s*restoredFast,?\s*\)/,+ );});it('ChatInput 本地切来源把完整选择交给 main 原子落定后再更新 UI', () => {@@ -1137,7 +1166,8 @@ describe('远程交互接线不变式', () => {// handler 可以只委托 helper,但 helper 必须负责 resolved 广播和权威落库。// 截取窗口用下一个语法边界而非固定字符数:handler/helper 体量会随入参校验、// 注释增长,固定窗口会在无行为回归时误报(#329 曾把调用挤出 1000 字符窗口)。- const handlerStart = src.indexOf('ipcMain.handle(MAKER_INVOKE.RESOLVE_INTERACTION');+ const handlerMatch = /ipcMain\.handle\(\s*MAKER_INVOKE\.RESOLVE_INTERACTION/.exec(src);+ const handlerStart = handlerMatch?.index ?? -1;expect(handlerStart).toBeGreaterThan(-1);const handlerEnd = src.indexOf('ipcMain.handle(', handlerStart + 1);const handlerBody = src.slice(handlerStart, handlerEnd === -1 ? undefined : handlerEnd);diff --git a/apps/desktop/src/renderer/__tests__/dropMessagesFromClientId.test.ts b/apps/desktop/src/renderer/__tests__/dropMessagesFromClientId.test.tsindex c8c3fce1ae..d034497fe6 100644--- a/apps/desktop/src/renderer/__tests__/dropMessagesFromClientId.test.ts+++ b/apps/desktop/src/renderer/__tests__/dropMessagesFromClientId.test.ts@@ -52,6 +52,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],diff --git a/apps/desktop/src/renderer/__tests__/fileBrowserTransportGzip.test.ts b/apps/desktop/src/renderer/__tests__/fileBrowserTransportGzip.test.tsindex 9fc4f96924..7e20ecaf79 100644--- a/apps/desktop/src/renderer/__tests__/fileBrowserTransportGzip.test.ts+++ b/apps/desktop/src/renderer/__tests__/fileBrowserTransportGzip.test.ts@@ -13,13 +13,25 @@ import { randomBytes } from 'node:crypto';import { gunzipSync, gzipSync } from 'node:zlib';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ __testing as dataOwnerGenerationTesting,+ setDataOwnerGeneration,+} from '../contexts/dataOwnerGeneration';+import { __testing as remoteDataOwnerPushFenceTesting } from '../lib/remoteDataOwnerPushFence';type InvokeMock = ReturnType<typeof vi.fn>;+type RemotePush = {+ deviceId: string;+ channel: string;+ payload: unknown;+ ownerStamp?: { dataOwnerId: string | null; ownerGeneration: number };+};const BIG = 'markdown 正文内容\n'.repeat(8000); // ~144K chars,> 64K 压缩阈值const SMALL = 'short content';let invokeMock: InvokeMock;+let remotePushHandler: ((push: RemotePush, localOwnerStamp?: unknown) => void) | undefined;let transport: typeof import('../lib/fileBrowserTransport');/** 取第 n 次 remote-op invoke 的 op args(invoke(deviceId, channel, [args])) */@@ -29,13 +41,28 @@ function opArgs(n: number): Record<string, unknown> {beforeEach(async () => {invokeMock = vi.fn();+ remotePushHandler = undefined;+ dataOwnerGenerationTesting.reset();+ remoteDataOwnerPushFenceTesting.reset();vi.stubGlobal('window', {- electronAPI: { deviceLink: { invoke: invokeMock } },+ electronAPI: {+ deviceLink: {+ invoke: invokeMock,+ onRemotePush: (handler: (push: RemotePush, localOwnerStamp?: unknown) => void) => {+ remotePushHandler = handler;+ return () => {+ if (remotePushHandler === handler) remotePushHandler = undefined;+ };+ },+ },+ },});transport = await import('../lib/fileBrowserTransport');});afterEach(() => {+ remoteDataOwnerPushFenceTesting.reset();+ dataOwnerGenerationTesting.reset();vi.unstubAllGlobals();});@@ -183,3 +210,89 @@ describe('fileBrowserTransport gzip read decode', () => {expect(res.data.content).toBe('plain');});});++describe('fileBrowserTransport owner fence', () => {+ it('rejects stale local-owner frames before they can advance the remote fence', () => {+ const cb = vi.fn();+ setDataOwnerGeneration('owner-b', 8);+ transport.onFileTreeEventFor('device-1', cb);++ const stalePush = {+ deviceId: 'device-1',+ channel: 'maker:file-browser:event',+ payload: {+ workdir: '/w',+ type: 'change' as const,+ relPath: 'src/a.ts',+ },+ ownerStamp: { dataOwnerId: 'owner-b', ownerGeneration: 5 },+ };+ remotePushHandler?.(stalePush, { dataOwnerId: 'owner-b', ownerGeneration: 7 });+ expect(cb).not.toHaveBeenCalled();++ remotePushHandler?.(+ {+ ...stalePush,+ ownerStamp: { dataOwnerId: 'owner-b', ownerGeneration: 1 },+ },+ { dataOwnerId: 'owner-b', ownerGeneration: 8 },+ );+ expect(cb).toHaveBeenCalledTimes(1);+ });++ it('tracks remote generations per device and closes legacy downgrade after a stamp', () => {+ const cb = vi.fn();+ setDataOwnerGeneration('owner-b', 8);+ transport.onFileTreeEventFor('device-1', cb);++ const payload = {+ workdir: '/w',+ type: 'change' as const,+ relPath: 'src/a.ts',+ };+ // Legacy peers remain compatible before this device proves stamp support.+ remotePushHandler?.({+ deviceId: 'device-1',+ channel: 'maker:file-browser:event',+ payload,+ });+ // Remote generations are process-local. Generation 1 is valid even though+ // the controller renderer is already at generation 8.+ remotePushHandler?.({+ deviceId: 'device-1',+ channel: 'maker:file-browser:event',+ payload,+ ownerStamp: { dataOwnerId: 'owner-b', ownerGeneration: 1 },+ });+ expect(cb).toHaveBeenCalledTimes(2);++ // Once stamped, unstamped downgrade frames and generation rollback fail+ // closed, while a newer remote generation remains valid.+ remotePushHandler?.({+ deviceId: 'device-1',+ channel: 'maker:file-browser:event',+ payload,+ });+ remotePushHandler?.({+ deviceId: 'device-1',+ channel: 'maker:file-browser:event',+ payload,+ ownerStamp: { dataOwnerId: 'owner-b', ownerGeneration: 0 },+ });+ remotePushHandler?.({+ deviceId: 'device-1',+ channel: 'maker:file-browser:event',+ payload,+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 9 },+ });+ expect(cb).toHaveBeenCalledTimes(2);++ remotePushHandler?.({+ deviceId: 'device-1',+ channel: 'maker:file-browser:event',+ payload,+ ownerStamp: { dataOwnerId: 'owner-b', ownerGeneration: 2 },+ });+ expect(cb).toHaveBeenCalledTimes(3);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/goalLearnTransportRouting.test.ts b/apps/desktop/src/renderer/__tests__/goalLearnTransportRouting.test.tsindex 127fd71eff..3fb4b2303c 100644--- a/apps/desktop/src/renderer/__tests__/goalLearnTransportRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/goalLearnTransportRouting.test.ts@@ -14,6 +14,16 @@ beforeEach(() => {vi.resetModules();});+async function primeOwnerFence(): Promise<void> {+ const { __testing: dataOwnerGenerationTesting, setDataOwnerGeneration } =+ await import('@/contexts/dataOwnerGeneration');+ const { __testing: remoteDataOwnerPushFenceTesting } =+ await import('@/lib/remoteDataOwnerPushFence');+ dataOwnerGenerationTesting.reset();+ remoteDataOwnerPushFenceTesting.reset();+ setDataOwnerGeneration('owner-a', 1);+}+const GOAL_TUNNEL_CHANNELS = ['maker:goal:set','maker:goal:clear',@@ -106,6 +116,7 @@ describe('goalApiFor 路由', () => {const { onRemotePush, makerSpies, remotePushListeners } = stubElectron();const { subscribeGoalStatusChanged } = await import('@/lib/makerTransport');const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');+ await primeOwnerFence();remoteProjectsStore.setDeviceSessions('dev-1', 'Mac', [sess('rs')]);const cb = vi.fn();@@ -159,6 +170,7 @@ describe('learnApiFor 路由', () => {const { learnSpies, remotePushListeners } = stubElectron();const { subscribeLearnEvents } = await import('@/features/learn/learnTransport');const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');+ await primeOwnerFence();remoteProjectsStore.setDeviceSessions('dev-1', 'Mac', [sess('rs')]);const cb = vi.fn();@@ -199,6 +211,7 @@ describe('origin 注入竞态(Codex review #548 回归)', () => {const { learnSpies, remotePushListeners } = stubElectron();const { subscribeLearnEvents } = await import('@/features/learn/learnTransport');const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');+ await primeOwnerFence();const cb = vi.fn();subscribeLearnEvents('rs', cb); // origin 未注册 → 先绑本机diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.tsindex 404323441f..fd73696459 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreActiveView.test.ts@@ -38,6 +38,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAroundClientId.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAroundClientId.test.tsindex 99d0e87861..6d43a9c571 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAroundClientId.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAroundClientId.test.ts@@ -30,6 +30,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoName.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoName.test.tsindex c61046a3b1..25e8d6e1ab 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoName.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoName.test.ts@@ -39,21 +39,21 @@ vi.mock('@/lib/logger', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],}),}));-const isRemoteSession = vi.fn((_sessionId: string) => false);-vi.mock('@/lib/makerTransport', async (importOriginal) => ({- ...(await importOriginal<Record<string, unknown>>()),- isRemoteSession: (id: string) => isRemoteSession(id),-}));-import { makerChatStore } from '@/lib/makerChatStore';import * as sessionService from '@/lib/sessionService';+import type { Session } from '@/lib/ccAgent.types';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import {+ __resetStickySessionOriginForTest,+ getStickySessionDeviceId,+} from '@/features/device-link/stickySessionOrigin';const SESSION_ID = 'auto-name-session';@@ -65,10 +65,11 @@ const flushPromises = async () => {beforeEach(() => {vi.clearAllMocks();- isRemoteSession.mockReturnValue(false);autoTitle.mockResolvedValue({ applied: true, done: true });makerChatStore.__resetAutoNameStateForTest();remoteProjectsStore.clear();+ remoteProjectsStore.__resetPinnedOriginsForTest();+ __resetStickySessionOriginForTest();remoteProjectsStore.__resetPendingTitlePreviewForTest();const w = globalThis as unknown as { window: Record<string, unknown> };w.window = { electronAPI: { maker: { autoTitle } } };@@ -267,12 +268,18 @@ describe('makerChatStore auto-name — 本机会话', () => {// 早的那次失败若按 sessionId 直接撤回,会把仍在飞的那次的预览一起revoke,标题白闪// 一次「未命名任务」。let failFirst: (v: { applied: boolean; done: boolean }) => void = () => {};- autoTitle.mockImplementationOnce(() => new Promise((resolve) => {- failFirst = resolve;- }));- autoTitle.mockImplementationOnce(() => new Promise(() => {- /* 第二次一直在飞 */- }));+ autoTitle.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ failFirst = resolve;+ }),+ );+ autoTitle.mockImplementationOnce(+ () =>+ new Promise(() => {+ /* 第二次一直在飞 */+ }),+ );makerChatStore.autoNameSession(SESSION_ID, '第一句', 'claude-code');makerChatStore.autoNameSession(SESSION_ID, '第二句', 'claude-code');@@ -348,7 +355,17 @@ describe('makerChatStore auto-name — 本机会话', () => {'medium','default','/tmp/wd',- [{ id: 'f1', name: '设计稿-v3.png', path: '/tmp/设计稿-v3.png', ext: '.png', size: 1, category: 'image', mimeType: 'image/png' }],+ [+ {+ id: 'f1',+ name: '设计稿-v3.png',+ path: '/tmp/设计稿-v3.png',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ },+ ],);await flushPromises();@@ -441,7 +458,8 @@ describe('makerChatStore auto-name — 本机会话', () => {describe('makerChatStore auto-name — device-link 远程会话', () => {beforeEach(() => {- isRemoteSession.mockReturnValue(true);+ remoteProjectsStore.setDeviceSessions('dev-auto', 'Mac', [{ id: SESSION_ID } as Session]);+ expect(getStickySessionDeviceId(SESSION_ID)).toBe('dev-auto');});it('不发起名 IPC(权威标题由被控端写),只登记投影层预览', async () => {@@ -478,4 +496,16 @@ describe('makerChatStore auto-name — device-link 远程会话', () => {expect(sessionService.get).not.toHaveBeenCalled();setPreview.mockRestore();});++ it('mirror 清空后仍沿用最后已知设备,不回退本机起名 IPC', async () => {+ remoteProjectsStore.clear();+ const setPreview = vi.spyOn(remoteProjectsStore, 'setPendingTitlePreview');++ makerChatStore.autoNameSession(SESSION_ID, '断线期间的第一句话', 'codex');+ await flushPromises();++ expect(setPreview).toHaveBeenCalledWith(SESSION_ID, '断线期间的第一句话', true);+ expect(autoTitle).not.toHaveBeenCalled();+ setPreview.mockRestore();+ });});diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.tsindex 4a6fdf5312..e5f3f9c57d 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreAutoResumeCard.test.ts@@ -49,6 +49,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.tsindex cbdac01fb6..515398ce62 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreJumpBackfill.test.ts@@ -63,6 +63,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.tsindex df0f087011..6733e1e56a 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreLearnCard.test.ts@@ -35,6 +35,7 @@ vi.mock('@/lib/imageRef', () => ({}));vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.tsindex 44de79c5d8..f762dbdae1 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTaskUpdates.test.ts@@ -50,6 +50,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex b4ae2f3bac..5d20180496 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -6,12 +6,9 @@*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import {- GHOST_SETUP_MAX_INTERACTION_STEPS,- GHOST_SETUP_MAX_STEPS,-} from '../../shared/ghost';+import { GHOST_SETUP_MAX_INTERACTION_STEPS, GHOST_SETUP_MAX_STEPS } from '../../shared/ghost';import type { AgentInputProjection, AgentInputQueuedMessage } from '../../shared/agentInputQueue';-import type { Message } from '@/lib/ccAgent.types';+import type { Message, Session } from '@/lib/ccAgent.types';import type { AttachedFile, MentionedResource } from '@/lib/fileTypes';vi.mock('@/lib/messageService', () => ({@@ -88,16 +85,31 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],}),}));-import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';+import {+ isRemoteOptimisticSessionPurgedError,+ makerChatStore,+ type ChatMessage,+} from '@/lib/makerChatStore';import * as messageService from '@/lib/messageService';import * as sessionService from '@/lib/sessionService';import * as sessionsBus from '@/lib/sessionsBus';+import { setRemoteOptimisticAttachmentUrls } from '@/lib/composerDraftStore';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import {+ __resetStickySessionOriginForTest,+ getStickySessionDeviceId,+} from '@/features/device-link/stickySessionOrigin';+import {+ __testing as dataOwnerGenerationTesting,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';import { CONTINUE_AFTER_APP_EXIT_PROMPT } from '../../shared/interruptedTurn';const SESSION_ID = 'text-delta-batching';@@ -119,9 +131,20 @@ function serverMessage(let onEvent: ((data: unknown) => void) | undefined;let onStatusChanged: ((data: unknown) => void) | undefined;+let onDeviceLinkStatusChanged: ((data: unknown) => void) | undefined;+let onPresenceChanged: ((data: unknown) => void) | undefined;+let onRemotePush: ((data: unknown, ownerStamp?: unknown) => void) | undefined;let onDbMessageCreated: ((data: unknown) => void) | undefined;+let onInputProjection: ((data: unknown) => void) | undefined;let onInteractionRequest: ((data: unknown) => void) | undefined;let onInteractionDismissed: ((data: unknown) => void) | undefined;+let onGhostMessageBlocked: ((data: unknown, ownerStamp?: unknown) => void) | undefined;+let onGhostMessageRewritten: ((data: unknown, ownerStamp?: unknown) => void) | undefined;+let onGhostAssistantRewritten: ((data: unknown, ownerStamp?: unknown) => void) | undefined;+let onGhostAssistantPending: ((data: unknown, ownerStamp?: unknown) => void) | undefined;+let onGhostHookFused: ((data: unknown, ownerStamp?: unknown) => void) | undefined;+let onGhostNotify: ((data: unknown, ownerStamp?: unknown) => void) | undefined;+let onGhostPreviewOpen: ((data: unknown, ownerStamp?: unknown) => void) | undefined;const getPendingInteractions = vi.fn<(sessionId: string) => Promise<Array<{@@ -130,6 +153,8 @@ const getPendingInteractions = vi.fn<}>>>(async () => []);+const deviceLinkInvoke =+ vi.fn<(deviceId: string, channel: string, args: unknown[]) => Promise<unknown>>();const input = {getProjection: vi.fn(async (sessionId: string) => projection(sessionId)),@@ -148,7 +173,10 @@ const input = {setExpanded: vi.fn(async (sessionId: string) => projection(sessionId)),setInteractionLock: vi.fn(async (sessionId: string) => projection(sessionId)),setEditLock: vi.fn(async (sessionId: string) => projection(sessionId)),- clearSession: vi.fn(async (sessionId: string, _clearedAt?: string) => projection(sessionId)),+ clearSession: vi.fn(async (sessionId: string, clearedAt?: string) => {+ void clearedAt;+ return projection(sessionId);+ }),persistTurnErrorDeferred: vi.fn(async () => {}),};@@ -176,19 +204,34 @@ function projection(function installElectronBridge(): void {onEvent = undefined;onStatusChanged = undefined;+ onDeviceLinkStatusChanged = undefined;+ onPresenceChanged = undefined;+ onRemotePush = undefined;onDbMessageCreated = undefined;+ onInputProjection = undefined;onInteractionRequest = undefined;onInteractionDismissed = undefined;+ onGhostMessageBlocked = undefined;+ onGhostMessageRewritten = undefined;+ onGhostAssistantRewritten = undefined;+ onGhostAssistantPending = undefined;+ onGhostHookFused = undefined;+ onGhostNotify = undefined;+ onGhostPreviewOpen = undefined;for (const fn of Object.values(input) as Array<{ mockClear: () => void }>) {fn.mockClear();}+ deviceLinkInvoke.mockReset();const w = globalThis as unknown as { window: Record<string, unknown> };w.window = {electronAPI: {maker: {input,- onInputProjection: vi.fn(() => vi.fn()),+ onInputProjection: (cb: (data: unknown) => void) => {+ onInputProjection = cb;+ return vi.fn();+ },onEvent: (cb: (data: unknown) => void) => {onEvent = cb;return vi.fn();@@ -215,6 +258,13 @@ function installElectronBridge(): void {closeSession: vi.fn(async () => {}),listActive: vi.fn(async () => []),},+ cacheMediaForSession: vi.fn(async ({ sessionId }: { sessionId: string }) => ({+ url: `xdt-image://${sessionId}/private.png`,+ name: 'private.png',+ ext: '.png',+ mimeType: 'image/png',+ size: 1,+ })),safeStorageRead: vi.fn(async () => 'local-key'),localDb: {messages: {@@ -227,6 +277,51 @@ function installElectronBridge(): void {ackInterrupted: vi.fn(async () => undefined),},},+ deviceLink: {+ invoke: deviceLinkInvoke,+ onStatusChanged: (cb: (data: unknown) => void) => {+ onDeviceLinkStatusChanged = cb;+ return vi.fn();+ },+ onPresenceChanged: (cb: (data: unknown) => void) => {+ onPresenceChanged = cb;+ return vi.fn();+ },+ onRemotePush: (cb: (data: unknown, ownerStamp?: unknown) => void) => {+ onRemotePush = cb;+ return vi.fn();+ },+ },+ ghosts: {+ onUserMessageBlocked: (cb: (data: unknown, ownerStamp?: unknown) => void) => {+ onGhostMessageBlocked = cb;+ return vi.fn();+ },+ onUserMessageRewritten: (cb: (data: unknown, ownerStamp?: unknown) => void) => {+ onGhostMessageRewritten = cb;+ return vi.fn();+ },+ onAssistantMessageRewritten: (cb: (data: unknown, ownerStamp?: unknown) => void) => {+ onGhostAssistantRewritten = cb;+ return vi.fn();+ },+ onAssistantMessagePending: (cb: (data: unknown, ownerStamp?: unknown) => void) => {+ onGhostAssistantPending = cb;+ return vi.fn();+ },+ onHookFused: (cb: (data: unknown, ownerStamp?: unknown) => void) => {+ onGhostHookFused = cb;+ return vi.fn();+ },+ onNotify: (cb: (data: unknown, ownerStamp?: unknown) => void) => {+ onGhostNotify = cb;+ return vi.fn();+ },+ onPreviewOpen: (cb: (data: unknown, ownerStamp?: unknown) => void) => {+ onGhostPreviewOpen = cb;+ return vi.fn();+ },+ },},};}@@ -354,13 +449,21 @@ const flushPromises = async () => {describe('makerChatStore text delta batching', () => {const MULTI_SESSION_IDS = Array.from({ length: 10 }, (_, i) => `${SESSION_ID}-multi-${i}`);+ const LRU_SESSION_IDS = Array.from({ length: 21 }, (_, i) => `${SESSION_ID}-lru-${i}`);beforeEach(() => {vi.useFakeTimers();vi.clearAllMocks();makerChatStore.__teardownGlobalListeners();makerChatStore.purgeSession(SESSION_ID);+ makerChatStore.__resetRemoteTerminalTombstonesForTest();+ remoteProjectsStore.clear();+ remoteProjectsStore.__resetPinnedOriginsForTest();+ __resetStickySessionOriginForTest();+ dataOwnerGenerationTesting.reset();+ setDataOwnerGeneration('owner-a');for (const sessionId of MULTI_SESSION_IDS) makerChatStore.purgeSession(sessionId);+ for (const sessionId of LRU_SESSION_IDS) makerChatStore.purgeSession(sessionId);installElectronBridge();makerChatStore.initGlobalListeners();});@@ -368,7 +471,13 @@ describe('makerChatStore text delta batching', () => {afterEach(() => {makerChatStore.__teardownGlobalListeners();makerChatStore.purgeSession(SESSION_ID);+ makerChatStore.__resetRemoteTerminalTombstonesForTest();+ remoteProjectsStore.clear();+ remoteProjectsStore.__resetPinnedOriginsForTest();+ __resetStickySessionOriginForTest();+ dataOwnerGenerationTesting.reset();for (const sessionId of MULTI_SESSION_IDS) makerChatStore.purgeSession(sessionId);+ for (const sessionId of LRU_SESSION_IDS) makerChatStore.purgeSession(sessionId);vi.useRealTimers();});@@ -400,6 +509,55 @@ describe('makerChatStore text delta batching', () => {unsubscribe();});+ it('drops stale ghost pushes before they mutate the current owner slice', () => {+ const staleOwnerStamp = { dataOwnerId: 'owner-b', ownerGeneration: 1 };+ const currentOwnerStamp = { dataOwnerId: 'owner-a', ownerGeneration: 1 };+ const blockedPayload = {+ sessionId: SESSION_ID,+ clientId: 'ghost-client-1',+ ghostId: 'ghost-a',+ ghostName: 'Ghost A',+ reason: 'blocked',+ text: 'original text',+ };++ onGhostMessageBlocked?.(blockedPayload, staleOwnerStamp);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);++ onGhostMessageBlocked?.(blockedPayload, currentOwnerStamp);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({+ clientId: 'ghost-client-1',+ content: 'original text',+ blockedByGhost: expect.objectContaining({ ghostId: 'ghost-a' }),+ }),+ ]);++ onGhostMessageRewritten?.(+ { sessionId: SESSION_ID, clientId: 'ghost-client-1', text: 'stale rewrite' },+ staleOwnerStamp,+ );+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]?.content).toBe('original text');++ onGhostMessageRewritten?.(+ { sessionId: SESSION_ID, clientId: 'ghost-client-1', text: 'current rewrite' },+ currentOwnerStamp,+ );+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]?.content).toBe('current rewrite');++ onGhostAssistantPending?.(+ { sessionId: SESSION_ID, clientId: 'ghost-client-1', pending: true },+ staleOwnerStamp,+ );+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]?.ghostReplyPending).toBeUndefined();++ onGhostAssistantPending?.(+ { sessionId: SESSION_ID, clientId: 'ghost-client-1', pending: true },+ currentOwnerStamp,+ );+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]?.ghostReplyPending).toBe(true);+ });+it('flushes pending text before the next non-delta event', () => {emitTextDelta('a');@@ -846,6 +1004,122 @@ describe('makerChatStore text delta batching', () => {expect(after.pluginSetupViewerState).toBe('minimized');});+ it('pins interaction snapshots to the last known remote device while the origin map is rebuilding', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ expect(getStickySessionDeviceId(SESSION_ID)).toBe('device-1');+ remoteProjectsStore.__resetPinnedOriginsForTest();+ getPendingInteractions.mockClear();+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ expect(channel).toBe('maker:get-pending-interactions');+ expect(args).toEqual([SESSION_ID]);+ return [+ {+ request: {+ kind: 'plan_review',+ requestId: 'remote-plan-review',+ plan: '# Remote plan',+ },+ persistId: 'persist-remote-plan-review',+ },+ ];+ });++ await expect(makerChatStore.reconcilePendingInteractions(SESSION_ID)).resolves.toBe(1);++ expect(getPendingInteractions).not.toHaveBeenCalled();+ expect(deviceLinkInvoke).toHaveBeenCalledTimes(1);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingPlanReview?.requestId).toBe(+ 'remote-plan-review',+ );+ });++ it('does not replay an interaction snapshot that became stale after dismissal', async () => {+ let resolveSnapshot!: (items: Awaited<ReturnType<typeof getPendingInteractions>>) => void;+ getPendingInteractions.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveSnapshot = resolve;+ }),+ );++ const reconcile = makerChatStore.reconcilePendingInteractions(SESSION_ID);+ onInteractionDismissed?.({+ sessionId: SESSION_ID,+ requestId: 'permission-late',+ reason: 'session_closed',+ });+ resolveSnapshot([+ {+ request: {+ kind: 'permission',+ requestId: 'permission-late',+ toolName: 'Read',+ input: { file_path: 'late.ts' },+ },+ },+ ]);++ await expect(reconcile).resolves.toBe(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingPermission).toBeNull();+ });++ it('does not replay an interaction snapshot across a data-owner boundary', async () => {+ let resolveSnapshot!: (items: Awaited<ReturnType<typeof getPendingInteractions>>) => void;+ getPendingInteractions.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveSnapshot = resolve;+ }),+ );++ const reconcile = makerChatStore.reconcilePendingInteractions(SESSION_ID);+ setDataOwnerGeneration('owner-b');+ resolveSnapshot([+ {+ request: {+ kind: 'permission',+ requestId: 'permission-old-owner',+ toolName: 'Read',+ input: { file_path: 'old-owner.ts' },+ },+ },+ ]);++ await expect(reconcile).resolves.toBe(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingPermission).toBeNull();+ });++ it('lets the newest concurrent interaction reconcile win', async () => {+ let resolveFirst!: (items: Awaited<ReturnType<typeof getPendingInteractions>>) => void;+ getPendingInteractions+ .mockReturnValueOnce(+ new Promise((resolve) => {+ resolveFirst = resolve;+ }),+ )+ .mockResolvedValueOnce([+ {+ request: {+ ...pluginSetupRequest(2),+ },+ },+ ]);++ const first = makerChatStore.reconcilePendingInteractions(SESSION_ID);+ const second = makerChatStore.reconcilePendingInteractions(SESSION_ID);+ await flushPromises();+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingPluginSetup?.revision).toBe(2);++ resolveFirst([+ {+ request: {+ ...pluginSetupRequest(1),+ },+ },+ ]);+ await expect(Promise.all([first, second])).resolves.toEqual([0, 1]);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingPluginSetup?.revision).toBe(2);+ });+it('sends the independent plugin_setup decision and waits for a newer snapshot', async () => {emitInteractionRequest(pluginSetupRequest(1));@@ -1819,6 +2093,2984 @@ describe('makerChatStore text delta batching', () => {expect(messages.filter((m) => m.role === 'user' && m.content === 'accepted')).toHaveLength(1);});+ it('shows a device-link busy send before remote preflight and enqueue settle', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let resolvePreflight!: (value: boolean) => void;+ const preflight = new Promise<boolean>((resolve) => {+ resolvePreflight = resolve;+ });+ let resolveEnqueue!: (value: AgentInputProjection) => void;+ let queued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ queued = args[1] as AgentInputQueuedMessage;+ return new Promise<AgentInputProjection>((resolve) => {+ resolveEnqueue = resolve;+ });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ const send = makerChatStore.sendMessage(+ SESSION_ID,+ 'remote queued',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { beforeEnqueue: () => preflight },+ );++ expect(+ deviceLinkInvoke.mock.calls.some(([, channel]) => channel === 'maker:input:enqueue'),+ ).toBe(false);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toEqual([+ expect.objectContaining({ text: 'remote queued', isPendingEnqueue: true }),+ ]);+ await expect(send).resolves.toBe(true);++ resolvePreflight(true);+ await flushPromises();+ expect(deviceLinkInvoke).toHaveBeenCalledWith(+ 'device-1',+ 'maker:input:enqueue',+ expect.any(Array),+ );+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue[0]).toEqual(+ expect.objectContaining({ isPendingEnqueue: true }),+ );++ resolveEnqueue(projection(SESSION_ID, { pendingQueue: queued ? [queued] : [] }));+ await flushPromises();+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue[0]).toEqual(+ expect.objectContaining({ text: 'remote queued' }),+ );+ expect(+ makerChatStore.getSnapshot(SESSION_ID).pendingQueue[0]?.isPendingEnqueue,+ ).toBeUndefined();+ });++ it('reuses a hydrated remote clear token for the first optimistic dispatch', async () => {+ const clearBoundaryMs = Date.parse('2026-08-03T00:00:00.000Z');+ let projectionProbes = 0;+ let enqueueOpts: unknown;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:get-projection') {+ projectionProbes += 1;+ return projection(SESSION_ID, { clearBoundaryMs });+ }+ if (channel === 'maker:input:enqueue') {+ enqueueOpts = args[2];+ const item = args[1] as AgentInputQueuedMessage;+ return projection(SESSION_ID, { clearBoundaryMs, pendingQueue: [item] });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ onInputProjection?.(projection(SESSION_ID, { clearBoundaryMs }));+ projectionProbes = 0;+ deviceLinkInvoke.mockClear();++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'probe before dispatch',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await flushPromises();++ // pinSessionOrigin starts the normal remote-origin reconciliation probe;+ // the outbox itself must reuse the hydrated token rather than issue another+ // probe before enqueue.+ expect(projectionProbes).toBe(1);+ expect(enqueueOpts).toEqual(+ expect.objectContaining({ expectedClearBoundaryMs: clearBoundaryMs }),+ );+ });++ it('keeps a probe alive when the remote clear is sealing, then retries it', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let projectionProbes = 0;+ let enqueueCalls = 0;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:get-projection') {+ projectionProbes += 1;+ if (projectionProbes === 1) {+ throw new Error('REMOTE_OPTIMISTIC_INPUT_CLEARED: session clear is still sealing');+ }+ return projection(SESSION_ID);+ }+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ return projection(SESSION_ID, { pendingQueue: [args[1] as AgentInputQueuedMessage] });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'retry after sealing',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await flushPromises();+ expect(enqueueCalls).toBe(0);++ onDeviceLinkStatusChanged?.({ status: 'online' });+ await flushPromises();+ expect(projectionProbes).toBe(2);+ expect(enqueueCalls).toBe(1);+ });++ it('rejects a stale modern projection before it can overwrite the new clear epoch', () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const clearBoundaryMs = Date.parse('2026-08-03T00:00:00.000Z');+ onInputProjection?.(+ projection(SESSION_ID, {+ clearBoundaryMs,+ error: 'current epoch error',+ queueInteractionLocks: ['current-lock'],+ }),+ );+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBe('current epoch error');++ onInputProjection?.(+ projection(SESSION_ID, {+ clearBoundaryMs: null,+ error: 'stale epoch error',+ queueInteractionLocks: ['stale-lock'],+ }),+ );++ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBe('current epoch error');+ expect(makerChatStore.getSnapshot(SESSION_ID).queueInteractionLocks).toEqual(['current-lock']);+ });++ it('accepts a source-tagged projection from the sticky origin after the mirror cache is cleared', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let resolveProbe!: (value: AgentInputProjection) => void;+ const restore = vi.fn();+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel) => {+ if (channel === 'maker:input:get-projection') {+ return new Promise<AgentInputProjection>((resolve) => {+ resolveProbe = resolve;+ });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'sticky projection boundary',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure: restore },+ ),+ ).resolves.toBe(true);+ await flushPromises();+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ content: 'sticky projection boundary', isPendingPersist: true }),+ ]);++ // Reconnect clears the live mirror before the first fresh projection arrives,+ // but the sticky origin still identifies the controlled device.+ remoteProjectsStore.clear();+ onRemotePush?.({+ deviceId: 'device-1',+ channel: 'maker:input:projection',+ payload: projection(SESSION_ID, { clearBoundaryMs: Date.parse('2026-08-03T00:01:00.000Z') }),+ });++ expect(restore).toHaveBeenCalledWith(expect.any(String), undefined);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);++ resolveProbe(projection(SESSION_ID));+ await flushPromises();+ });++ it('accepts a second remote send while the first enqueue invoke is still unresolved', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ const sentTexts: string[] = [];+ let resolveFirst!: (value: AgentInputProjection) => void;+ let firstQueued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ const item = args[1] as AgentInputQueuedMessage;+ sentTexts.push(item.text);+ if (sentTexts.length === 1) {+ firstQueued = item;+ return new Promise<AgentInputProjection>((resolve) => {+ resolveFirst = resolve;+ });+ }+ return projection(SESSION_ID, { pendingQueue: [item] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'first pending',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'second pending',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);++ expect(sentTexts).toEqual(['first pending']);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toEqual([+ expect.objectContaining({ text: 'first pending' }),+ expect.objectContaining({ text: 'second pending', isPendingEnqueue: true }),+ ]);++ resolveFirst(projection(SESSION_ID, { pendingQueue: firstQueued ? [firstQueued] : [] }));+ await flushPromises();++ expect(sentTexts).toEqual(['first pending', 'second pending']);+ });++ it('continues the remote FIFO when a DB ack beats the first enqueue response', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ const sentTexts: string[] = [];+ let resolveFirst!: (value: AgentInputProjection) => void;+ let firstQueued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ const item = args[1] as AgentInputQueuedMessage;+ sentTexts.push(item.text);+ if (sentTexts.length === 1) {+ firstQueued = item;+ return new Promise<AgentInputProjection>((resolve) => {+ resolveFirst = resolve;+ });+ }+ return projection(SESSION_ID, { pendingQueue: [item] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'first pending',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'second pending',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);++ expect(sentTexts).toEqual(['first pending']);+ onDbMessageCreated?.({+ sessionId: SESSION_ID,+ message: {+ clientId: firstQueued?.clientId,+ role: 'user',+ content: 'first pending',+ createdAt: new Date().toISOString(),+ },+ });+ resolveFirst(projection(SESSION_ID));+ await flushPromises();++ expect(sentTexts).toEqual(['first pending', 'second pending']);+ });++ it('does not let a detached pre-clear pump race a new optimistic send', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let resolveFirst!: (value: AgentInputProjection) => void;+ let resolveSecondPreflight!: (value: boolean) => void;+ const secondPreflight = new Promise<boolean>((resolve) => {+ resolveSecondPreflight = resolve;+ });+ let secondPreflightCalls = 0;+ const sentTexts: string[] = [];+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:clear-session') return projection(SESSION_ID);+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:enqueue') {+ const item = args[1] as AgentInputQueuedMessage;+ sentTexts.push(item.text);+ if (item.text === 'before clear') {+ return new Promise<AgentInputProjection>((resolve) => {+ resolveFirst = resolve;+ });+ }+ return projection(SESSION_ID, { pendingQueue: [item] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'before clear',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await makerChatStore.clearSession(SESSION_ID);+ await flushPromises();++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'after clear',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ {+ beforeEnqueue: () => {+ secondPreflightCalls += 1;+ return secondPreflight;+ },+ },+ ),+ ).resolves.toBe(true);+ await flushPromises();+ expect(secondPreflightCalls).toBe(1);++ resolveFirst(projection(SESSION_ID));+ await flushPromises();+ expect(secondPreflightCalls).toBe(1);++ resolveSecondPreflight(true);+ await flushPromises();+ expect(sentTexts).toEqual(['before clear', 'after clear']);+ });++ it('keeps a device-link queue item settling until its DB message arrives', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let queued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ queued = args[1] as AgentInputQueuedMessage;+ return projection(SESSION_ID, { pendingQueue: [queued] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'settling remote',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ const clientId = queued?.clientId;+ expect(clientId).toBeTruthy();++ onInputProjection?.(projection(SESSION_ID));+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ clientId, content: 'settling remote', isPendingPersist: true }),+ ]);++ emitDbMessageCreated({+ clientId: clientId!,+ role: 'user',+ content: 'settling remote',+ createdAt: '2026-08-02T00:00:00.000Z',+ });+ const messages = makerChatStore.getSnapshot(SESSION_ID).messages;+ expect(messages.filter((message) => message.clientId === clientId)).toHaveLength(1);+ expect(messages[0]?.isPendingPersist).toBeUndefined();+ });++ it('keeps pending remote attachment URLs live until the DB ack retires the send', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const sentUrl = 'cindy-media://blobs/annotated.png';+ const sourceUrl = 'cindy-media://blobs/original.png';+ let queued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ queued = args[1] as AgentInputQueuedMessage;+ return projection(SESSION_ID, { pendingQueue: [queued] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });+ const attachment: AttachedFile = {+ id: 'remote-live-media',+ name: 'annotated.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: sentUrl,+ annotationSourceUrl: sourceUrl,+ };++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'media pending',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [attachment],+ ),+ ).resolves.toBe(true);+ await flushPromises();++ const liveUrls = vi.mocked(setRemoteOptimisticAttachmentUrls).mock.lastCall?.[0] ?? [];+ expect(liveUrls).toHaveLength(2);+ expect(liveUrls).toEqual(expect.arrayContaining([sentUrl, sourceUrl]));++ emitDbMessageCreated({+ clientId: queued!.clientId,+ role: 'user',+ content: 'media pending',+ createdAt: '2026-08-03T00:00:00.000Z',+ });++ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith([]);+ });++ it('bridges composer media into the remote outbox without a live-reference gap', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const sentUrl = 'cindy-media://blobs/transition-annotated.png';+ const sourceUrl = 'cindy-media://blobs/transition-source.png';+ const attachment: AttachedFile = {+ id: 'remote-transition-media',+ name: 'transition.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: sentUrl,+ annotationSourceUrl: sourceUrl,+ };+ const restore = vi.fn();+ let queued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ queued = args[1] as AgentInputQueuedMessage;+ return projection(SESSION_ID, { pendingQueue: [queued] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ const firstTransitionReport = vi.mocked(setRemoteOptimisticAttachmentUrls).mock.calls.length;+ const release = makerChatStore.beginRemoteOptimisticComposerTransition(+ SESSION_ID,+ [attachment],+ restore,+ );+ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith(+ expect.arrayContaining([sentUrl, sourceUrl]),+ );++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'transition media',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [attachment],+ undefined,+ { onRemoteOptimisticFailure: restore },+ ),+ ).resolves.toBe(true);+ release();++ const reportsBeforeAck = vi+ .mocked(setRemoteOptimisticAttachmentUrls)+ .mock.calls.slice(firstTransitionReport);+ expect(reportsBeforeAck.length).toBeGreaterThan(0);+ expect(+ reportsBeforeAck.every(([urls]) => urls.includes(sentUrl) && urls.includes(sourceUrl)),+ ).toBe(true);++ emitDbMessageCreated({+ clientId: queued!.clientId,+ role: 'user',+ content: 'transition media',+ createdAt: '2026-08-03T00:00:00.000Z',+ });+ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith([]);+ expect(restore).not.toHaveBeenCalled();+ });++ it.each(['send', 'steer'] as const)(+ 'restores a pre-registration %s transition before owner-boundary refs retire and rejects its late continuation',+ async (deliveryMode) => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const attachment: AttachedFile = {+ id: 'owner-transition-media',+ name: 'owner-transition.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: 'cindy-media://blobs/owner-transition.png',+ };+ const restore = vi.fn();+ const release = makerChatStore.beginRemoteOptimisticComposerTransition(+ SESSION_ID,+ [attachment],+ restore,+ );++ makerChatStore.cancelRemoteOptimisticSendsForDataOwnerBoundary();++ expect(restore).toHaveBeenCalledWith(expect.any(String), expect.any(Error));+ expect(restore.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(setRemoteOptimisticAttachmentUrls).mock.invocationCallOrder.at(-1)!,+ );+ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith([]);++ setDataOwnerGeneration('owner-b');+ const accepted = await (deliveryMode === 'steer'+ ? makerChatStore.steerMessage(+ SESSION_ID,+ 'late owner transition',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [attachment],+ undefined,+ { onRemoteOptimisticFailure: restore },+ )+ : makerChatStore.sendMessage(+ SESSION_ID,+ 'late owner transition',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [attachment],+ undefined,+ { onRemoteOptimisticFailure: restore },+ ));++ expect(accepted).toBe(false);+ expect(deviceLinkInvoke).not.toHaveBeenCalled();+ release();+ expect(restore).toHaveBeenCalledTimes(1);+ },+ );++ it('shows a device-link steer bubble before preflight settles and dedupes its DB ack', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let resolvePreflight!: (value: boolean) => void;+ const preflight = new Promise<boolean>((resolve) => {+ resolvePreflight = resolve;+ });+ let queued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:steer') {+ queued = args[1] as AgentInputQueuedMessage;+ return true;+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ const steer = makerChatStore.steerMessage(+ SESSION_ID,+ 'remote steer',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { beforeEnqueue: () => preflight },+ );++ expect(deviceLinkInvoke.mock.calls.some(([, channel]) => channel === 'maker:input:steer')).toBe(+ false,+ );+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ content: 'remote steer', isPendingPersist: true }),+ ]);++ resolvePreflight(true);+ await expect(steer).resolves.toBe(true);+ const clientId = queued?.clientId;+ expect(clientId).toBeTruthy();++ emitDbMessageCreated({+ clientId: clientId!,+ role: 'user',+ content: 'remote steer',+ createdAt: '2026-08-02T00:00:00.000Z',+ });+ const messages = makerChatStore.getSnapshot(SESSION_ID).messages;+ expect(messages.filter((message) => message.clientId === clientId)).toHaveLength(1);+ expect(messages[0]?.isPendingPersist).toBeUndefined();+ });++ it('keeps an accepted device-link steer until a delayed DB ack is reconciled', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let queued: AgentInputQueuedMessage | undefined;+ let persisted = false;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:steer') {+ queued = args[1] as AgentInputQueuedMessage;+ return false;+ }+ if (channel === 'maker:input:get-projection') {+ return projection(SESSION_ID, { pendingQueue: queued ? [queued] : [] });+ }+ if (channel === 'local-db:messages:around-client-id') {+ if (!persisted) throw new Error('[NOT_FOUND] message not persisted yet');+ return [+ serverMessage({+ id: `row-${queued?.clientId}`,+ sessionId: SESSION_ID,+ clientId: queued?.clientId ?? 'missing',+ role: 'user',+ content: 'materialized steer',+ createdAt: '2026-08-02T00:00:00.000Z',+ }),+ ];+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'materialized steer',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ const clientId = queued?.clientId;+ expect(clientId).toBeTruthy();+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toEqual([+ expect.objectContaining({ clientId, text: 'materialized steer' }),+ ]);++ onInputProjection?.(projection(SESSION_ID));+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ clientId, content: 'materialized steer', isPendingPersist: true }),+ ]);++ vi.advanceTimersByTime(10_000);+ await flushPromises();+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ clientId, content: 'materialized steer', isPendingPersist: true }),+ ]);++ persisted = true;+ vi.advanceTimersByTime(10_000);+ await flushPromises();+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ clientId, content: 'materialized steer' }),+ ]);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0]?.isPendingPersist).toBeUndefined();+ });++ it('ignores a stale device-link queue projection after the DB message persists', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let queued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ queued = args[1] as AgentInputQueuedMessage;+ return projection(SESSION_ID, { pendingQueue: [queued] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'persisted before projection',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ const clientId = queued?.clientId;+ expect(clientId).toBeTruthy();++ emitDbMessageCreated({+ clientId: clientId!,+ role: 'user',+ content: 'persisted before projection',+ createdAt: '2026-08-02T00:00:00.000Z',+ });+ onInputProjection?.(projection(SESSION_ID, { pendingQueue: queued ? [queued] : [] }));++ const snapshot = makerChatStore.getSnapshot(SESSION_ID);+ expect(snapshot.pendingQueue).toHaveLength(0);+ expect(snapshot.messages.filter((message) => message.clientId === clientId)).toHaveLength(1);+ expect(snapshot.messages[0]?.isPendingPersist).toBeUndefined();+ });++ it('treats an enqueue reject as delivered when reconciliation finds the same clientId', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let queued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ queued = args[1] as AgentInputQueuedMessage;+ throw new Error('device-link timeout');+ }+ if (channel === 'maker:input:get-projection') {+ return projection(SESSION_ID, { pendingQueue: queued ? [queued] : [] });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'maybe delivered',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toEqual([+ expect.objectContaining({ clientId: queued?.clientId, text: 'maybe delivered' }),+ ]);+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBeNull();+ });++ it('treats an uncertain remote steer as accepted while its steering marker is present', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let queued: AgentInputQueuedMessage | undefined;+ let steerCalls = 0;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:steer') {+ steerCalls += 1;+ queued = args[1] as AgentInputQueuedMessage;+ throw new Error('[DEVICE_LINK_TIMEOUT] no result within 30000ms');+ }+ if (channel === 'maker:input:get-projection') {+ return projection(SESSION_ID, {+ steeringQueueClientIds: queued ? [queued.clientId] : [],+ });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'maybe accepted steer',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ expect(steerCalls).toBe(1);+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBeNull();+ });++ it('falls an ambiguous remote steer back to enqueue with the same clientId', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let steerCalls = 0;+ let enqueueCalls = 0;+ let queued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:steer') {+ steerCalls += 1;+ queued = args[1] as AgentInputQueuedMessage;+ throw new Error('[DEVICE_LINK_TIMEOUT] no result within 30000ms');+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ if (channel === 'local-db:messages:around-client-id') {+ throw new Error('[NOT_FOUND] Message 不存在');+ }+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ const fallback = args[1] as AgentInputQueuedMessage;+ expect(fallback.clientId).toBe(queued?.clientId);+ return projection(SESSION_ID, { pendingQueue: [fallback] });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'ambiguous steer',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);++ await flushPromises();++ expect(steerCalls).toBe(1);+ expect(enqueueCalls).toBe(1);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toEqual([+ expect.objectContaining({ clientId: queued?.clientId, text: 'ambiguous steer' }),+ ]);+ });++ it('reconciles an ambiguous steer after reconnect without invoking steer twice', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let online = false;+ let steerCalls = 0;+ let enqueueCalls = 0;+ let queued: AgentInputQueuedMessage | undefined;+ const onRemoteOptimisticFailure = vi.fn();+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:steer') {+ steerCalls += 1;+ queued = args[1] as AgentInputQueuedMessage;+ throw new Error('[DEVICE_LINK_TIMEOUT] no result within 30000ms');+ }+ if (channel === 'maker:input:get-projection') {+ if (!online) throw new Error('[DEVICE_LINK_NOT_CONNECTED] relay offline');+ return projection(SESSION_ID);+ }+ if (channel === 'local-db:messages:around-client-id') {+ if (!online) throw new Error('[DEVICE_LINK_NOT_CONNECTED] relay offline');+ throw new Error('[NOT_FOUND] Message 不存在');+ }+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ const fallback = args[1] as AgentInputQueuedMessage;+ expect(fallback.clientId).toBe(queued?.clientId);+ return projection(SESSION_ID, { pendingQueue: [fallback] });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'reconcile after reconnect',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ await flushPromises();++ // Unknown clear tokens are fenced before the first steer. While the relay+ // is offline the optimistic bubble remains local and the steer invoke is+ // deferred until a projection probe succeeds after reconnect.+ expect(steerCalls).toBe(0);+ expect(enqueueCalls).toBe(0);+ expect(onRemoteOptimisticFailure).not.toHaveBeenCalled();++ online = true;+ onDeviceLinkStatusChanged?.({ status: 'online' });+ await flushPromises();+ await flushPromises();+ await flushPromises();++ expect(steerCalls).toBe(1);+ expect(enqueueCalls).toBe(1);+ expect(onRemoteOptimisticFailure).not.toHaveBeenCalled();+ });++ it('lets a late DB ack retire an ambiguous steer without fallback or composer restore', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let queued: AgentInputQueuedMessage | undefined;+ let projectionCalls = 0;+ let resolveProjection!: (value: AgentInputProjection) => void;+ let resolvePersisted!: (value: Message[]) => void;+ let enqueueCalls = 0;+ const onRemoteOptimisticFailure = vi.fn();+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:steer') {+ queued = args[1] as AgentInputQueuedMessage;+ throw new Error('[DEVICE_LINK_NOT_CONNECTED] relay connection lost');+ }+ if (channel === 'maker:input:get-projection') {+ projectionCalls += 1;+ if (projectionCalls === 1) return projection(SESSION_ID);+ return new Promise<AgentInputProjection>((resolve) => {+ resolveProjection = resolve;+ });+ }+ if (channel === 'local-db:messages:around-client-id') {+ return new Promise<Message[]>((resolve) => {+ resolvePersisted = resolve;+ });+ }+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ return projection(SESSION_ID);+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'late persisted steer',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ await flushPromises();++ expect(queued).toBeDefined();+ emitDbMessageCreated({+ clientId: queued!.clientId,+ role: 'user',+ content: 'late persisted steer',+ createdAt: '2026-08-03T00:00:00.000Z',+ });+ resolveProjection(projection(SESSION_ID));+ resolvePersisted([]);+ await flushPromises();++ expect(enqueueCalls).toBe(0);+ expect(onRemoteOptimisticFailure).not.toHaveBeenCalled();+ const persisted = makerChatStore.getSnapshot(SESSION_ID).messages;+ expect(persisted).toEqual([expect.objectContaining({ clientId: queued?.clientId })]);+ expect(persisted[0]).not.toHaveProperty('isPendingPersist');+ });++ it('retires an unfenced steer when first numeric clear hydration races its dispatch', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ const clearBoundaryMs = Date.now() - 5_000;+ // The controller clock is ahead of the remote host. A wall-clock+ // comparison would incorrectly classify this pre-hydration record as+ // clear-after input.+ vi.setSystemTime(clearBoundaryMs + 10_000);+ let queued: AgentInputQueuedMessage | undefined;+ let resolveSteer!: (accepted: boolean) => void;+ const onRemoteOptimisticFailure = vi.fn();+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ if (channel === 'maker:input:steer') {+ queued = args[1] as AgentInputQueuedMessage;+ return new Promise<boolean>((resolve) => {+ resolveSteer = resolve;+ });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'pre-clear steer',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ await flushPromises();+ expect(queued).toBeDefined();+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ clientId: queued?.clientId, isPendingPersist: true }),+ ]);++ onInputProjection?.(projection(SESSION_ID, { clearBoundaryMs }));+ expect(onRemoteOptimisticFailure).toHaveBeenCalledWith(queued?.clientId, undefined);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);++ resolveSteer(true);+ await flushPromises();+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ });++ it('retires an unknown-token steer even while the first clear probe is in flight', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ const clearBoundaryMs = Date.parse('2026-08-03T00:00:00.000Z');+ let resolveProjection!: (value: AgentInputProjection) => void;+ let steerCalls = 0;+ let queued: AgentInputQueuedMessage | undefined;+ const onRemoteOptimisticFailure = vi.fn();+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:get-projection') {+ return new Promise<AgentInputProjection>((resolve) => {+ resolveProjection = resolve;+ });+ }+ if (channel === 'maker:input:steer') {+ steerCalls += 1;+ queued = args[1] as AgentInputQueuedMessage;+ return true;+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'probe still pending',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ await flushPromises();++ expect(steerCalls).toBe(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ isPendingPersist: true }),+ ]);++ onInputProjection?.(projection(SESSION_ID, { clearBoundaryMs }));+ expect(onRemoteOptimisticFailure).toHaveBeenCalledWith(expect.any(String), undefined);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);++ resolveProjection(projection(SESSION_ID, { clearBoundaryMs }));+ await flushPromises();+ expect(steerCalls).toBe(0);+ expect(queued).toBeUndefined();+ });++ it('rolls back only the failed device-link optimistic item when reconciliation is empty', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel) => {+ if (channel === 'maker:input:enqueue') throw new Error('definitely failed');+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'failed remote',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await flushPromises();+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBe('definitely failed');+ });++ it('keeps a remote message locally on NOT_CONNECTED and pumps it after relay recovery', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let online = false;+ let enqueueCount = 0;+ let queued: AgentInputQueuedMessage | undefined;+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ if (channel === 'maker:input:enqueue') {+ enqueueCount += 1;+ queued = args[1] as AgentInputQueuedMessage;+ if (!online) throw new Error('[NOT_CONNECTED] target offline');+ return projection(SESSION_ID, { pendingQueue: [queued] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'offline message',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ expect(enqueueCount).toBe(1);+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBeNull();+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toEqual([+ expect.objectContaining({ text: 'offline message', isPendingEnqueue: true }),+ ]);++ online = true;+ onDeviceLinkStatusChanged?.({ status: 'online' });+ await flushPromises();++ expect(enqueueCount).toBe(2);+ expect(deviceLinkInvoke).toHaveBeenLastCalledWith(+ 'device-1',+ 'maker:input:enqueue',+ expect.arrayContaining([SESSION_ID, expect.objectContaining({ clientId: queued?.clientId })]),+ );+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue[0]).toEqual(+ expect.objectContaining({ text: 'offline message' }),+ );+ expect(+ makerChatStore.getSnapshot(SESSION_ID).pendingQueue[0]?.isPendingEnqueue,+ ).toBeUndefined();+ });++ it('calls the composer recovery callback when a deferred remote send later fails permanently', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const recoveryUrl = 'cindy-media://blobs/recover-me.png';+ let enqueueAttempts = 0;+ let queued: AgentInputQueuedMessage | undefined;+ const onRemoteOptimisticFailure = vi.fn();+ const recoveryAttachment: AttachedFile = {+ id: 'recover-me-media',+ name: 'recover-me.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: recoveryUrl,+ };+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ if (channel === 'maker:input:enqueue') {+ enqueueAttempts += 1;+ queued = args[1] as AgentInputQueuedMessage;+ if (enqueueAttempts === 1) throw new Error('[NOT_CONNECTED] target offline');+ throw new Error('permission denied');+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'recover me',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [recoveryAttachment],+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ expect(queued?.text).toBe('recover me');+ expect(onRemoteOptimisticFailure).not.toHaveBeenCalled();+ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith([recoveryUrl]);+ const reportCallCountBeforeFailure = vi.mocked(setRemoteOptimisticAttachmentUrls).mock.calls+ .length;++ onDeviceLinkStatusChanged?.({ status: 'online' });+ await flushPromises();++ expect(enqueueAttempts).toBe(2);+ expect(onRemoteOptimisticFailure).toHaveBeenCalledWith(queued?.clientId, expect.any(Error));+ expect(onRemoteOptimisticFailure.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(setRemoteOptimisticAttachmentUrls).mock.invocationCallOrder[+ reportCallCountBeforeFailure+ ]!,+ );+ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith([]);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toHaveLength(0);+ });++ it('restores a remote composer without an error when clear supersedes input preparation', async () => {+ let enqueueAttempts = 0;+ let projectionRequests = 0;+ let queued: AgentInputQueuedMessage | undefined;+ const onRemoteOptimisticFailure = vi.fn();+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ if (channel === 'maker:input:enqueue') {+ enqueueAttempts += 1;+ queued = args[1] as AgentInputQueuedMessage;+ throw new Error(+ 'Error invoking remote method: Error: [PRECONDITION_FAILED] REMOTE_OPTIMISTIC_INPUT_SUPERSEDED: input preparation was superseded',+ );+ }+ if (channel === 'maker:input:get-projection') {+ projectionRequests += 1;+ return projection(SESSION_ID);+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'superseded remote send',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ await flushPromises();++ expect(enqueueAttempts).toBe(1);+ // The first remote send performs one ordinary slice projection sync. The+ // superseded enqueue must not add a second reconciliation request.+ expect(projectionRequests).toBe(1);+ expect(onRemoteOptimisticFailure).toHaveBeenCalledWith(queued?.clientId, undefined);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBeNull();++ onDeviceLinkStatusChanged?.({ status: 'online' });+ await flushPromises();+ expect(enqueueAttempts).toBe(1);+ expect(projectionRequests).toBe(1);+ });++ it('does not re-enqueue a steer when clear supersedes its preparation', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let steerAttempts = 0;+ let enqueueAttempts = 0;+ let queued: AgentInputQueuedMessage | undefined;+ const channels: string[] = [];+ const onRemoteOptimisticFailure = vi.fn();+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ channels.push(channel);+ if (channel === 'maker:input:steer') {+ steerAttempts += 1;+ queued = args[1] as AgentInputQueuedMessage;+ throw new Error(+ 'Error invoking remote method: Error: [PRECONDITION_FAILED] REMOTE_OPTIMISTIC_INPUT_SUPERSEDED: input preparation was superseded',+ );+ }+ if (channel === 'maker:input:enqueue') {+ enqueueAttempts += 1;+ return projection(SESSION_ID);+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'superseded remote steer',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ await flushPromises();++ expect(steerAttempts).toBe(1);+ expect(enqueueAttempts).toBe(0);+ expect(channels).not.toContain('local-db:messages:around-client-id');+ expect(onRemoteOptimisticFailure).toHaveBeenCalledWith(queued?.clientId, undefined);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBeNull();++ onDeviceLinkStatusChanged?.({ status: 'online' });+ await flushPromises();+ expect(steerAttempts).toBe(1);+ expect(enqueueAttempts).toBe(0);+ });++ it('cancels an old-owner outbox before publishing the next data owner', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const ownerAttachmentUrl = 'cindy-media://blobs/owner-a-pending.png';+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let resolvePreflight!: (value: boolean) => void;+ const preflight = new Promise<boolean>((resolve) => {+ resolvePreflight = resolve;+ });+ const restore = vi.fn();+ const ownerAttachment: AttachedFile = {+ id: 'owner-a-pending-media',+ name: 'owner-a-pending.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: ownerAttachmentUrl,+ };+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel) => {+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'owner-a pending',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [ownerAttachment],+ undefined,+ { beforeEnqueue: () => preflight, onRemoteOptimisticFailure: restore },+ ),+ ).resolves.toBe(true);+ const clientId = makerChatStore.getSnapshot(SESSION_ID).pendingQueue[0]?.clientId;+ expect(clientId).toBeTruthy();+ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith([ownerAttachmentUrl]);+ const reportCallCountBeforeBoundary = vi.mocked(setRemoteOptimisticAttachmentUrls).mock.calls+ .length;++ makerChatStore.cancelRemoteOptimisticSendsForDataOwnerBoundary();+ setDataOwnerGeneration('owner-b');++ expect(restore).toHaveBeenCalledWith(clientId, expect.any(Error));+ expect(restore.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(setRemoteOptimisticAttachmentUrls).mock.invocationCallOrder[+ reportCallCountBeforeBoundary+ ]!,+ );+ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith([]);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toHaveLength(0);++ resolvePreflight(true);+ await flushPromises();+ onDeviceLinkStatusChanged?.({ status: 'online' });+ await flushPromises();+ expect(+ deviceLinkInvoke.mock.calls.some(([, channel]) => channel === 'maker:input:enqueue'),+ ).toBe(false);+ expect(restore).toHaveBeenCalledTimes(1);+ });++ it('drops a standalone late projection when the data owner changes', async () => {+ remoteProjectsStore.setDeviceSessions('device-1', 'Test Mac', [+ { id: SESSION_ID, status: 'active', title: 'Remote task' } as Session,+ ]);+ expect(getStickySessionDeviceId(SESSION_ID)).toBe('device-1');+ remoteProjectsStore.clear();++ onInputProjection?.(+ projection(SESSION_ID, {+ error: 'new-owner-state',+ queueInteractionLocks: ['new-owner-lock'],+ steeringQueueClientIds: ['already-steering'],+ }),+ );++ let resolveProjection!: (value: AgentInputProjection) => void;+ deviceLinkInvoke.mockImplementation(async (deviceId, channel) => {+ expect(deviceId).toBe('device-1');+ if (channel === 'maker:input:get-projection') {+ return new Promise<AgentInputProjection>((resolve) => {+ resolveProjection = resolve;+ });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'late projection probe',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(false);+ await flushPromises();+ expect(deviceLinkInvoke).toHaveBeenCalledWith('device-1', 'maker:input:get-projection', [+ SESSION_ID,+ ]);++ makerChatStore.cancelRemoteOptimisticSendsForDataOwnerBoundary();+ setDataOwnerGeneration('owner-b');+ resolveProjection(+ projection(SESSION_ID, {+ error: 'old-owner-state',+ queueInteractionLocks: ['old-owner-lock'],+ steeringQueueClientIds: [],+ }),+ );+ await flushPromises();++ expect(makerChatStore.getSnapshot(SESSION_ID).error).toBe('new-owner-state');+ expect(makerChatStore.getSnapshot(SESSION_ID).queueInteractionLocks).toEqual([+ 'new-owner-lock',+ ]);+ expect(makerChatStore.getSnapshot(SESSION_ID).steeringQueueClientIds).toEqual([+ 'already-steering',+ ]);+ expect(input.getProjection).not.toHaveBeenCalled();+ });++ it('retries a deferred remote steer through steer instead of degrading it to enqueue', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let online = false;+ const channels: string[] = [];+ deviceLinkInvoke.mockImplementation(async (deviceId, channel) => {+ expect(deviceId).toBe('device-1');+ channels.push(channel);+ if (channel === 'maker:input:steer') {+ if (!online) throw new Error('[DEVICE_LINK_DEVICE_OFFLINE] target offline');+ return true;+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'steer me',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ expect(channels).toContain('maker:input:steer');+ expect(channels).not.toContain('maker:input:enqueue');++ online = true;+ onDeviceLinkStatusChanged?.({ status: 'online' });+ await flushPromises();++ expect(channels.filter((channel) => channel === 'maker:input:steer')).toHaveLength(2);+ expect(channels).not.toContain('maker:input:enqueue');+ });++ it('keeps an ambiguous disconnected steer accepted when the same clientId is already persisted', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let queued: AgentInputQueuedMessage | undefined;+ let steerCalls = 0;+ let enqueueCalls = 0;+ const onRemoteOptimisticFailure = vi.fn();+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:steer') {+ steerCalls += 1;+ queued = args[1] as AgentInputQueuedMessage;+ throw new Error('[DEVICE_LINK_NOT_CONNECTED] relay connection lost');+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ if (channel === 'local-db:messages:around-client-id') {+ return [+ serverMessage({+ id: 'persisted-ambiguous-steer',+ sessionId: SESSION_ID,+ clientId: queued!.clientId,+ role: 'user',+ content: 'ambiguous disconnect',+ createdAt: '2026-08-02T00:00:00.000Z',+ }),+ ];+ }+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ return projection(SESSION_ID);+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.steerMessage(+ SESSION_ID,+ 'ambiguous disconnect',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ await flushPromises();++ expect(steerCalls).toBe(1);+ expect(enqueueCalls).toBe(0);+ expect(onRemoteOptimisticFailure).not.toHaveBeenCalled();+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ clientId: queued?.clientId, isPendingPersist: true }),+ ]);+ });++ it('settles multiple permanent failures through composer callbacks in FIFO order', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let enqueueAttempts = 0;+ const permanentlyFailedClientIds: string[] = [];+ const onRemoteOptimisticFailure = vi.fn();+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ enqueueAttempts += 1;+ if (enqueueAttempts === 1) throw new Error('[NOT_CONNECTED] target offline');+ permanentlyFailedClientIds.push((args[1] as AgentInputQueuedMessage).clientId);+ throw new Error('permission denied');+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'first failed message',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'second failed message',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure },+ ),+ ).resolves.toBe(true);+ onDeviceLinkStatusChanged?.({ status: 'online' });+ await flushPromises();++ expect(permanentlyFailedClientIds).toHaveLength(2);+ expect(onRemoteOptimisticFailure.mock.calls.map(([clientId]) => clientId)).toEqual(+ permanentlyFailedClientIds,+ );+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ });++ it('does not LRU-evict a remote optimistic message while its preflight is pending', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let resolvePreflight!: (value: boolean) => void;+ const preflight = new Promise<boolean>((resolve) => {+ resolvePreflight = resolve;+ });+ let enqueueCalls = 0;+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ const item = args[1] as AgentInputQueuedMessage;+ return projection(SESSION_ID, { pendingQueue: [item] });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ const send = makerChatStore.sendMessage(+ SESSION_ID,+ 'must survive cache pressure',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { beforeEnqueue: () => preflight },+ );+ const optimisticSnapshot = makerChatStore.getSnapshot(SESSION_ID);+ expect([+ ...optimisticSnapshot.messages,+ ...optimisticSnapshot.pendingQueue.map((item) => item.chatMessage),+ ]).toEqual([+ expect.objectContaining({ content: 'must survive cache pressure', isPendingPersist: true }),+ ]);++ for (const sessionId of LRU_SESSION_IDS) makerChatStore.getSnapshot(sessionId);+ resolvePreflight(true);++ await expect(send).resolves.toBe(true);+ expect(enqueueCalls).toBe(1);+ });++ it('does not LRU-evict a remote optimistic message while its annotation is materializing', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let resolveMaterialize!: (value: {+ url: string;+ name: string;+ ext: string;+ mimeType: string;+ size: number;+ }) => void;+ vi.mocked(window.electronAPI.cacheMediaForSession).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveMaterialize = resolve;+ }),+ );+ let enqueueCalls = 0;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ const item = args[1] as AgentInputQueuedMessage;+ return projection(SESSION_ID, { pendingQueue: [item] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });+ const attachment: AttachedFile = {+ id: 'lru-materializing-source',+ name: 'lru-materializing.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: 'xdt-image://source/lru-materializing.png',+ cacheUrlShared: true,+ };++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'must survive materialization pressure',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [attachment],+ ),+ ).resolves.toBe(true);+ await flushPromises();+ for (const sessionId of LRU_SESSION_IDS) makerChatStore.getSnapshot(sessionId);++ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({+ content: 'must survive materialization pressure',+ isPendingPersist: true,+ }),+ ]);++ resolveMaterialize({+ url: 'xdt-image://text-delta-batching/lru-private.png',+ name: 'lru-private.png',+ ext: '.png',+ mimeType: 'image/png',+ size: 1,+ });+ await flushPromises();+ await flushPromises();+ expect(enqueueCalls).toBe(1);+ });++ it('does not revive or dispatch a materializing remote message after purge', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let resolveMaterialize!: (value: {+ url: string;+ name: string;+ ext: string;+ mimeType: string;+ size: number;+ }) => void;+ vi.mocked(window.electronAPI.cacheMediaForSession).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveMaterialize = resolve;+ }),+ );+ let enqueueCalls = 0;+ const restore = vi.fn();+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ return projection(SESSION_ID, {+ pendingQueue: [args[1] as AgentInputQueuedMessage],+ });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });+ const attachment: AttachedFile = {+ id: 'purged-materializing-source',+ name: 'purged-materializing.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: 'xdt-image://source/purged-materializing.png',+ cacheUrlShared: true,+ };++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'must stay purged',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [attachment],+ undefined,+ { onRemoteOptimisticFailure: restore },+ ),+ ).resolves.toBe(true);+ await flushPromises();+ makerChatStore.purgeSession(SESSION_ID);++ resolveMaterialize({+ url: 'xdt-image://text-delta-batching/purged-private.png',+ name: 'purged-private.png',+ ext: '.png',+ mimeType: 'image/png',+ size: 1,+ });+ await flushPromises();++ expect(enqueueCalls).toBe(0);+ expect(restore).toHaveBeenCalledTimes(1);+ expect(isRemoteOptimisticSessionPurgedError(restore.mock.calls[0]?.[1])).toBe(true);+ expect(makerChatStore.__hasSessionForTest(SESSION_ID)).toBe(false);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toHaveLength(0);+ });++ it.each(['archived', 'deleted'] as const)(+ 'cancels a background offline outbox when the controlled task is %s',+ async (status) => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let resolvePreflight!: (value: boolean) => void;+ const preflight = new Promise<boolean>((resolve) => {+ resolvePreflight = resolve;+ });+ const restore = vi.fn();+ let enqueueCalls = 0;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel) => {+ if (channel === 'maker:input:enqueue') enqueueCalls += 1;+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'must not outlive remote task',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ {+ beforeEnqueue: () => preflight,+ onRemoteOptimisticFailure: restore,+ },+ ),+ ).resolves.toBe(true);++ onRemotePush?.({+ deviceId: 'device-1',+ channel: 'local-db:sessions:patched',+ payload: { sessionId: SESSION_ID, patch: { status } },+ });+ resolvePreflight(true);+ await flushPromises();++ expect(enqueueCalls).toBe(0);+ expect(restore).toHaveBeenCalledTimes(1);+ expect(isRemoteOptimisticSessionPurgedError(restore.mock.calls[0]?.[1])).toBe(true);+ expect(makerChatStore.__hasSessionForTest(SESSION_ID)).toBe(false);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toHaveLength(0);+ },+ );++ it.each(['archived', 'deleted'] as const)(+ 'keeps a remotely %s task purged when late session frames arrive',+ (status) => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });++ onRemotePush?.({+ deviceId: 'device-1',+ channel: 'local-db:sessions:patched',+ payload: { sessionId: SESSION_ID, patch: { status } },+ });+ expect(makerChatStore.__hasSessionForTest(SESSION_ID)).toBe(false);++ onRemotePush?.({+ deviceId: 'device-1',+ channel: 'local-db:messages:created',+ payload: {+ sessionId: SESSION_ID,+ message: serverMessage({+ id: 'late-row',+ sessionId: SESSION_ID,+ clientId: 'late-user',+ role: 'user',+ content: 'late message',+ createdAt: '2026-08-02T00:00:00.000Z',+ }),+ },+ });+ onRemotePush?.({+ deviceId: 'device-1',+ channel: 'maker:event',+ payload: {+ sessionId: SESSION_ID,+ event: {+ type: 'status',+ data: {+ status: 'running',+ isRunning: true,+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ },+ },+ },+ });+ onRemotePush?.({+ deviceId: 'device-1',+ channel: 'maker:input:projection',+ payload: projection(SESSION_ID),+ });+ expect(makerChatStore.__hasSessionForTest(SESSION_ID)).toBe(false);++ if (status === 'archived') {+ remoteProjectsStore.setDeviceSessions('device-1', 'Test Mac', [+ {+ id: SESSION_ID,+ status: 'active',+ title: 'Restored task',+ } as Session,+ ]);+ onRemotePush?.({+ deviceId: 'device-1',+ channel: 'local-db:messages:created',+ payload: {+ sessionId: SESSION_ID,+ message: serverMessage({+ id: 'restored-row',+ sessionId: SESSION_ID,+ clientId: 'restored-user',+ role: 'user',+ content: 'after unarchive',+ createdAt: '2026-08-02T00:01:00.000Z',+ }),+ },+ });+ expect(makerChatStore.__hasSessionForTest(SESSION_ID)).toBe(true);+ }+ },+ );++ it('cancels a remote optimistic send that is still in preflight when the session is cleared', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let resolvePreflight!: (value: boolean) => void;+ const preflight = new Promise<boolean>((resolve) => {+ resolvePreflight = resolve;+ });+ let enqueueCalls = 0;+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ if (channel === 'maker:input:clear-session') return projection(SESSION_ID);+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ const item = args[1] as AgentInputQueuedMessage;+ return projection(SESSION_ID, { pendingQueue: [item] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ const send = makerChatStore.sendMessage(+ SESSION_ID,+ 'must be cancelled by clear',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { beforeEnqueue: () => preflight },+ );+ makerChatStore.clearSession(SESSION_ID);+ await flushPromises();+ resolvePreflight(true);++ await expect(send).resolves.toBe(true);+ await flushPromises();+ expect(enqueueCalls).toBe(0);+ });++ it.each(['send', 'steer'] as const)(+ 'rejects a pre-registration %s continuation after clear and leaves one caller-owned restore',+ async (deliveryMode) => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const restore = vi.fn();+ const release = makerChatStore.beginRemoteOptimisticComposerTransition(+ SESSION_ID,+ undefined,+ restore,+ );+ const dispatchedChannels: string[] = [];+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel) => {+ dispatchedChannels.push(channel);+ if (channel === 'maker:input:clear-session') return projection(SESSION_ID);+ if (channel === 'maker:close-session') return undefined;+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ makerChatStore.clearSession(SESSION_ID);+ await flushPromises();++ const accepted = await (deliveryMode === 'steer'+ ? makerChatStore.steerMessage(+ SESSION_ID,+ 'late clear transition',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure: restore },+ )+ : makerChatStore.sendMessage(+ SESSION_ID,+ 'late clear transition',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { onRemoteOptimisticFailure: restore },+ ));++ expect(accepted).toBe(false);+ expect(dispatchedChannels).not.toContain('maker:input:enqueue');+ expect(dispatchedChannels).not.toContain('maker:input:steer');+ if (!accepted) restore('caller-owned-restore');+ release();+ expect(restore).toHaveBeenCalledTimes(1);+ },+ );++ it('keeps a send local while clear is waiting for its remote guard', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let resolveClear!: (value: AgentInputProjection) => void;+ let enqueueCalls = 0;+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ if (channel === 'maker:input:clear-session') {+ return new Promise<AgentInputProjection>((resolve) => {+ resolveClear = resolve;+ });+ }+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ return projection(SESSION_ID, { pendingQueue: [args[1] as AgentInputQueuedMessage] });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ makerChatStore.clearSession(SESSION_ID);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'blocked during clear',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ expect(enqueueCalls).toBe(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ content: 'blocked during clear', isPendingPersist: true }),+ ]);++ resolveClear(projection(SESSION_ID));+ await flushPromises();+ await flushPromises();+ expect(enqueueCalls).toBe(1);+ });++ it('keeps a clear-fenced send local after invoke rejection and dispatches it on reconnect ACK', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let clearAttempts = 0;+ let online = false;+ let clearedAt: string | undefined;+ let enqueueCalls = 0;+ let enqueueOpts: unknown;+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ if (channel === 'maker:input:clear-session') {+ clearAttempts += 1;+ clearedAt = args[1] as string;+ if (clearAttempts === 1) throw new Error('[DEVICE_LINK_DEVICE_OFFLINE] offline');+ if (!online) throw new Error('[DEVICE_LINK_DEVICE_OFFLINE] offline');+ // The controller and controlled host may have skewed clocks. The+ // host-owned boundary is still authoritative even when it is earlier+ // than the controller's request timestamp.+ return projection(SESSION_ID, { clearBoundaryMs: Date.parse(clearedAt) - 10_000 });+ }+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ enqueueOpts = args[2];+ return projection(SESSION_ID, {+ clearBoundaryMs: Date.parse(clearedAt!) - 10_000,+ pendingQueue: [args[1] as AgentInputQueuedMessage],+ });+ }+ if (channel === 'maker:input:get-projection') {+ return projection(SESSION_ID, { clearBoundaryMs: Date.parse(clearedAt!) - 10_000 });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await makerChatStore.clearSession(SESSION_ID);+ expect(clearAttempts).toBe(1);++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'send after offline clear',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await flushPromises();++ expect(enqueueCalls).toBe(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ content: 'send after offline clear', isPendingPersist: true }),+ ]);++ online = true;+ onPresenceChanged?.({ deviceId: 'device-1', online: true });+ await flushPromises();+ await flushPromises();++ // Presence and projection-reseed callbacks may race and request the same+ // definitely-undelivered clear more than once; the send must still settle+ // only after an ACK, regardless of that duplicate retry trigger.+ expect(clearAttempts).toBeGreaterThanOrEqual(2);+ expect(enqueueCalls).toBe(1);+ expect(enqueueOpts).toEqual({+ sendAtMs: expect.any(Number),+ expectedClearBoundaryMs: Date.parse(clearedAt!) - 10_000,+ });+ });++ it('reconciles an ambiguous clear response loss before retrying the destructive clear', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const baselineBoundary = Date.parse('2026-08-03T00:00:00.000Z');+ const appliedBoundary = baselineBoundary + 1_000;+ onInputProjection?.(projection(SESSION_ID, { clearBoundaryMs: baselineBoundary }));+ let online = false;+ let clearAttempts = 0;+ let projectionProbes = 0;+ let enqueueCalls = 0;+ let enqueueOpts: unknown;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:clear-session') {+ clearAttempts += 1;+ if (clearAttempts === 1) {+ throw new Error('[DEVICE_LINK_NOT_CONNECTED] response lost after host clear');+ }+ return projection(SESSION_ID, { clearBoundaryMs: appliedBoundary + clearAttempts });+ }+ if (channel === 'maker:input:get-projection') {+ projectionProbes += 1;+ if (!online) throw new Error('[DEVICE_LINK_NOT_CONNECTED] host still offline');+ return projection(SESSION_ID, { clearBoundaryMs: appliedBoundary });+ }+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ enqueueOpts = args[2];+ return projection(SESSION_ID, {+ clearBoundaryMs: appliedBoundary,+ pendingQueue: [args[1] as AgentInputQueuedMessage],+ });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await makerChatStore.clearSession(SESSION_ID);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'send after lost clear ACK',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ expect(enqueueCalls).toBe(0);++ await flushPromises();+ projectionProbes = 0;+ online = true;+ onPresenceChanged?.({ deviceId: 'device-1', online: true });+ await flushPromises();+ await flushPromises();++ expect(projectionProbes).toBe(1);+ expect(clearAttempts).toBe(1);+ expect(enqueueCalls).toBe(1);+ expect(enqueueOpts).toEqual({+ sendAtMs: expect.any(Number),+ // The queued item captured the pre-clear token. If the host rejects it,+ // the normal send path re-probes and refreshes the token before retrying.+ expectedClearBoundaryMs: baselineBoundary,+ });+ });++ it('does not acknowledge a pending clear from an equal stale boundary replay', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const baselineBoundary = Date.parse('2026-08-03T00:00:00.000Z');+ onInputProjection?.(projection(SESSION_ID, { clearBoundaryMs: baselineBoundary }));+ let clearAttempts = 0;+ let enqueueCalls = 0;+ let online = false;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:clear-session') {+ clearAttempts += 1;+ throw new Error('[DEVICE_LINK_NOT_CONNECTED] response lost after host clear');+ }+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ return projection(SESSION_ID, {+ clearBoundaryMs: baselineBoundary,+ pendingQueue: [args[1] as AgentInputQueuedMessage],+ });+ }+ if (channel === 'maker:input:get-projection') {+ if (!online) throw new Error('[DEVICE_LINK_NOT_CONNECTED] host still offline');+ return projection(SESSION_ID, { clearBoundaryMs: baselineBoundary });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await makerChatStore.clearSession(SESSION_ID);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'still fenced after stale replay',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);++ onInputProjection?.(projection(SESSION_ID, { clearBoundaryMs: baselineBoundary }));+ await flushPromises();++ expect(clearAttempts).toBe(1);+ expect(enqueueCalls).toBe(0);+ });++ it('retries clear only after a projection proves the first attempt was not applied', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const baselineBoundary = Date.parse('2026-08-03T00:00:00.000Z');+ const appliedBoundary = baselineBoundary + 1_000;+ onInputProjection?.(projection(SESSION_ID, { clearBoundaryMs: baselineBoundary }));+ let clearAttempts = 0;+ let projectionProbes = 0;+ let enqueueCalls = 0;+ let online = false;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:clear-session') {+ clearAttempts += 1;+ if (clearAttempts === 1) {+ throw new Error('[DEVICE_LINK_NOT_CONNECTED] request delivery uncertain');+ }+ return projection(SESSION_ID, { clearBoundaryMs: appliedBoundary });+ }+ if (channel === 'maker:input:get-projection') {+ projectionProbes += 1;+ if (!online) throw new Error('[DEVICE_LINK_NOT_CONNECTED] host still offline');+ return projection(SESSION_ID, { clearBoundaryMs: baselineBoundary });+ }+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ return projection(SESSION_ID, {+ clearBoundaryMs: appliedBoundary,+ pendingQueue: [args[1] as AgentInputQueuedMessage],+ });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await makerChatStore.clearSession(SESSION_ID);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'send after proved retry',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);++ await flushPromises();+ projectionProbes = 0;+ online = true;+ onPresenceChanged?.({ deviceId: 'device-1', online: true });+ await flushPromises();+ await flushPromises();+ await flushPromises();++ expect(projectionProbes).toBe(1);+ expect(clearAttempts).toBe(2);+ expect(enqueueCalls).toBe(1);+ });++ it('keeps an ambiguous clear fenced when the reconciliation projection also fails', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const baselineBoundary = Date.parse('2026-08-03T00:00:00.000Z');+ onInputProjection?.(projection(SESSION_ID, { clearBoundaryMs: baselineBoundary }));+ let clearAttempts = 0;+ let projectionProbes = 0;+ let enqueueCalls = 0;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:clear-session') {+ clearAttempts += 1;+ if (clearAttempts === 1) {+ throw new Error('[DEVICE_LINK_NOT_CONNECTED] request delivery uncertain');+ }+ return projection(SESSION_ID, { clearBoundaryMs: baselineBoundary + 1_000 });+ }+ if (channel === 'maker:input:get-projection') {+ projectionProbes += 1;+ throw new Error('[DEVICE_LINK_NOT_CONNECTED] projection unavailable');+ }+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ return projection(SESSION_ID, {+ pendingQueue: [args[1] as AgentInputQueuedMessage],+ });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await makerChatStore.clearSession(SESSION_ID);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'still fenced after failed probe',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);++ onPresenceChanged?.({ deviceId: 'device-1', online: true });+ await flushPromises();+ await flushPromises();++ expect(projectionProbes).toBeGreaterThanOrEqual(1);+ expect(clearAttempts).toBe(1);+ expect(enqueueCalls).toBe(0);+ });++ it('accepts a direct clear response even when the host boundary equals the baseline', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const baselineBoundary = Date.parse('2026-08-03T00:00:00.000Z');+ onInputProjection?.(projection(SESSION_ID, { clearBoundaryMs: baselineBoundary }));+ let enqueueCalls = 0;+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:clear-session') {+ return projection(SESSION_ID, { clearBoundaryMs: baselineBoundary });+ }+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:enqueue') {+ enqueueCalls += 1;+ return projection(SESSION_ID, {+ clearBoundaryMs: baselineBoundary,+ pendingQueue: [args[1] as AgentInputQueuedMessage],+ });+ }+ if (channel === 'maker:input:get-projection') {+ return projection(SESSION_ID, { clearBoundaryMs: baselineBoundary });+ }+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await makerChatStore.clearSession(SESSION_ID);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'send after same-millisecond clear',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await flushPromises();++ expect(enqueueCalls).toBe(1);+ });++ it('does not reset a remote owner fence for repeated online presence updates', () => {+ const deviceId = 'device-1';+ remoteProjectsStore.setDeviceSessions(deviceId, 'Test Mac', [+ { id: SESSION_ID, status: 'active', title: 'initial' } as Session,+ ]);++ // The first online edge permits a restarted controlled process to start at+ // any local generation; subsequent online=true snapshots must not reopen+ // the fence (busy/name/settings updates use the same snapshot shape).+ onPresenceChanged?.({ deviceId, online: true });+ onRemotePush?.({+ deviceId,+ channel: 'local-db:sessions:patched',+ payload: { sessionId: SESSION_ID, patch: { title: 'generation-5' } },+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 5 },+ });+ expect(remoteProjectsStore.getDeviceSessions(deviceId)[0]?.title).toBe('generation-5');++ onPresenceChanged?.({ deviceId, online: true });+ onRemotePush?.({+ deviceId,+ channel: 'local-db:sessions:patched',+ payload: { sessionId: SESSION_ID, patch: { title: 'stale-generation-4' } },+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 4 },+ });+ expect(remoteProjectsStore.getDeviceSessions(deviceId)[0]?.title).toBe('generation-5');++ // A real offline -> online edge represents a possible controlled-process+ // restart, so the next lower generation is accepted after the reset.+ onPresenceChanged?.({ deviceId, online: false });+ onPresenceChanged?.({ deviceId, online: true });+ onRemotePush?.({+ deviceId,+ channel: 'local-db:sessions:patched',+ payload: { sessionId: SESSION_ID, patch: { title: 'generation-1-after-restart' } },+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 },+ });+ expect(remoteProjectsStore.getDeviceSessions(deviceId)[0]?.title).toBe(+ 'generation-1-after-restart',+ );+ });++ it('rejects stale local-owner frames before they can advance the remote fence', () => {+ const deviceId = 'device-1';+ remoteProjectsStore.setDeviceSessions(deviceId, 'Test Mac', [+ { id: SESSION_ID, status: 'active', title: 'initial' } as Session,+ ]);+ setDataOwnerGeneration('owner-a', 2);++ const stalePush = {+ deviceId,+ channel: 'local-db:sessions:patched',+ payload: { sessionId: SESSION_ID, patch: { title: 'stale' } },+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 5 },+ };+ onRemotePush?.(stalePush, { dataOwnerId: 'owner-a', ownerGeneration: 1 });+ expect(remoteProjectsStore.getDeviceSessions(deviceId)[0]?.title).toBe('initial');++ onRemotePush?.(+ {+ ...stalePush,+ payload: { sessionId: SESSION_ID, patch: { title: 'updated' } },+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 },+ },+ { dataOwnerId: 'owner-a', ownerGeneration: 2 },+ );+ expect(remoteProjectsStore.getDeviceSessions(deviceId)[0]?.title).toBe('updated');+ });++ it.each(['send', 'steer'] as const)(+ 'discards an already-accepted annotated %s when clear wins before materialization',+ async (deliveryMode) => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ if (deliveryMode === 'steer') {+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ }+ let resolveMaterialize!: (value: {+ url: string;+ name: string;+ ext: string;+ mimeType: string;+ size: number;+ }) => void;+ vi.mocked(window.electronAPI.cacheMediaForSession).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveMaterialize = resolve;+ }),+ );+ const dispatchedChannels: string[] = [];+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel) => {+ dispatchedChannels.push(channel);+ if (channel === 'maker:input:clear-session') return projection(SESSION_ID);+ if (channel === 'maker:close-session') return undefined;+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });+ const sharedAttachment: AttachedFile = {+ id: 'shared-annotation-source',+ name: 'shared.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: 'xdt-image://source/shared.png',+ cacheUrlShared: true,+ };+ const restore = vi.fn();++ const pending =+ deliveryMode === 'steer'+ ? makerChatStore.steerMessage(+ SESSION_ID,+ 'late steer',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [sharedAttachment],+ undefined,+ { onRemoteOptimisticFailure: restore },+ )+ : makerChatStore.sendMessage(+ SESSION_ID,+ 'late send',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [sharedAttachment],+ undefined,+ { onRemoteOptimisticFailure: restore },+ );+ await flushPromises();+ expect(window.electronAPI.cacheMediaForSession).toHaveBeenCalledTimes(1);+ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith([sharedAttachment.url]);+ await expect(pending).resolves.toBe(true);++ makerChatStore.clearSession(SESSION_ID);+ await flushPromises();+ resolveMaterialize({+ url: 'xdt-image://text-delta-batching/private.png',+ name: 'private.png',+ ext: '.png',+ mimeType: 'image/png',+ size: 1,+ });++ await flushPromises();+ expect(restore).not.toHaveBeenCalled();+ expect(setRemoteOptimisticAttachmentUrls).toHaveBeenLastCalledWith([]);+ expect(dispatchedChannels).not.toContain('maker:input:enqueue');+ expect(dispatchedChannels).not.toContain('maker:input:steer');+ },+ );++ it.each(['send', 'steer'] as const)(+ 'restores an old-owner annotated %s before its late materialization can dispatch',+ async (deliveryMode) => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ if (deliveryMode === 'steer') {+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ }+ let resolveMaterialize!: (value: {+ url: string;+ name: string;+ ext: string;+ mimeType: string;+ size: number;+ }) => void;+ vi.mocked(window.electronAPI.cacheMediaForSession).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveMaterialize = resolve;+ }),+ );+ const sharedAttachment: AttachedFile = {+ id: 'old-owner-annotation-source',+ name: 'old-owner.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: 'xdt-image://source/old-owner.png',+ cacheUrlShared: true,+ };+ const restore = vi.fn();++ const pending =+ deliveryMode === 'steer'+ ? makerChatStore.steerMessage(+ SESSION_ID,+ 'old-owner steer',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [sharedAttachment],+ undefined,+ { onRemoteOptimisticFailure: restore },+ )+ : makerChatStore.sendMessage(+ SESSION_ID,+ 'old-owner send',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [sharedAttachment],+ undefined,+ { onRemoteOptimisticFailure: restore },+ );+ await flushPromises();+ expect(window.electronAPI.cacheMediaForSession).toHaveBeenCalledTimes(1);+ await expect(pending).resolves.toBe(true);++ makerChatStore.cancelRemoteOptimisticSendsForDataOwnerBoundary();+ expect(restore).toHaveBeenCalledWith(expect.any(String), expect.any(Error));+ setDataOwnerGeneration('owner-b');+ resolveMaterialize({+ url: 'xdt-image://text-delta-batching/private.png',+ name: 'private.png',+ ext: '.png',+ mimeType: 'image/png',+ size: 1,+ });++ await flushPromises();+ expect(restore).toHaveBeenCalledTimes(1);+ expect(deviceLinkInvoke).not.toHaveBeenCalled();+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toHaveLength(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingQueue).toHaveLength(0);+ },+ );++ it('drains multiple remote messages in FIFO order and keeps the pinned route after mirror clear', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let online = false;+ const sentTexts: string[] = [];+ deviceLinkInvoke.mockImplementation(async (deviceId, channel, args) => {+ expect(deviceId).toBe('device-1');+ if (channel === 'maker:input:enqueue') {+ const item = args[1] as AgentInputQueuedMessage;+ if (!online) throw new Error('[DEVICE_OFFLINE] target offline');+ sentTexts.push(item.text);+ return projection(SESSION_ID, { pendingQueue: [item] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'first offline',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'second offline',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ expect(sentTexts).toEqual([]);++ online = true;+ // Clearing the live shard simulates the relay reconnect window. The+ // sticky origin must still route the pump to device-1, never local maker.+ remoteProjectsStore.clear();+ onPresenceChanged?.({ deviceId: 'device-1', online: true });+ await flushPromises();++ expect(sentTexts).toEqual(['first offline', 'second offline']);+ expect(+ deviceLinkInvoke.mock.calls+ .filter(([, channel]) => channel === 'maker:input:enqueue')+ .every(([deviceId]) => deviceId === 'device-1'),+ ).toBe(true);+ });++ it('keeps click FIFO when an annotated message materializes after a later plain message', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ makerChatStore.__applyStatusUpdateForTest(SESSION_ID, {+ sessionId: SESSION_ID,+ status: 'running',+ tokenUsage: 0,+ contextTokens: 0,+ contextWindow: 0,+ isRunning: true,+ });+ let resolveMaterialize!: (value: {+ url: string;+ name: string;+ ext: string;+ mimeType: string;+ size: number;+ }) => void;+ vi.mocked(window.electronAPI.cacheMediaForSession).mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveMaterialize = resolve;+ }),+ );+ const sentTexts: string[] = [];+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ const item = args[1] as AgentInputQueuedMessage;+ sentTexts.push(item.text);+ return projection(SESSION_ID, { pendingQueue: [item] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });+ const attachment: AttachedFile = {+ id: 'fifo-materializing-source',+ name: 'fifo-materializing.png',+ path: '',+ ext: '.png',+ size: 1,+ category: 'image',+ mimeType: 'image/png',+ url: 'xdt-image://source/fifo-materializing.png',+ cacheUrlShared: true,+ };++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'first annotated',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ [attachment],+ ),+ ).resolves.toBe(true);+ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'second plain',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ ),+ ).resolves.toBe(true);+ await flushPromises();+ expect(sentTexts).toEqual([]);++ resolveMaterialize({+ url: 'xdt-image://text-delta-batching/fifo-private.png',+ name: 'fifo-private.png',+ ext: '.png',+ mimeType: 'image/png',+ size: 1,+ });+ await flushPromises();+ await flushPromises();+ await flushPromises();++ expect(sentTexts).toEqual(['first annotated', 'second plain']);+ });++ it('reruns a deferred remote preflight after the connection recovers', async () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ let online = false;+ let preflightCalls = 0;+ const beforeEnqueue = vi.fn(async () => {+ preflightCalls += 1;+ if (!online) throw new Error('[DEVICE_LINK_NOT_CONNECTED] remote preflight deferred');+ return true;+ });+ const sentTexts: string[] = [];+ deviceLinkInvoke.mockImplementation(async (_deviceId, channel, args) => {+ if (channel === 'maker:input:enqueue') {+ const item = args[1] as AgentInputQueuedMessage;+ sentTexts.push(item.text);+ return projection(SESSION_ID, { pendingQueue: [item] });+ }+ if (channel === 'maker:input:get-projection') return projection(SESSION_ID);+ throw new Error(`unexpected remote channel: ${channel}`);+ });++ await expect(+ makerChatStore.sendMessage(+ SESSION_ID,+ 'wait for preflight',+ MODEL,+ EFFORT,+ PERMISSION_MODE,+ WORKING_DIR,+ undefined,+ undefined,+ { beforeEnqueue },+ ),+ ).resolves.toBe(true);+ expect(preflightCalls).toBe(1);+ expect(sentTexts).toEqual([]);++ online = true;+ onPresenceChanged?.({ deviceId: 'device-1', online: true });+ await flushPromises();++ expect(preflightCalls).toBe(2);+ expect(sentTexts).toEqual(['wait for preflight']);+ });+it('hydrates existing runtime messages with authoritative DB-created timestamps', () => {vi.setSystemTime(new Date('2026-06-15T00:00:30.000Z'));emitTextDelta('draft');diff --git a/apps/desktop/src/renderer/__tests__/makerTransportOrcaRouting.test.ts b/apps/desktop/src/renderer/__tests__/makerTransportOrcaRouting.test.tsindex 86b791be96..ba56fc69b4 100644--- a/apps/desktop/src/renderer/__tests__/makerTransportOrcaRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerTransportOrcaRouting.test.ts@@ -10,6 +10,16 @@ beforeEach(() => {vi.resetModules();});+async function primeOwnerFence(): Promise<void> {+ const { __testing: dataOwnerGenerationTesting, setDataOwnerGeneration } =+ await import('@/contexts/dataOwnerGeneration');+ const { __testing: remoteDataOwnerPushFenceTesting } =+ await import('@/lib/remoteDataOwnerPushFence');+ dataOwnerGenerationTesting.reset();+ remoteDataOwnerPushFenceTesting.reset();+ setDataOwnerGeneration('owner-a', 1);+}+function stubElectron() {const orcaSpies = {create: vi.fn(),@@ -117,6 +127,7 @@ describe('subscribeOrcaWorkerChanged 分流', () => {const { orcaSpies, onRemotePush } = stubElectron();const { subscribeOrcaWorkerChanged } = await import('@/lib/makerTransport');const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');+ await primeOwnerFence();remoteProjectsStore.setDeviceSessions('dev-1', 'Mac', [sess('rlead')]);const cb = vi.fn();@@ -138,6 +149,7 @@ describe('subscribeOrcaWorkerChanged 分流', () => {const { getStickySessionDeviceId } = await import('@/features/device-link/stickySessionOrigin');+ await primeOwnerFence();remoteProjectsStore.setDeviceSessions('dev-sticky', 'Mac', [sess('sticky-lead')]);expect(getStickySessionDeviceId('sticky-lead')).toBe('dev-sticky');remoteProjectsStore.setDeviceSessions('dev-sticky', 'Mac', []);diff --git a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.tsindex c2160c14b1..f954a26a6d 100644--- a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts@@ -126,10 +126,7 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {await api.setModel('rs', 'with-revision', null, 7);await api.setModel('rs', 'with-selection', 'provider-b', undefined, selection);- expect(invoke).toHaveBeenCalledWith('dev-wire', 'maker:set-model', [- 'rs',- 'model-only',- ]);+ expect(invoke).toHaveBeenCalledWith('dev-wire', 'maker:set-model', ['rs', 'model-only']);expect(invoke).toHaveBeenCalledWith('dev-wire', 'maker:set-model', ['rs','with-provider',@@ -170,6 +167,22 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {expect(invoke).not.toHaveBeenCalled();});+ it('getSessionFor:镜像清空期间仍从最后已知设备读取任务元数据', async () => {+ const { invoke } = stubElectron();+ invoke.mockResolvedValue({ id: 'rs', workingDir: '/remote/worktree' });+ const { getSessionFor } = await import('@/lib/makerTransport');+ const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');++ remoteProjectsStore.setDeviceSessions('dev-1', 'Mac', [sess('rs')]);+ await getSessionFor('rs'); // seed sticky origin before the simulated clear+ invoke.mockClear();+ remoteProjectsStore.clear();++ await getSessionFor('rs');++ expect(invoke).toHaveBeenCalledWith('dev-1', 'local-db:sessions:get', ['rs']);+ });+it('远程会话 patchMeta(删/归档/改名/置顶)经隧道 local-db:sessions:patch-meta', async () => {const { invoke } = stubElectron();const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');@@ -188,6 +201,15 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {'rs',{ title: 'New' },]);++ // Relay reconnect may temporarily clear the live mirror. The sticky+ // origin must keep the archived-session auto-unarchive on the remote host.+ remoteProjectsStore.clear();+ await sessionService.setStatus('rs', 'active');+ expect(invoke).toHaveBeenCalledWith('dev-1', 'local-db:sessions:patch-meta', [+ 'rs',+ { status: 'active' },+ ]);});it('本机会话:走本地 maker,不经隧道', async () => {@@ -264,9 +286,7 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {const { makerSpies, invoke } = stubElectron();const { makerApiFor, makerApiForSticky } = await import('@/lib/makerTransport');const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');- const { getStickySessionDeviceId } = await import(- '@/features/device-link/stickySessionOrigin'- );+ const { getStickySessionDeviceId } = await import('@/features/device-link/stickySessionOrigin');remoteProjectsStore.setDeviceSessions('dev-1', 'Mac', [sess('lead')]);// 先解析一次,让粘滞归属记住 dev-1(与真实链路一致:视图渲染时已解析过)。@@ -303,11 +323,11 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {invoke.mockResolvedValue({ effectiveEnabled: false });const { pluginEnableStateFor } = await import('@/lib/makerTransport');- await expect(- pluginEnableStateFor('dev-1', 'collab', '/host/proj', 'project'),- ).resolves.toEqual({- effectiveEnabled: false,- });+ await expect(pluginEnableStateFor('dev-1', 'collab', '/host/proj', 'project')).resolves.toEqual(+ {+ effectiveEnabled: false,+ },+ );expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:plugins:get-state', ['collab','/host/proj',@@ -317,11 +337,7 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {invoke.mockClear();await pluginEnableStateFor(null, 'collab', '/local/proj', 'project');- expect(makerSpies.plugins.getState).toHaveBeenCalledWith(- 'collab',- '/local/proj',- 'project',- );+ expect(makerSpies.plugins.getState).toHaveBeenCalledWith('collab', '/local/proj', 'project');expect(invoke).not.toHaveBeenCalled();// skipQuery 档(SSH 远端):不传 workingDir → 落用户级/全局级,两条路由都要保持原样透传。diff --git a/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts b/apps/desktop/src/renderer/__tests__/messageTurnCost.test.tsindex 6fddb6fcbb..010e264d64 100644--- a/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts+++ b/apps/desktop/src/renderer/__tests__/messageTurnCost.test.ts@@ -43,6 +43,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],@@ -55,6 +56,10 @@ import { buildTurnUsageDetails } from '../../shared/turnUsageDetails';import { makerChatStore } from '@/lib/makerChatStore';import * as messageService from '@/lib/messageService';import type { Message } from '@/lib/ccAgent.types';+import {+ __testing as dataOwnerTesting,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';describe('formatTurnCostUsd', () => {it('始终保留两位小数,小于一美分显示下限', () => {@@ -72,6 +77,7 @@ describe('formatTurnCostUsd', () => {// ── store 集成:历史映射 + 实时推送 ──────────────────────────────────────────type FanOutCb = (data: unknown) => void;+const TEST_OWNER_STAMP = { dataOwnerId: 'test-owner', ownerGeneration: 0 } as const;function makeElectronApiStub() {let turnCostCb: FanOutCb | null = null;@@ -92,7 +98,13 @@ function makeElectronApiStub() {localDb: { messages: { onCreated: fanOut() } },deviceLink: {onRemotePush: (cb: FanOutCb) => {- remotePushCb = cb;+ remotePushCb = (data) => {+ if (data && typeof data === 'object' && !Array.isArray(data)) {+ cb({ ...(data as Record<string, unknown>), ownerStamp: TEST_OWNER_STAMP });+ } else {+ cb(data);+ }+ };return () => {remotePushCb = null;};@@ -160,6 +172,8 @@ describe('makerChatStore per-turn 费用', () => {const SID = 'sess-turn-cost';beforeEach(() => {+ dataOwnerTesting.reset();+ setDataOwnerGeneration(TEST_OWNER_STAMP.dataOwnerId, TEST_OWNER_STAMP.ownerGeneration);const { stub, getRemotePushCb: getRemote, getTurnCostCb: getTurn } = makeElectronApiStub();getRemotePushCb = getRemote;getTurnCostCb = getTurn;@@ -172,6 +186,7 @@ describe('makerChatStore per-turn 费用', () => {makerChatStore.__teardownGlobalListeners();delete (globalThis as { window?: unknown }).window;vi.clearAllMocks();+ dataOwnerTesting.reset();});it('历史加载:原始分段与用户轮累计成本分别映射;无值不映射', async () => {diff --git a/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts b/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.tsindex 53743aca93..ede937d2cf 100644--- a/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts@@ -137,9 +137,7 @@ describe('NewMakerDraftRoute Orca worker create order', () => {);expect(sessionViewSource).toContain('if (sessionHandoffPreparing) return false;');expect(sessionViewSource).not.toContain('if (worktreePreparing) return false;');- expect(sessionViewSource).toContain(- 'disabled={remoteSessionUnavailable || remoteHandoffPreparing}',- );+ expect(sessionViewSource).toContain('disabled={remoteHandoffPreparing}');});it('refreshes the remote mirror even when the remote enableOrca reports failure', () => {diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.tsindex 43d1a62009..acd50b357a 100644--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts@@ -123,6 +123,19 @@ describe('Shared create project picker', () => {expect(folderPickerPopoverSource).toContain('scrollRoot.scrollTop += normalizeWheelDeltaY(e)');});+ it('waits for async folder selection before closing the controlled popover', () => {+ const start = folderPickerPopoverSource.indexOf('const handleSelectPath = async');+ const end = folderPickerPopoverSource.indexOf('const handleRemoveProject', start);+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ const body = folderPickerPopoverSource.slice(start, end);+ const selectAt = body.indexOf('await onSelect(folderPath, source, option);');+ const closeAt = body.indexOf('onOpenChange(false);');+ expect(selectAt).toBeGreaterThan(-1);+ expect(closeAt).toBeGreaterThan(selectAt);+ expect(body).toContain('finally {');+ });+it('keeps dialogue outside of the project group in the picker menu', () => {const topHeadingIndex = folderPickerPopoverSource.indexOf("t('newChat.folderPicker.dialogueOrSelectProject')",diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.tsindex 8f6fc8e3ec..2f03b36e65 100644--- a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts+++ b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts@@ -179,14 +179,8 @@ describe('OrcaWorkflowRoute source invariants', () => {});it('keeps the active collaboration tooltip free of policy-disabled reasons', () => {- expect(sessionViewSource).toContain(- "disabledReason:\n" +- " !collabEnabled\n" +- " ? collabPolicy.loading",- );- expect(sessionViewSource).toContain(- " : undefined\n" +- " : undefined,",+ expect(sessionViewSource).toMatch(+ /disabledReason:\s*!collabEnabled\s*\?\s*collabPolicy\.loading[\s\S]*?:\s*undefined\s*:\s*undefined,/,);});@@ -320,7 +314,9 @@ describe('OrcaWorkflowRoute source invariants', () => {expect(sessionViewSource).toContain('routeWorkerHint.hasWorkerParam || !!orcaWorkersReveal || hasWorkerSearchJump');expect(sessionViewSource).toContain('const shouldRevealWorkersTab = hasExplicitOrcaWorkersReveal || shouldPassiveRevealWorkersTab;');expect(sessionViewSource).toContain('orcaWorkersReveal?.focusWorkerSessionId ??');- expect(sessionViewSource).toContain('hasWorkerSearchJump ? searchJump?.sessionId ?? null : null');+ expect(sessionViewSource).toMatch(+ /hasWorkerSearchJump\s*\?\s*\(?searchJump\?\.sessionId\s*\?\?\s*null\)?\s*:\s*null/,+ );expect(sessionViewSource).toContain('orcaWorkersReveal: undefined');expect(sessionViewSource).toContain("routeResult === 'stale-context' && shouldRevealWorkersTab");expect(sessionViewSource).toContain("routeResult !== 'attached' && routeResult !== 'routed'");@@ -424,7 +420,9 @@ describe('OrcaWorkflowRoute source invariants', () => {it('passes Orca lead vendor options when sending from the plain lead route', () => {expect(sessionViewSource).toContain('const orcaLeadVendorOptions =');- expect(sessionViewSource).toContain('sessionId && isOrcaLeadSession(session)');+ expect(sessionViewSource).toMatch(+ /sessionId\s*&&\s*session\s*!==\s*null\s*&&\s*isOrcaLeadSession\(session\)/,+ );expect(sessionViewSource).not.toContain('isOrcaMode && sessionId && isOrcaLeadSession(session)');expect(sessionViewSource).toContain("vendorOptions: { orcaRole: 'lead', orcaLeadSessionId: sessionId }");});diff --git a/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts b/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.tsindex cc4ec78aae..be4a17a67e 100644--- a/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts+++ b/apps/desktop/src/renderer/__tests__/pendingQueueDefer.test.ts@@ -16,6 +16,8 @@ import type {AgentInputProjection,AgentInputQueuedMessage,} from '../../shared/agentInputQueue';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import { __resetStickySessionOriginForTest, getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';vi.mock('@/lib/messageService', () => ({list: vi.fn(async () => ({ items: [], hasMore: false, oldestId: null })),@@ -58,6 +60,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],@@ -73,6 +76,7 @@ const WD = 'C:\\workspace';let projectionHandler: ((projection: AgentInputProjection) => void) | null = null;let messageCreatedHandler: ((payload: unknown) => void) | null = null;+let remoteInvoke = vi.fn();const legacySend = vi.fn(async () => {});const legacySteer = vi.fn(async () => {});@@ -162,6 +166,7 @@ function queued(clientId: string, text: string): AgentInputQueuedMessage {function installElectronBridge(): void {projectionHandler = null;messageCreatedHandler = null;+ remoteInvoke = vi.fn().mockResolvedValue(undefined);const w = (globalThis as unknown as { window?: Record<string, unknown> });if (!w.window) w.window = {};w.window.electronAPI = {@@ -190,6 +195,7 @@ function installElectronBridge(): void {}),},},+ deviceLink: { invoke: remoteInvoke },};}@@ -201,12 +207,16 @@ const flushPromises = async () => {beforeEach(() => {vi.clearAllMocks();+ remoteProjectsStore.clear();+ __resetStickySessionOriginForTest();makerChatStore.__teardownGlobalListeners();installElectronBridge();});afterEach(() => {makerChatStore.__teardownGlobalListeners();+ remoteProjectsStore.clear();+ __resetStickySessionOriginForTest();});describe('renderer input queue facade', () => {@@ -366,6 +376,23 @@ describe('renderer input queue facade', () => {expect(legacySteer).not.toHaveBeenCalled();});+ it('keeps queue controls on the sticky remote device while the live mirror is rebuilding', async () => {+ const sid = `sticky-row-${Math.random().toString(36).slice(2, 8)}`;+ const deviceId = 'dev-sticky';+ remoteProjectsStore.setDeviceSessions(deviceId, 'Remote Mac', [+ { id: sid } as never,+ ]);+ expect(getStickySessionDeviceId(sid)).toBe(deviceId);+ remoteProjectsStore.clear();+ remoteInvoke.mockResolvedValue(projection(sid, { queueExpanded: true }));++ makerChatStore.setQueueExpanded(sid, true);+ await flushPromises();++ expect(remoteInvoke).toHaveBeenCalledWith(deviceId, 'maker:input:set-expanded', [sid, true]);+ expect(input.setExpanded).not.toHaveBeenCalled();+ });+it('preserves queued source device hints while editing an anchored link', async () => {const sid = `row-ref-${Math.random().toString(36).slice(2, 8)}`;const item = queued('q-ref', 'compare cindy://session/source?message=old-anchor');diff --git a/apps/desktop/src/renderer/__tests__/permissionSessionApproval.test.ts b/apps/desktop/src/renderer/__tests__/permissionSessionApproval.test.tsindex 0b444884a7..7f477e452d 100644--- a/apps/desktop/src/renderer/__tests__/permissionSessionApproval.test.ts+++ b/apps/desktop/src/renderer/__tests__/permissionSessionApproval.test.ts@@ -38,6 +38,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],diff --git a/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.ts b/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.tsindex d8a5797de9..5d84e698e3 100644--- a/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.ts@@ -61,6 +61,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],@@ -91,12 +92,14 @@ let onEvent: ((data: unknown) => void) | undefined;let onDbMessageCreated: ((data: unknown) => void) | undefined;let onInteractionRequest: ((data: unknown) => void) | undefined;let onInteractionDismissed: ((data: unknown) => void) | undefined;+let getPendingInteractions: ReturnType<typeof vi.fn>;function installElectronBridge(): void {onEvent = undefined;onDbMessageCreated = undefined;onInteractionRequest = undefined;onInteractionDismissed = undefined;+ getPendingInteractions = vi.fn(async () => []);const w = globalThis as unknown as { window: Record<string, unknown> };w.window = {electronAPI: {@@ -121,6 +124,7 @@ function installElectronBridge(): void {},send: vi.fn(async () => ({ accepted: true })),generateTitle: vi.fn(async () => ({ title: 't' })),+ getPendingInteractions,setPlanMode: vi.fn(async () => {}),resolveInteraction: vi.fn(async () => {}),abortSession: vi.fn(async () => {}),@@ -309,6 +313,53 @@ describe('plan_review 与 done 的时序', () => {expect(pendingBubbleStatuses()).toEqual(['pending']);});+ it('codex:done 作废在途旧快照后主动拉新快照重建计划审阅', async () => {+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });+ let resolveStaleSnapshot!: (items: unknown[]) => void;+ getPendingInteractions+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveStaleSnapshot = resolve;+ }),+ )+ .mockResolvedValueOnce([+ {+ request: {+ kind: 'plan_review',+ requestId: 'pr-fresh-snapshot',+ plan: '# 最新计划\n1. do Y',+ },+ persistId: 'persist-pr-fresh-snapshot',+ },+ ]);++ const staleReconcile = makerChatStore.reconcilePendingInteractions(SESSION_ID);+ emitDone('codex');++ await vi.waitFor(() => {+ expect(getPendingInteractions).toHaveBeenCalledTimes(2);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingPlanReview?.requestId).toBe(+ 'pr-fresh-snapshot',+ );+ });++ resolveStaleSnapshot([+ {+ request: {+ kind: 'plan_review',+ requestId: 'pr-stale-snapshot',+ plan: '# 旧计划',+ },+ persistId: 'persist-pr-stale-snapshot',+ },+ ]);+ await expect(staleReconcile).resolves.toBe(0);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingPlanReview?.requestId).toBe(+ 'pr-fresh-snapshot',+ );+ });+it('claude:turn 结束仍将 pending 计划审阅标过期(既有语义不变)', () => {makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'claude-code' });emitPlanReviewRequest('pr-2');diff --git a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.tsindex 156820c26b..c460f8fb6c 100644--- a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts+++ b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts@@ -8,6 +8,10 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import type { Message } from '@/lib/ccAgent.types';+import {+ __testing as dataOwnerTesting,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';vi.mock('@/lib/messageService', () => ({list: vi.fn(async () => []),@@ -29,9 +33,15 @@ import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore'const DEVICE_ID = 'dev-A';const DEVICE_B_ID = 'dev-B';+const TEST_OWNER_STAMP = { dataOwnerId: 'test-owner', ownerGeneration: 0 } as const;let n = 0;const sid = () => `reconcile-${n++}`;-type RemotePush = { deviceId: string; channel: string; payload: unknown };+type RemotePush = {+ deviceId: string;+ channel: string;+ payload: unknown;+ ownerStamp?: typeof TEST_OWNER_STAMP;+};let remotePush: ((push: RemotePush) => void) | undefined;function dbMessage(sessionId: string, id: string, content: string, ts: string, role: Message['role'] = 'assistant'): Message {@@ -102,7 +112,7 @@ function stubApi(): void {deviceLink: {invoke,onRemotePush: (cb: (push: RemotePush) => void) => {- remotePush = cb;+ remotePush = (push) => cb({ ...push, ownerStamp: push.ownerStamp ?? TEST_OWNER_STAMP });return vi.fn();},},@@ -138,6 +148,8 @@ async function openRemoteWithHistory(s: string, initial: Message[]): Promise<voi}beforeEach(() => {+ dataOwnerTesting.reset();+ setDataOwnerGeneration(TEST_OWNER_STAMP.dataOwnerId, TEST_OWNER_STAMP.ownerGeneration);makerChatStore.__teardownGlobalListeners();stubApi();remoteList = [];@@ -153,6 +165,7 @@ afterEach(() => {makerChatStore.__teardownGlobalListeners();remoteProjectsStore.clear();vi.unstubAllGlobals();+ dataOwnerTesting.reset();});describe('makerChatStore.reconcileRemoteMessages', () => {diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.tsindex 3971fd3e5d..861000428a 100644--- a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts@@ -35,6 +35,18 @@ const projectNodeSrc = readFileSync(resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'sections', 'ProjectNode.tsx'),'utf8',);+const makerChatStoreSrc = readFileSync(+ resolve(__dirname, '..', 'lib', 'makerChatStore.ts'),+ 'utf8',+);+const makerTransportSrc = readFileSync(+ resolve(__dirname, '..', 'lib', 'makerTransport.ts'),+ 'utf8',+);+const chatInputSrc = readFileSync(+ resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),+ 'utf8',+);describe('useRemoteSessionSync 接线不变式', () => {it('WS 重连(onStatusChanged online)重建重 topic 订阅 + 对账', () => {@@ -64,23 +76,57 @@ describe('CCAgentSessionView 接线不变式', () => {expect(sessionViewSrc).toContain('useRemoteSessionConnection(remoteDeviceId)');expect(sessionViewSrc).toContain('<RemoteSessionBanner');// 旧的 mount-once 重 topic effect 已被 hook 取代(不再就地订阅 session: topic)。- expect(sessionViewSrc).not.toContain("const topic = `session:${sessionId}`");+ expect(sessionViewSrc).not.toContain('const topic = `session:${sessionId}`');+ });+ it('断线缓存的远程 session 可打开查看并继续乐观发送', () => {+ expect(sessionViewSrc).toContain(+ "const remoteSessionUnavailable = remoteConn === 'reconnecting' || remoteConn === 'host-offline'",+ );+ expect(sessionViewSrc).not.toContain('if (remoteSessionUnavailable) return false');+ expect(sessionViewSrc).not.toContain('remoteSessionUnavailableRef');+ expect(sessionViewSrc).toContain('if (!remoteDeviceId) {');+ expect(sessionViewSrc).not.toContain('beforeEnqueue: checkVendorReady');+ // device-link 远程交接期间仍要禁用(见 remoteHandoffPreparing):那几段 await+ // 可能数十秒,不禁用的话用户补发的消息会插到草稿提交的首条之前。+ expect(sessionViewSrc).toContain('disabled={remoteHandoffPreparing}');});- it('断线缓存的远程 session 可打开查看,但禁用 composer 并拦截发送', () => {- expect(sessionViewSrc).toContain("const remoteSessionUnavailable = remoteConn === 'reconnecting' || remoteConn === 'host-offline'");- expect(sessionViewSrc).toContain('if (remoteSessionUnavailable) return false');- // device-link 远程交接期间也要禁用(见 remoteHandoffPreparing):那几段 await- // 可能数十秒,不禁用的话用户补发的消息会插到草稿提交的首条之前。断线这一档不变。+ it('补选目录后的续发保持 delivery mode,并按本地/远端策略清理原 composer', () => {+ expect(sessionViewSrc).toContain('deliveryMode: MessageDeliveryMode;');+ expect(sessionViewSrc).toContain(+ "const dispatch = deliveryMode === 'steer' ? steerMessage : sendMessage;",+ );+ expect(sessionViewSrc).toContain('if (accepted) onDeferredAccepted?.();');expect(sessionViewSrc).toContain(- 'disabled={remoteSessionUnavailable || remoteHandoffPreparing}',+ '...(opts?.onDeferredAccepted ? { onDeferredAccepted: opts.onDeferredAccepted } : {})',+ );+ expect(chatInputSrc).toContain('onDeferredAccepted,');+ expect(chatInputSrc).toMatch(+ /if \(optimisticallyClearRemoteComposer\) \{\s*\/\/[^\n]*\n(?:\s*\/\/[^\n]*\n){2}\s*optimisticComposerRestored = false;\s*clearSentComposer\(\{ preserveNewerContent: true \}\);\s*\} else \{[\s\S]*?clearSentComposer\(\);\s*\}/,+ );+ });+ it('已有远程 session 断线时跳过来源门禁,远程草稿与本地任务仍保留门禁', () => {+ expect(chatInputSrc).toContain(+ 'const enforceConnectedSourceGate = !sessionId || !deviceLinkDeviceId;',+ );+ expect(chatInputSrc).toMatch(+ /const noConnectedSource =\s*enforceConnectedSourceGate &&\s*!!currentModelAgentKind/,+ );+ expect(chatInputSrc).toMatch(+ /if\s*\(\s*enforceConnectedSourceGate\s*&&\s*currentModelAgentKind\s*&&[\s\S]*?\)\s*\{/,);});it('断线缓存的远程 session 可查看,但生命周期/元数据写操作必须走统一 gate', () => {- expect(sessionHeaderSrc).toContain('remoteSessionUnavailable || isRemoteSessionWriteBlocked(session)');+ expect(sessionHeaderSrc).toContain(+ 'remoteSessionUnavailable || isRemoteSessionWriteBlocked(session)',+ );expect(sidebarUpperSrc).toContain('isRemoteSessionWriteBlocked(session)');expect(sidebarUpperSrc).toContain('selectedSessions.some(isRemoteSessionWriteBlocked)');- expect(sessionItemSrc).toContain('const remoteWritesBlocked = isRemoteSessionWriteBlocked(session)');- expect(sessionCardSrc).toContain('const remoteWritesBlocked = isRemoteSessionWriteBlocked(session)');+ expect(sessionItemSrc).toContain(+ 'const remoteWritesBlocked = isRemoteSessionWriteBlocked(session)',+ );+ expect(sessionCardSrc).toContain(+ 'const remoteWritesBlocked = isRemoteSessionWriteBlocked(session)',+ );expect(sessionViewSrc).toContain('remoteSessionUnavailable={remoteSessionUnavailable}');});it('断线 device-link session 不能触发 Stop 或新窗口写入口', () => {@@ -111,10 +157,40 @@ describe('CCAgentSessionView 接线不变式', () => {expect(sessionViewSrc).toContain('sessionInterruptAcked || remoteTurnActive');});it('断线 device-link project 不能从项目标题 + 入口创建远程 draft', () => {- expect(projectNodeSrc).toContain('const projectWritesBlocked = isDeviceLinkWriteBlocked(project)');+ expect(projectNodeSrc).toContain(+ 'const projectWritesBlocked = isDeviceLinkWriteBlocked(project)',+ );expect(projectNodeSrc).toContain('disabled={projectWritesBlocked}');expect(projectNodeSrc).toContain('handleCreateInProject');expect(projectNodeSrc).toContain('handleArchiveAll');expect(sidebarUpperSrc).toContain('isDeviceLinkWriteBlocked(project)');});});++describe('弱网 optimistic mutation 粘滞路由不变式', () => {+ it('发送相关的控制操作在 mirror clear 后仍使用 pinned device', () => {+ expect(makerChatStoreSrc).toContain(+ 'const remoteDeviceId = getStickySessionDeviceId(sessionId);',+ );+ expect(makerChatStoreSrc).toContain(+ 'const steerApi = remoteDeviceId ? makerApiForDevice(remoteDeviceId) : makerApiFor(sessionId);',+ );+ expect(makerChatStoreSrc).toContain(+ 'const operation = beginInputProjectionOperation(sessionId, remoteDeviceId);',+ );+ expect(makerChatStoreSrc).toContain(+ 'const triggerApi = remoteDeviceId ? makerApiForDevice(remoteDeviceId) : makerApiFor(sessionId);',+ );+ expect(makerChatStoreSrc).toMatch(/clearOperation\.api\s*\.closeSession/);+ expect(makerChatStoreSrc).toContain(+ 'const remoteDeviceId = sourceRemoteDeviceId ?? getStickySessionDeviceId(sessionId);',+ );+ });++ it('自动标题和会话元数据读取使用 sticky 远端判定', () => {+ expect(makerChatStoreSrc).toContain('if (getStickySessionDeviceId(sessionId)) {');+ expect(makerTransportSrc).toContain(+ '// Session metadata is part of the same remote send attempt as the later',+ );+ });+});diff --git a/apps/desktop/src/renderer/__tests__/remoteStallRecovery.test.ts b/apps/desktop/src/renderer/__tests__/remoteStallRecovery.test.tsindex c20fc9090b..71c49ff795 100644--- a/apps/desktop/src/renderer/__tests__/remoteStallRecovery.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteStallRecovery.test.ts@@ -40,6 +40,7 @@ vi.mock('@/lib/imageRef', () => ({}));vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({ type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }] }),}));diff --git a/apps/desktop/src/renderer/__tests__/sessionLinkPaste.test.ts b/apps/desktop/src/renderer/__tests__/sessionLinkPaste.test.tsindex 47805f7c08..5a1de10e45 100644--- a/apps/desktop/src/renderer/__tests__/sessionLinkPaste.test.ts+++ b/apps/desktop/src/renderer/__tests__/sessionLinkPaste.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import type { Editor } from '@tiptap/core';import {+ resolveSerializedSessionMessageReferencesForSend,resolveSessionMessageReferencesForSend,sanitizeSessionChipTitle,pastedSessionChipAttrs,@@ -133,4 +134,43 @@ describe('resolveSessionMessageReferencesForSend', () => {agentText: 'Full cross-device message body',});});++ it('hydrates an immutable click-time reference snapshot without mutating later composer state', async () => {+ const frozenReferences = [+ {+ kind: 'message' as const,+ start: 0,+ end: MESSAGE_URL.length,+ href: MESSAGE_URL,+ sessionId: 'ee59672a-5591-48a7-a44d-aa97e3808c64',+ messageClientId: 'client-message-12345678',+ },+ ];+ const liveReferences = [...frozenReferences];+ let release!: (value: string | null) => void;+ const messageText = new Promise<string | null>((resolve) => {+ release = resolve;+ });++ const pending = resolveSerializedSessionMessageReferencesForSend(+ frozenReferences,+ async () => messageText,+ );+ liveReferences.splice(0, 1, {+ ...frozenReferences[0],+ href: `${SESSION_URL}?message=new-live-message`,+ messageClientId: 'new-live-message',+ });+ release('Body captured for the original click');++ await expect(pending).resolves.toEqual([+ expect.objectContaining({+ href: MESSAGE_URL,+ messageClientId: 'client-message-12345678',+ text: 'Body captured for the original click',+ }),+ ]);+ expect(frozenReferences[0]).not.toHaveProperty('text');+ expect(liveReferences[0]?.messageClientId).toBe('new-live-message');+ });});diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsxindex 31146cf1c2..620467b94a 100644--- a/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx@@ -9,13 +9,14 @@ type SpendPayload = {totalMoney?: Session['totalMoney'];totalCostUsd?: number;};+type OwnerStamp = { dataOwnerId: string | null; ownerGeneration: number };const mocks = vi.hoisted(() => {let spendListener:- | ((payload: SpendPayload) => void)+ | ((payload: SpendPayload, ownerStamp?: OwnerStamp) => void)| undefined;const onUsageSessionSpendChanged = vi.fn(- (listener: (payload: SpendPayload) => void) => {+ (listener: (payload: SpendPayload, ownerStamp?: OwnerStamp) => void) => {spendListener = listener;return vi.fn();},@@ -26,8 +27,8 @@ const mocks = vi.hoisted(() => {});return {list: vi.fn(),- emitSessionSpend(payload: SpendPayload): void {- spendListener?.(payload);+ emitSessionSpend(payload: SpendPayload, ownerStamp?: OwnerStamp): void {+ spendListener?.(payload, ownerStamp);},};});@@ -38,6 +39,10 @@ vi.mock('@/lib/sessionService', () => ({}));import { useCCSessions } from '@/hooks/useCCSessions';+import {+ __testing as dataOwnerTesting,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';import { sessionsStore } from '@/lib/sessionsStore';function deferred<T>(): {@@ -64,6 +69,7 @@ describe('sessionsStore account boundaries', () => {afterEach(() => {cleanup();sessionsStore.reset();+ dataOwnerTesting.reset();});it('does not let a request started before reset repopulate the cache', async () => {@@ -168,6 +174,34 @@ describe('sessionsStore account boundaries', () => {unsubscribe();});+ it('ignores a delayed spend push stamped for the previous owner', async () => {+ setDataOwnerGeneration('owner-b', 2);+ mocks.list.mockResolvedValueOnce([session('same-id', { totalCostUsd: 1 })]);+ await sessionsStore.ensureByFilter('active');++ act(() => {+ mocks.emitSessionSpend(+ { sessionId: 'same-id', totalCostUsd: 9 },+ { dataOwnerId: 'owner-a', ownerGeneration: 1 },+ );+ });++ expect(sessionsStore.getByFilter('active')).toEqual([+ expect.objectContaining({ id: 'same-id', totalCostUsd: 1 }),+ ]);++ act(() => {+ mocks.emitSessionSpend(+ { sessionId: 'same-id', totalCostUsd: 2 },+ { dataOwnerId: 'owner-b', ownerGeneration: 2 },+ );+ });++ expect(sessionsStore.getByFilter('active')).toEqual([+ expect.objectContaining({ id: 'same-id', totalCostUsd: 2 }),+ ]);+ });+it('patches structured CNY spend without fabricating a USD projection', async () => {mocks.list.mockResolvedValueOnce([session('target', { totalCostUsd: 1 }),diff --git a/apps/desktop/src/renderer/__tests__/staleErrorClearedOnTurnStart.test.ts b/apps/desktop/src/renderer/__tests__/staleErrorClearedOnTurnStart.test.tsindex 62f8cea7ad..784d922dff 100644--- a/apps/desktop/src/renderer/__tests__/staleErrorClearedOnTurnStart.test.ts+++ b/apps/desktop/src/renderer/__tests__/staleErrorClearedOnTurnStart.test.ts@@ -58,6 +58,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (s: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],diff --git a/apps/desktop/src/renderer/__tests__/useAttachmentsRejections.test.ts b/apps/desktop/src/renderer/__tests__/useAttachmentsRejections.test.tsindex 30774c8f41..eb0d274dd7 100644--- a/apps/desktop/src/renderer/__tests__/useAttachmentsRejections.test.ts+++ b/apps/desktop/src/renderer/__tests__/useAttachmentsRejections.test.ts@@ -30,6 +30,16 @@ vi.mock('@/lib/toast', () => ({}));import { useAttachments } from '@/hooks/useAttachments';+import {+ clearDraft,+ discardDraft,+ getDraft,+ setComposerDraftOwner,+} from '@/lib/composerDraftStore';+import {+ __testing as dataOwnerTesting,+ setDataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';/** Build a minimal FileList-like object addFiles can iterate. */function fileListOf(files: Array<{ name: string; size: number }>): FileList {@@ -37,7 +47,22 @@ function fileListOf(files: Array<{ name: string; size: number }>): FileList {return Object.assign(arr, { item: (i: number) => arr[i] }) as unknown as FileList;}+function deferred<T>(): {+ promise: Promise<T>;+ resolve: (value: T) => void;+} {+ let resolve!: (value: T) => void;+ return {+ promise: new Promise<T>((next) => {+ resolve = next;+ }),+ resolve,+ };+}+beforeEach(() => {+ dataOwnerTesting.reset();+ setComposerDraftOwner(null);toastWarning.mockClear();stageChatAttachment.mockReset();stageChatAttachment.mockResolvedValue({ success: true, path: '/cache/setup.exe.bin' });@@ -48,6 +73,8 @@ beforeEach(() => {});afterEach(() => {+ dataOwnerTesting.reset();+ setComposerDraftOwner(null);delete (window as unknown as { electronAPI?: unknown }).electronAPI;});@@ -56,9 +83,7 @@ describe('useAttachments inline rejections', () => {const { result } = renderHook(() => useAttachments());await act(async () => {- await result.current.addFiles(- fileListOf([{ name: 'empty.png', size: 0 }]),- );+ await result.current.addFiles(fileListOf([{ name: 'empty.png', size: 0 }]));});expect(result.current.rejections).toHaveLength(1);@@ -137,4 +162,236 @@ describe('useAttachments inline rejections', () => {expect(result.current.rejections[0].message).toContain('setup.exe');expect(result.current.rejections[0].message).toContain('copy_failed');});++ it('restores sent attachments without dropping files added while send was in flight', async () => {+ const { result } = renderHook(() => useAttachments());++ await act(async () => {+ await result.current.addFiles(fileListOf([{ name: 'sent.pdf', size: 128 }]));+ });+ const sentAttachments = [...result.current.attachments];+ expect(sentAttachments).toHaveLength(1);++ act(() => result.current.clearFiles());+ await act(async () => {+ await result.current.addFiles(fileListOf([{ name: 'new-during-rtt.pdf', size: 256 }]));+ result.current.restoreFiles(sentAttachments);+ });++ expect(result.current.attachments.map((attachment) => attachment.name)).toEqual([+ 'sent.pdf',+ 'new-during-rtt.pdf',+ ]);+ });++ it('does not mirror an old owner attachment draft into a new owner with the same key', async () => {+ const key = 'shared-owner-switch-draft';+ setDataOwnerGeneration('owner-a');+ setComposerDraftOwner('owner-a');+ const { result, rerender, unmount } = renderHook(() => useAttachments(undefined, key));++ await act(async () => {+ await result.current.addFiles(fileListOf([{ name: 'owner-a.pdf', size: 128 }]));+ });+ expect(result.current.attachments.map((attachment) => attachment.name)).toEqual([+ 'owner-a.pdf',+ ]);++ act(() => {+ setDataOwnerGeneration('owner-b');+ setComposerDraftOwner('owner-b');+ rerender();+ });++ expect(result.current.attachments).toEqual([]);+ expect(getDraft(key)?.attachments ?? []).toEqual([]);+ unmount();++ setDataOwnerGeneration('owner-a');+ setComposerDraftOwner('owner-a');+ expect(getDraft(key)?.attachments.map((attachment) => attachment.name)).toEqual([+ 'owner-a.pdf',+ ]);+ clearDraft(key);+ setDataOwnerGeneration('owner-b');+ setComposerDraftOwner('owner-b');+ clearDraft(key);+ });++ it('writes a delayed file peek back to its captured session instead of the newly opened one', async () => {+ const peek = deferred<{ success: true; actualBytes: number; data: string }>();+ (window as unknown as { electronAPI: Record<string, unknown> }).electronAPI = {+ getFilePath: (file: { name: string }) => `/tmp/${file.name}`,+ peekFileHeader: vi.fn(() => peek.promise),+ cleanupCachedImages: vi.fn(async () => undefined),+ };+ const { result, rerender, unmount } = renderHook(+ ({ sid }: { sid: string }) => useAttachments(sid),+ { initialProps: { sid: 'attachment-session-A' } },+ );++ let pending!: Promise<void>;+ act(() => {+ pending = result.current.addFiles(fileListOf([{ name: 'README', size: 5 }]));+ });+ act(() => rerender({ sid: 'attachment-session-B' }));+ await act(async () => {+ peek.resolve({ success: true, actualBytes: 5, data: 'aGVsbG8=' });+ await pending;+ });++ expect(result.current.attachments).toEqual([]);+ expect(getDraft('attachment-session-A')?.attachments).toEqual([+ expect.objectContaining({ name: 'README' }),+ ]);+ expect(getDraft('attachment-session-B')?.attachments ?? []).toEqual([]);++ unmount();+ clearDraft('attachment-session-A');+ clearDraft('attachment-session-B');+ });++ it('keeps a delayed clipboard cache bound to the session captured before navigation', async () => {+ const arrayBuffer = deferred<ArrayBuffer>();+ const cacheImageFromBuffer = vi.fn(async () => ({+ url: 'xdt-image://attachment-session-A/clipboard.png',+ }));+ (window as unknown as { electronAPI: Record<string, unknown> }).electronAPI = {+ getFilePath: (file: { name: string }) => `/tmp/${file.name}`,+ cacheImageFromBuffer,+ cleanupCachedImages: vi.fn(async () => undefined),+ };+ const clipboardBlob = {+ type: 'image/png',+ size: 4,+ arrayBuffer: () => arrayBuffer.promise,+ } as Blob;+ const { result, rerender, unmount } = renderHook(+ ({ sid }: { sid: string }) => useAttachments(sid),+ { initialProps: { sid: 'attachment-session-A' } },+ );++ let pending!: Promise<void>;+ act(() => {+ pending = result.current.addClipboardImage(clipboardBlob);+ });+ act(() => rerender({ sid: 'attachment-session-B' }));+ await act(async () => {+ arrayBuffer.resolve(new Uint8Array([1, 2, 3, 4]).buffer);+ await pending;+ });++ expect(cacheImageFromBuffer).toHaveBeenCalledWith(+ expect.objectContaining({ sessionId: 'attachment-session-A' }),+ );+ expect(result.current.attachments).toEqual([]);+ expect(getDraft('attachment-session-A')?.attachments).toEqual([+ expect.objectContaining({ url: 'xdt-image://attachment-session-A/clipboard.png' }),+ ]);+ expect(getDraft('attachment-session-B')?.attachments ?? []).toEqual([]);+ expect(toastWarning).not.toHaveBeenCalled();++ unmount();+ clearDraft('attachment-session-A');+ clearDraft('attachment-session-B');+ });++ it('does not recreate an attachment draft when the session draft is discarded before unmount', async () => {+ const sessionId = 'discarded-attachment-session';+ const { result, unmount } = renderHook(() => useAttachments(sessionId));++ await act(async () => {+ await result.current.addFiles(fileListOf([{ name: 'discard-me.pdf', size: 128 }]));+ });+ expect(getDraft(sessionId)?.attachments).toEqual([+ expect.objectContaining({ name: 'discard-me.pdf' }),+ ]);++ act(() => discardDraft(sessionId));+ expect(result.current.attachments).toEqual([]);+ expect(getDraft(sessionId)).toBeUndefined();++ unmount();+ expect(getDraft(sessionId)).toBeUndefined();+ });++ it('recycles a delayed clipboard cache instead of restoring a discarded session draft', async () => {+ const sessionId = 'discarded-delayed-attachment-session';+ const cached = deferred<{ url: string }>();+ const cleanupCachedImages = vi.fn(async () => undefined);+ (window as unknown as { electronAPI: Record<string, unknown> }).electronAPI = {+ getFilePath: (file: { name: string }) => `/tmp/${file.name}`,+ cacheImageFromBuffer: vi.fn(() => cached.promise),+ cleanupCachedImages,+ };+ const clipboardBlob = {+ type: 'image/png',+ size: 1,+ arrayBuffer: async () => new Uint8Array([1]).buffer,+ } as Blob;+ const { result, unmount } = renderHook(() => useAttachments(sessionId));++ let pending!: Promise<void>;+ await act(async () => {+ pending = result.current.addClipboardImage(clipboardBlob);+ await Promise.resolve();+ });+ act(() => discardDraft(sessionId));+ await act(async () => {+ cached.resolve({ url: `xdt-image://${sessionId}/late.png` });+ await pending;+ });++ expect(result.current.attachments).toEqual([]);+ expect(getDraft(sessionId)).toBeUndefined();+ expect(cleanupCachedImages).toHaveBeenCalledWith([`xdt-image://${sessionId}/late.png`]);++ unmount();+ expect(getDraft(sessionId)).toBeUndefined();+ });++ it('drops and cleans a cached image when the data owner changes before completion', async () => {+ setDataOwnerGeneration('owner-a');+ setComposerDraftOwner('owner-a');+ const cached = deferred<{ url: string }>();+ const cleanupCachedImages = vi.fn(async () => undefined);+ (window as unknown as { electronAPI: Record<string, unknown> }).electronAPI = {+ getFilePath: (file: { name: string }) => `/tmp/${file.name}`,+ cacheImageFromBuffer: vi.fn(() => cached.promise),+ cleanupCachedImages,+ };+ const clipboardBlob = {+ type: 'image/png',+ size: 1,+ arrayBuffer: async () => new Uint8Array([1]).buffer,+ } as Blob;+ const { result, rerender, unmount } = renderHook(() =>+ useAttachments('owner-boundary-attachment-session'),+ );++ let pending!: Promise<void>;+ await act(async () => {+ pending = result.current.addClipboardImage(clipboardBlob);+ await Promise.resolve();+ });+ act(() => {+ setDataOwnerGeneration('owner-b');+ setComposerDraftOwner('owner-b');+ rerender();+ });+ await act(async () => {+ cached.resolve({ url: 'xdt-image://owner-a/late.png' });+ await pending;+ });++ expect(result.current.attachments).toEqual([]);+ expect(cleanupCachedImages).toHaveBeenCalledWith(['xdt-image://owner-a/late.png']);+ expect(result.current.rejections).toEqual([]);++ unmount();+ clearDraft('owner-boundary-attachment-session');+ setDataOwnerGeneration('owner-a');+ setComposerDraftOwner('owner-a');+ clearDraft('owner-boundary-attachment-session');+ });});diff --git a/apps/desktop/src/renderer/__tests__/voiceInputDraftScroll.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputDraftScroll.test.tsindex 357e0bcfee..67079ae203 100644--- a/apps/desktop/src/renderer/__tests__/voiceInputDraftScroll.test.ts+++ b/apps/desktop/src/renderer/__tests__/voiceInputDraftScroll.test.ts@@ -3,10 +3,7 @@ import path from 'node:path';import { describe, expect, it } from 'vitest';const root = path.resolve(__dirname, '..');-const chatInput = readFileSync(- path.join(root, 'components/new-chat/ChatInput.tsx'),- 'utf8',-);+const chatInput = readFileSync(path.join(root, 'components/new-chat/ChatInput.tsx'), 'utf8');const draftDecoration = readFileSync(path.join(root, 'components/new-chat/VoiceInputDraftDecoration.ts'),'utf8',@@ -16,10 +13,7 @@ describe('voice input draft scroll anchoring', () => {it('scrolls the live draft to the saved insertion range instead of the bottom', () => {const effectStart = chatInput.indexOf('setVoiceInputDraftDecoration(');expect(effectStart).toBeGreaterThan(-1);- const effectEnd = chatInput.indexOf(- '}, [editor, voiceCaretState, voiceInput.draftRange, voiceInput.draftSource, voiceInput.draftText]);',- effectStart,- );+ const effectEnd = chatInput.indexOf('// Route changes such as Chat -> Settings', effectStart);expect(effectEnd).toBeGreaterThan(effectStart);const effectBlock = chatInput.slice(effectStart, effectEnd);diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.tsindex 2535e74609..c32029770d 100644--- a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts+++ b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts@@ -19,8 +19,8 @@ describe('ChatInput voice input Enter-to-send contract', () => {'const handleKeyUp = (event: KeyboardEvent) => {',);- expect(chatInputSource).toContain(- 'const voiceInputStopAndSendRef = useRef<(deliveryMode?: MessageDeliveryMode) => void | Promise<void>>(() => {});',+ expect(chatInputSource).toMatch(+ /const voiceInputStopAndSendRef\s*=\s*useRef<\s*\(deliveryMode\?: MessageDeliveryMode\)\s*=>\s*void\s*\|\s*Promise<void>\s*>\(\(\)\s*=>\s*\{\}\);/,);expect(chatInputSource).toContain('const voiceInputCanStopAndSendRef = useRef(false);');expect(chatInputSource).toContain('voiceInputStopAndSendRef.current = handleClickSend;');@@ -47,7 +47,9 @@ describe('ChatInput voice input Enter-to-send contract', () => {'const handleKeyDown = (event: KeyboardEvent) => {',);- expect(keydownSetupBlock).toContain('const isVoiceInputEnterTarget = (target: EventTarget | null) => {');+ expect(keydownSetupBlock).toContain(+ 'const isVoiceInputEnterTarget = (target: EventTarget | null) => {',+ );expect(keydownSetupBlock).toContain('if (isComposerEnterTarget(target)) return true;');expect(keydownSetupBlock).toContain('target === document.body');expect(keydownSetupBlock).toContain('target === document.documentElement');@@ -75,7 +77,9 @@ describe('ChatInput voice input Enter-to-send contract', () => {expect(enterBlock).toContain("if (enterIntent === 'queue' || enterIntent === 'steer') {");expect(enterBlock).toContain("voiceInputStateRef.current === 'listening'");expect(enterBlock).toContain('voiceInputCanStopAndSendRef.current');- expect(enterBlock).toContain('const isEditorEnterTarget = event.target instanceof Node && view.dom.contains(event.target);');+ expect(enterBlock).toMatch(+ /const isEditorEnterTarget\s*=\s*event\.target instanceof Node\s*&&\s*view\.dom\.contains\(event\.target\);/,+ );expect(enterBlock).toContain('isEditorEnterTarget');expect(enterBlock).not.toContain('isComposerEnterTarget(event.target)');expect(enterBlock).toContain('!isVoiceInputShortcutMatch(event, voiceShortcutRef.current)');@@ -110,20 +114,24 @@ describe('ChatInput voice input Enter-to-send contract', () => {});it('allows release-to-send while listening before ASR draft arrives', () => {- expect(chatInputSource).toContain(- 'const canReleaseVoiceToSend = Boolean(!disabled && (voiceInput.isListening || canSend || hasVoiceDraftText));',+ expect(chatInputSource).toMatch(+ /const canReleaseVoiceToSend\s*=\s*Boolean\(\s*!disabled\s*&&\s*\(voiceInput\.isListening\s*\|\|\s*canSend\s*\|\|\s*hasVoiceDraftText\),?\s*\);/,);});it('keeps stop/refine/send alive when the active conversation changes', () => {const handleClickSendBlock = extractBetween(chatInputSource,- "const handleClickSend = useCallback(async (deliveryMode: MessageDeliveryMode = 'queue') => {",- 'useEffect(() => {\n voiceInputStopAndSendRef.current = handleClickSend;',+ 'const handleClickSend = useCallback(',+ 'voiceInputStopAndSendRef.current = handleClickSend;',);expect(handleClickSendBlock).toContain('voiceInput.isBusy');- expect(handleClickSendBlock).toContain('voiceInputStopAndSendPromiseRef.current = stopAndSend;');- expect(handleClickSendBlock).toContain("await handleVoiceInputStop({ waitForRefinement: true });");+ expect(handleClickSendBlock).toContain(+ 'voiceInputStopAndSendPromiseRef.current = stopAndSend;',+ );+ expect(handleClickSendBlock).toContain(+ 'await handleVoiceInputStop({ waitForRefinement: true });',+ );expect(handleClickSendBlock).toContain('Do not send the pre-existing draft/attachments');expect(handleClickSendBlock).toContain('catch {\n // Voice stop failures');expect(handleClickSendBlock).toContain('await dispatchSend(deliveryMode);');@@ -135,11 +143,14 @@ describe('ChatInput voice input Enter-to-send contract', () => {"// storageKey actually changed — swap the editor's content.",);expect(restoreEffectBlock).toContain('await pendingStopAndSend;');- expect(restoreEffectBlock).toContain("await voiceInputStopRef.current({ waitForRefinement: true });");+ expect(restoreEffectBlock).toContain(+ 'await voiceInputStopRef.current({ waitForRefinement: true });',+ );expect(restoreEffectBlock).toContain('if (isCurrentTransition()) {');expect(restoreEffectBlock).toContain('restoreNextDraft();');- expect(chatInputSource).toContain('}, [editor, storageKey, voiceInput.isBusy]);');- expect(chatInputSource).not.toContain('}, [editor, handleVoiceInputStop, storageKey, voiceInput.isBusy]);');+ expect(restoreEffectBlock).toContain('pendingStopAndSend || voiceInputBusyRef.current');+ expect(chatInputSource).toContain('}, [editor, storageKey]);');+ expect(chatInputSource).not.toContain('}, [editor, storageKey, voiceInput.isBusy]);');});it('keeps storageKey hydration and stop completion safe across switch races', () => {@@ -156,7 +167,9 @@ describe('ChatInput voice input Enter-to-send contract', () => {'const transitionSeq = storageKeyTransitionSeqRef.current + 1;',"// storageKey actually changed — swap the editor's content.",);- expect(chatInputSource).toContain('const latestStorageKeyRef = useRef<string | undefined>(storageKey);');+ expect(chatInputSource).toContain(+ 'const latestStorageKeyRef = useRef<string | undefined>(storageKey);',+ );expect(restoreEffectBlock).toContain('if (!hasHydratedRef.current) return;');expect(restoreEffectBlock).toContain('let cancelled = false;');expect(restoreEffectBlock).toContain('!cancelled');@@ -171,9 +184,15 @@ describe('ChatInput voice input Enter-to-send contract', () => {'const stop = useCallback(async (options?: VoiceInputStopOptions) => {',);expect(voiceInputSource).toContain('type StopCompletionWaiter = {');- expect(voiceInputSource).toContain('const stopCompletionWaitersRef = useRef<StopCompletionWaiter[]>([]);');- expect(waitForBusyCompletionBlock).toContain('stopCompletionWaitersRef.current = [...stopCompletionWaitersRef.current, waiter];');- expect(waitForBusyCompletionBlock).toContain('stopCompletionWaitersRef.current.filter((item) => item !== waiter)');+ expect(voiceInputSource).toContain(+ 'const stopCompletionWaitersRef = useRef<StopCompletionWaiter[]>([]);',+ );+ expect(waitForBusyCompletionBlock).toContain(+ 'stopCompletionWaitersRef.current = [...stopCompletionWaitersRef.current, waiter];',+ );+ expect(waitForBusyCompletionBlock).toContain(+ 'stopCompletionWaitersRef.current.filter((item) => item !== waiter)',+ );const resolveStopCompletionBlock = extractBetween(voiceInputSource,@@ -190,9 +209,15 @@ describe('ChatInput voice input Enter-to-send contract', () => {);expect(stopBlock).toContain("if (stateRef.current === 'error')");expect(stopBlock).toContain("throw new Error(lastErrorRef.current ?? 'Voice input failed.')");- expect(stopBlock).toContain('const stopWithGate = useCallback(async (options?: VoiceInputStopOptions) => {');- expect(stopBlock).toContain('if (stopInFlightPromiseRef.current) return stopInFlightPromiseRef.current;');- expect(voiceInputSource).toContain('const stopInFlightPromiseRef = useRef<Promise<void> | null>(null);');+ expect(stopBlock).toContain(+ 'const stopWithGate = useCallback(async (options?: VoiceInputStopOptions) => {',+ );+ expect(stopBlock).toContain(+ 'if (stopInFlightPromiseRef.current) return stopInFlightPromiseRef.current;',+ );+ expect(voiceInputSource).toContain(+ 'const stopInFlightPromiseRef = useRef<Promise<void> | null>(null);',+ );expect(stopBlock).toContain('throw new Error(startResult.error);');const startFailureBlock = extractBetween(stopBlock,@@ -209,15 +234,31 @@ describe('ChatInput voice input Enter-to-send contract', () => {});it('waits for refinement before finishing a plain voice stop', () => {- expect(chatInputSource).toContain('const handleVoiceInputPlainStop = useCallback(() => (');+ expect(chatInputSource).toMatch(+ /const handleVoiceInputPlainStop\s*=\s*useCallback\(\s*\(\)\s*=>\s*handleVoiceInputStop\(\{ waitForRefinement: true \}\)\.catch\(\(\)\s*=>\s*undefined\)/,+ );expect(chatInputSource).toContain('handleVoiceInputStop({ waitForRefinement: true })');- expect(chatInputSource).toContain('handleVoiceInputStop({ waitForRefinement: true }).catch(() => undefined)');- expect(chatInputSource).toContain('const handleVoiceInputStopWithRefinement = useCallback((options?: { waitForRefinement?: boolean }) => (');- expect(chatInputSource).toContain('handleVoiceInputStop({ waitForRefinement: options?.waitForRefinement ?? true })');- expect(chatInputSource).toContain('handleVoiceInputStop({ waitForRefinement: options?.waitForRefinement ?? true }).catch(() => undefined)');- expect(chatInputSource).toContain('const voiceInputStopRef = useRef(handleVoiceInputStopWithRefinement);');- expect(chatInputSource).toContain('voiceInputStopRef.current = handleVoiceInputStopWithRefinement;');- expect(chatInputSource).toContain('await voiceInputStopRef.current({ waitForRefinement: true });');+ expect(chatInputSource).toMatch(+ /handleVoiceInputStop\(\{ waitForRefinement: true \}\)\.catch\(\(\)\s*=>\s*undefined\)/,+ );+ expect(chatInputSource).toMatch(+ /const handleVoiceInputStopWithRefinement\s*=\s*useCallback\(\s*\(options\?: \{ waitForRefinement\?: boolean \}\)\s*=>/,+ );+ expect(chatInputSource).toContain(+ 'handleVoiceInputStop({ waitForRefinement: options?.waitForRefinement ?? true })',+ );+ expect(chatInputSource).toMatch(+ /handleVoiceInputStop\(\{ waitForRefinement: options\?\.waitForRefinement \?\? true \}\)\.catch\(\s*\(\)\s*=>\s*undefined,?\s*\)/,+ );+ expect(chatInputSource).toContain(+ 'const voiceInputStopRef = useRef(handleVoiceInputStopWithRefinement);',+ );+ expect(chatInputSource).toContain(+ 'voiceInputStopRef.current = handleVoiceInputStopWithRefinement;',+ );+ expect(chatInputSource).toContain(+ 'await voiceInputStopRef.current({ waitForRefinement: true });',+ );expect(chatInputSource).toContain('onStop={handleVoiceInputPlainStop}');});diff --git a/apps/desktop/src/renderer/cindy-brain/ghostMediaHandover.ts b/apps/desktop/src/renderer/cindy-brain/ghostMediaHandover.tsindex c1c3f6f9ed..6b7ad5ccb4 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostMediaHandover.ts+++ b/apps/desktop/src/renderer/cindy-brain/ghostMediaHandover.ts@@ -100,10 +100,14 @@ export async function attachGhostMediaToSession(/** 把一条附件合入会话草稿(托盘可见;其余草稿字段原样保留)。 */function appendDraftAttachment(sessionId: string, attached: AttachedFile): void {const existing = getDraft(sessionId);- saveDraft(sessionId, {- text: existing?.text ?? null,- attachments: [...(existing?.attachments ?? []), attached],- quotes: existing?.quotes ?? [],- browserComments: existing?.browserComments ?? [],- });+ saveDraft(+ sessionId,+ {+ text: existing?.text ?? null,+ attachments: [...(existing?.attachments ?? []), attached],+ quotes: existing?.quotes ?? [],+ browserComments: existing?.browserComments ?? [],+ },+ { preserveRemoteOptimisticRecovery: true },+ );}diff --git a/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx b/apps/desktop/src/renderer/components/chat/ImageLightbox.tsxindex 2de03ea35f..1c53ef15c1 100644--- a/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx+++ b/apps/desktop/src/renderer/components/chat/ImageLightbox.tsx@@ -226,7 +226,9 @@ function isDirectCacheable(src: string): boolean {if (/^https?:\/\//.test(src)) return true;if (DIRECT_CACHEABLE_DATA_RE.test(src)) return true;const localFilePath = xdtFileUrlToPath(src);- return localFilePath !== null && DIRECT_CACHEABLE_EXTS.has(extractExt(localFilePath).toLowerCase());+ return (+ localFilePath !== null && DIRECT_CACHEABLE_EXTS.has(extractExt(localFilePath).toLowerCase())+ );}/** 左右翻页圆形按钮的内联样式。lightbox overlay 不走 Tailwind,这里同样用内联。 */@@ -283,11 +285,8 @@ const counterStyle: React.CSSProperties = {* 对应,activeIndex 才准。*/function collectGallery(): { items: GalleryImage[]; activeIndex: number } {- const root: ParentNode =- document.querySelector('[data-scroll-container]') ?? document;- const els = Array.from(- root.querySelectorAll<HTMLElement>('[data-gallery-src]'),- );+ const root: ParentNode = document.querySelector('[data-scroll-container]') ?? document;+ const els = Array.from(root.querySelectorAll<HTMLElement>('[data-gallery-src]'));const items: GalleryImage[] = [];let activeIndex = -1;els.forEach((el, i) => {@@ -299,11 +298,9 @@ function collectGallery(): { items: GalleryImage[]; activeIndex: number } {/** 清掉所有遗留的 `data-gallery-active` 临时标记(lightbox 读取起始下标后调用)。 */function clearGalleryActiveMarks(): void {- document- .querySelectorAll<HTMLElement>('[data-gallery-active]')- .forEach((el) => {- delete el.dataset.galleryActive;- });+ document.querySelectorAll<HTMLElement>('[data-gallery-active]').forEach((el) => {+ delete el.dataset.galleryActive;+ });}/**@@ -422,9 +419,7 @@ export function ImageLightbox({);// 已保存的笔迹起步(托盘编辑或历史图再编辑)——"撤销之前的编辑"就是从// 这里往回 pop。- const [strokes, setStrokes] = useState<AnnotationStroke[]>(() => [- ...baselineStrokesRef.current,- ]);+ const [strokes, setStrokes] = useState<AnnotationStroke[]>(() => [...baselineStrokesRef.current]);const [draftStroke, setDraftStroke] = useState<AnnotationStroke | null>(null);const [isDrawing, setIsDrawing] = useState(false);// 图片自然尺寸:SVG viewBox 与烧录 canvas 的坐标基准。onLoad 时设置。@@ -790,9 +785,7 @@ export function ImageLightbox({// 打开期间锁住聊天滚动容器。useEffect(() => {- const container = document.querySelector(- '[data-scroll-container]',- ) as HTMLElement | null;+ const container = document.querySelector('[data-scroll-container]') as HTMLElement | null;if (container) container.style.overflowY = 'hidden';return () => {if (container) container.style.overflowY = '';@@ -822,7 +815,13 @@ export function ImageLightbox({})();const canRevealRemote = Boolean(chatSessionId && remoteWorkdirRelPath);const hasAnyAction =- canCopy || canReveal || canRevealRemote || canOpenWith || canSaveAs || canSendToChat || canOpenInBrowser;+ canCopy ||+ canReveal ||+ canRevealRemote ||+ canOpenWith ||+ canSaveAs ||+ canSendToChat ||+ canOpenInBrowser;// 画笔入口:发送场景要求能发送到对话(标注的出口是发送);编辑场景(托盘)// 出口是保存,不要求会话。源条件 = 字节可达(五种来源全覆盖:http/remote@@ -1036,12 +1035,16 @@ export function ImageLightbox({}}const existing = getDraft(chatSessionId);- saveDraft(chatSessionId, {- text: existing?.text ?? null,- attachments: [...(existing?.attachments ?? []), attached],- quotes: existing?.quotes ?? [],- browserComments: existing?.browserComments ?? [],- });+ saveDraft(+ chatSessionId,+ {+ text: existing?.text ?? null,+ attachments: [...(existing?.attachments ?? []), attached],+ quotes: existing?.quotes ?? [],+ browserComments: existing?.browserComments ?? [],+ },+ { preserveRemoteOptimisticRecovery: true },+ );toast.success(t('chat.media.sentToChat'));handleClose();} catch (err) {@@ -1303,7 +1306,10 @@ export function ImageLightbox({)}onClick={(e) => e.stopPropagation()}>- <LightboxToolbarButton onClick={discardAnnotation} label={t('chat.media.annotateDiscard')}>+ <LightboxToolbarButton+ onClick={discardAnnotation}+ label={t('chat.media.annotateDiscard')}+ ><X className="h-4 w-4" /></LightboxToolbarButton><LightboxToolbarButton onClick={undoLastStroke} label={t('chat.media.annotateUndo')}>@@ -1344,7 +1350,10 @@ export function ImageLightbox({</LightboxToolbarButton>) : null}{canOpenInBrowser ? (- <LightboxToolbarButton onClick={handleOpenInBrowser} label={t('chat.media.openInBrowser')}>+ <LightboxToolbarButton+ onClick={handleOpenInBrowser}+ label={t('chat.media.openInBrowser')}+ ><Globe className="h-4 w-4" /></LightboxToolbarButton>) : null}diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 336a731fe6..c05ea7980a 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -84,11 +84,20 @@ import { shouldOpenTextLightbox } from '@/lib/filePreview';import { isDangerousAttachmentName } from '../../../shared/attachmentSafety';import {getDraft as getComposerDraft,+ getOrCreateRemoteOptimisticTransitionCheckpoint,+ removeRemoteOptimisticDraftFragment,+ type RemoteOptimisticTransitionCheckpoint,saveDraft as saveComposerDraft,+ saveComposerTextAfterAsyncTransition,clearDraft as clearComposerDraft,+ restoreRemoteOptimisticDraft,subscribeDraft as subscribeComposerDraft,tiptapDocHasContent,} from '@/lib/composerDraftStore';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';import { subscribeSessionLinkInsert } from '@/lib/composerActionsBus';import {ModelSelector,@@ -101,10 +110,7 @@ import {getEffortChangeCoordinator,isSessionScopeCurrent,} from './effortChangeQueue';-import {- captureComposerSendSnapshot,- isComposerSendSnapshotCurrent,-} from './composerSendSnapshot';+import { captureComposerSendSnapshot, isComposerSendSnapshotCurrent } from './composerSendSnapshot';import { useRemoteSessionConnection } from '@/features/cc-agent/hooks/useRemoteSessionConnection';import {@@ -160,6 +166,7 @@ import { deriveStableComposerHistory } from './composerHistoryProjection';import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';import {pastedSessionChipAttrs,+ resolveSerializedSessionMessageReferencesForSend,resolveSessionMessageReferencesForSend,resolveSessionChipTitles,sanitizeSessionChipTitle,@@ -255,7 +262,12 @@ import {setFastModeForModel,} from '@/state/newMakerDraft';import type { MessageDeliveryMode, QueuedMessage } from '@/lib/makerChatStore';-import { makerChatStore } from '@/lib/makerChatStore';+import {+ isRemoteOptimisticComposerTransitionActive,+ isRemoteOptimisticDataOwnerBoundaryError,+ isRemoteOptimisticSessionPurgedError,+ makerChatStore,+} from '@/lib/makerChatStore';// 切模型前的上下文容量预检(大窗口 → 小窗口护栏), 纯函数与 main 共用。import { assessModelSwitchContext } from '../../../shared/modelSwitchAssessment';import { useVoiceInput } from '@/voice-input/useVoiceInput';@@ -352,6 +364,10 @@ interface ChatInputProps {* false(未接受)语义解耦。*/onAccepted?: () => void;+ /** 远端乐观发送稍后永久失败时恢复本地 composer。 */+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;+ /** 发送因补选目录暂缓时,由父组件在后续真正受理后完成原 composer 的清理。 */+ onDeferredAccepted?: () => void;},) => boolean | void | Promise<boolean | void>;/** Session ID for binding workingDir. When absent, folder picker is hidden. */@@ -529,6 +545,7 @@ interface ChatInputProps {removeFile: (id: string) => void;updateFile: (id: string, patch: Partial<AttachedFile>) => void;discardFiles: () => void;+ restoreFiles: (files: readonly AttachedFile[]) => AttachedFile[];clearFiles: () => void;};/**@@ -1075,6 +1092,10 @@ export function ChatInput({// During voice-input session switches this can intentionally lag behind the// prop `storageKey` until the old stop/refine/send transaction is complete.const storageKeyForDraftRef = useRef<string | undefined>(storageKey);+ // The editor owns both a raw storageKey and the data-owner generation that+ // qualified it. Stale effects must never reinterpret an old editor as the+ // newly published owner just because the raw session id is unchanged.+ const editorDataOwnerRef = useRef(getDataOwnerGeneration());// composer-draft-mount-race 修复 (issue #40):Tiptap 的 useEditor 在 mount 期间// 会因为我们挂的 decoration 扩展 (CjkPunctDecoration / VoiceInputDraftDecoration)// 触发一次 onUpdate,这次 onUpdate 跑在 React 的 useEffect 之前(早 4ms 量级),@@ -1109,10 +1130,11 @@ export function ChatInput({removeFile,updateFile,discardFiles,+ restoreFiles,clearFiles,} = attachmentState;- const attachmentsRef = useRef(attachments);- attachmentsRef.current = attachments;+ const latestAttachmentsRef = useRef(attachments);+ latestAttachmentsRef.current = attachments;// browser-comment-chip:内置浏览器页面评论(结构化,不进草稿文本),渲染为// 「N 条注释」胶囊,发送时序列化 + 截图并入 filesToSend。const [browserComments, setBrowserComments] = useState<BrowserCommentDraftItem[]>([]);@@ -1211,9 +1233,8 @@ export function ChatInput({// initialModel/initialEffort 缺失的瞬态(会话快照未加载)兜底:读本地草稿 lastByVendor// (localStorage,按 agent 分槽、sanitize 恒有种子值)。默认模型/档位偏好已全量本地化,// 不再依赖服务端 UserPreferences(登录态失效/离线时模型与档位选择必须照常工作)。- const localVendorDefaults = getDraft().lastByVendor[- vendorKey === 'pi' ? 'pi' : vendorKey === 'codex' ? 'codex' : 'cc'- ];+ const localVendorDefaults =+ getDraft().lastByVendor[vendorKey === 'pi' ? 'pi' : vendorKey === 'codex' ? 'codex' : 'cc'];// session-agent-switch 意图制:意图期内 chip / 选择器显示用户选择的目标// (model/effort/provider/fast),props(镜像 DB)仍是旧引擎值——真切换在下一条// 消息发送时刻 apply,patched 回流后意图清除、显示交回 props。意图存放在@@ -1362,8 +1383,7 @@ export function ChatInput({// 与下拉菜单看到的顺序一致。vendorKey 未锁定时按 PermissionSelector 的// 默认取 cc。editorProps.handleKeyDown 是稳定闭包, 走 ref 取值。const permissionCycleOptions = useMemo(- () =>- activeAgentCapabilities?.permissionModes ?? [],+ () => activeAgentCapabilities?.permissionModes ?? [],[activeAgentCapabilities],);const permissionCycleOptionsRef = useRef(permissionCycleOptions);@@ -1376,8 +1396,7 @@ export function ChatInput({);// 计划模式入口门控:agent capability(device-link 老被控端无此字段 → 隐藏)+ 父组件接线。- const planModeSupported =- activeAgentCapabilities?.planMode?.supported === true;+ const planModeSupported = activeAgentCapabilities?.planMode?.supported === true;const planModeEntry =planModeSupported && onPlanModeChange? { enabled: planModeEnabled, onToggle: (next: boolean) => void onPlanModeChange(next) }@@ -1415,10 +1434,7 @@ export function ChatInput({// 排除项),两者职责分离以保留 remote guard。// 本机沿用 useConnectedSource 的加载态;device-link 必须同时等待被控端 capabilities 与// provider 目录,且真实读取失败时 fail closed。只有结构化 unsupported 才允许旧端回退。- const { loading: localProvidersLoading } = useConnectedSource(- currentModelAgentKind,- activeModel,- );+ const { loading: localProvidersLoading } = useConnectedSource(currentModelAgentKind, activeModel);const remoteModelListStatus = resolveRemoteModelListStatus({deviceId: deviceLinkDeviceId,agentKind: currentModelAgentKind,@@ -1430,8 +1446,12 @@ export function ChatInput({const providersLoading = deviceLinkDeviceId? remoteModelListStatus === 'loading': localProvidersLoading;+ // 已有 device-link 任务在断链时仍有 pinned deviceId + renderer outbox 可接住发送,+ // 不能因为被控端 provider 目录暂时拉不到就禁用 composer。远程草稿没有既有 session+ // 可以排队,仍与本地任务一样保留来源门禁。+ const enforceConnectedSourceGate = !sessionId || !deviceLinkDeviceId;const remoteModelListBlocked =- !!deviceLinkDeviceId && remoteModelListStatus !== 'ready';+ !!deviceLinkDeviceId && enforceConnectedSourceGate && remoteModelListStatus !== 'ready';// chatEligibleSourcesForModel(不是裸 sourcesForModel):非聊天模型即便"存在于某个// 已连接来源"也不算有可发送来源(issue #882 第 3 点,2026-07 review)——否则 Send// 会对着一个 image/embedding 端点放行,而不是显示这里的"去连接"空态。已建会话@@ -1445,6 +1465,7 @@ export function ChatInput({}).length > 0: false;const noConnectedSource =+ enforceConnectedSourceGate &&!!currentModelAgentKind &&!providersLoading &&!remoteModelListBlocked &&@@ -1552,14 +1573,14 @@ export function ChatInput({const refreshComposerRef = useRef<(() => void) | null>(null);refreshComposerRef.current = () => setTick((t) => t + 1);const renderSnapshotRef = useRef<ComposerRenderSnapshot | null>(null);- const draftSaveSchedulerRef = useRef<ReturnType<- typeof createComposerDraftSaveScheduler- > | null>(null);+ const draftSaveSchedulerRef = useRef<ReturnType<typeof createComposerDraftSaveScheduler> | null>(+ null,+ );draftSaveSchedulerRef.current ??= createComposerDraftSaveScheduler();const caretScrollEditorRef = useRef<Editor | null>(null);- const caretScrollSchedulerRef = useRef<ReturnType<- typeof createComposerFrameScheduler- > | null>(null);+ const caretScrollSchedulerRef = useRef<ReturnType<typeof createComposerFrameScheduler> | null>(+ null,+ );caretScrollSchedulerRef.current ??= createComposerFrameScheduler(() => {const current = caretScrollEditorRef.current;if (current) scrollCaretIntoView(current);@@ -2070,11 +2091,10 @@ export function ChatInput({// Native mode keeps Enter available to Tiptap for paragraph breaks and// IME composition; queue/steer modes continue through the existing// send and voice state machines.- const enterIntent = resolveComposerEnterIntent(- event,- getComposerSendShortcutPreference(),- { turnRunning: showStopButtonRef.current, platform: window.electronAPI?.platform },- );+ const enterIntent = resolveComposerEnterIntent(event, getComposerSendShortcutPreference(), {+ turnRunning: showStopButtonRef.current,+ platform: window.electronAPI?.platform,+ });if (enterIntent === 'native') return false;if (enterIntent === 'ignore') {event.preventDefault();@@ -2084,7 +2104,8 @@ export function ChatInput({event.preventDefault();if (enterIntent === 'queue' || enterIntent === 'steer') {- const isEditorEnterTarget = event.target instanceof Node && view.dom.contains(event.target);+ const isEditorEnterTarget =+ event.target instanceof Node && view.dom.contains(event.target);if (voiceInputStateRef.current === 'listening' &&voiceInputCanStopAndSendRef.current &&@@ -2112,11 +2133,7 @@ export function ChatInput({listPromotionQueuedRef.current = true;queueMicrotask(() => {listPromotionQueuedRef.current = false;- if (- !ed.isDestroyed &&- !suppressListNormalizationRef.current &&- !ed.view.composing- ) {+ if (!ed.isDestroyed && !suppressListNormalizationRef.current && !ed.view.composing) {promoteTrailingPlainListParagraph(ed.view);}});@@ -2152,6 +2169,7 @@ export function ChatInput({scheduleCaretScroll(ed);return;}+ const dataOwnerAtSchedule = editorDataOwnerRef.current;// silent: 自己写自己——不通知 subscribeComposerDraft 监听器,避免回灌// setContent 把光标位置/IME 组合状态打乱。把 JSON 序列化和写入都放进短// debounce,生命周期边界由 flush 强制落最后一版。@@ -2168,6 +2186,7 @@ export function ChatInput({// 跳过这次写入(旧会话的最终内容已由 saveCurrentEditorDraft 在切换前存妥)。draftSaveSchedulerRef.current?.schedule(() => {if (storageKeyForDraftRef.current !== sk) return;+ if (!isDataOwnerGenerationCurrent(dataOwnerAtSchedule)) return;const existing = getComposerDraft(sk);saveComposerDraft(sk,@@ -2466,18 +2485,27 @@ export function ChatInput({},[voiceInput.stop, playVoiceInputEndCueNow],);- const handleVoiceInputPlainStop = useCallback(() => (- handleVoiceInputStop({ waitForRefinement: true }).catch(() => undefined)- ), [handleVoiceInputStop]);- const handleVoiceInputStopWithRefinement = useCallback((options?: { waitForRefinement?: boolean }) => (- handleVoiceInputStop({ waitForRefinement: options?.waitForRefinement ?? true }).catch(() => undefined)- ), [handleVoiceInputStop]);+ const handleVoiceInputPlainStop = useCallback(+ () => handleVoiceInputStop({ waitForRefinement: true }).catch(() => undefined),+ [handleVoiceInputStop],+ );+ const handleVoiceInputStopWithRefinement = useCallback(+ (options?: { waitForRefinement?: boolean }) =>+ handleVoiceInputStop({ waitForRefinement: options?.waitForRefinement ?? true }).catch(+ () => undefined,+ ),+ [handleVoiceInputStop],+ );const voiceShortcutRef = useRef(voiceInputSettings.shortcut);const voiceInputStateRef = useRef(voiceInput.state);const voiceInputStopRef = useRef(handleVoiceInputStopWithRefinement);+ const voiceInputBusyRef = useRef(voiceInput.isBusy);+ voiceInputBusyRef.current = voiceInput.isBusy;const voiceInputCancelRef = useRef(voiceInput.cancel);- const voiceInputStopAndSendRef = useRef<(deliveryMode?: MessageDeliveryMode) => void | Promise<void>>(() => {});+ const voiceInputStopAndSendRef = useRef<+ (deliveryMode?: MessageDeliveryMode) => void | Promise<void>+ >(() => {});const voiceInputStopAndSendPromiseRef = useRef<Promise<void> | null>(null);const voiceInputCanStopAndSendRef = useRef(false);const composerCanSubmitRef = useRef(false);@@ -2491,7 +2519,9 @@ export function ChatInput({const latestStorageKeyRef = useRef<string | undefined>(storageKey);const currentStorageKeyRef = useRef<string | undefined>(storageKey);currentStorageKeyRef.current = storageKey;+ latestStorageKeyRef.current = storageKey;const storageKeyTransitionSeqRef = useRef(0);+ const storageKeyTransitionRecoveryRef = useRef<RemoteOptimisticTransitionCheckpoint | null>(null);const sendButtonRef = useRef<HTMLElement | null>(null);const voiceShortcutPressRef = useRef<{shortcut: VoiceInputShortcut;@@ -2575,11 +2605,10 @@ export function ChatInput({}}- const enterIntent = resolveComposerEnterIntent(- event,- getComposerSendShortcutPreference(),- { turnRunning: showStopButtonRef.current, platform },- );+ const enterIntent = resolveComposerEnterIntent(event, getComposerSendShortcutPreference(), {+ turnRunning: showStopButtonRef.current,+ platform,+ });const isModifiedEnter = hasComposerModifier(event, platform);if (isComposerEnterTarget(event.target) &&@@ -2841,14 +2870,25 @@ export function ChatInput({if (editor) scrollVoiceInputDraftEndIntoView(editor);});}- }, [editor, voiceCaretState, voiceInput.draftRange, voiceInput.draftSource, voiceInput.draftText]);+ }, [+ editor,+ voiceCaretState,+ voiceInput.draftRange,+ voiceInput.draftSource,+ voiceInput.draftText,+ ]);// Route changes such as Chat -> Settings unmount the composer immediately.// `onUpdate` is still the primary "instant save" path, but this cleanup// snapshots the final editor state before React tears the instance down.useEffect(() => {if (!editor) return;+ const dataOwnerAtEffect = editorDataOwnerRef.current;return () => {+ if (!isDataOwnerGenerationCurrent(dataOwnerAtEffect)) {+ draftSaveSchedulerRef.current?.cancel();+ return;+ }draftSaveSchedulerRef.current?.flush();const editorStorageKey = storageKeyForDraftRef.current;if (!editorStorageKey) return;@@ -2882,6 +2922,7 @@ export function ChatInput({// hydrate the initial key's draft if one exists.useEffect(() => {if (!editor) return;+ const dataOwnerAtTransition = getDataOwnerGeneration();latestStorageKeyRef.current = storageKey;const prevEditorKey = editorStorageKeyRef.current;const storageKeyFocusAnchor = document.activeElement;@@ -2889,6 +2930,7 @@ export function ChatInput({// (Possible when only `editor` flipped to non-null but the key// was already current.)if (prevEditorKey === storageKey) {+ storageKeyTransitionRecoveryRef.current = null;// First-mount hydration path: the editor just became available for// the *current* storageKey — check the store once.// We detect "first-mount" by an editorStorageKeyRef that matches the@@ -2899,11 +2941,10 @@ export function ChatInput({const draft = getComposerDraft(storageKey);// 判空同外部草稿订阅:草稿正文可能是「空文档 JSON」而不是 undefined。此时// 编辑器本来就是空的,setContent 只会原地重建 doc(replace(0, size)),把按- // 位置存活的状态(语音插入点、草稿装饰锚点)推到 block 边界上。本 effect 依赖- // voiceInput.isBusy,录音开始与结束各会重跑一次——新建对话页的草稿键固定、- // 常留着一份空正文,于是上屏文字前凭空多出一个空行。- const draftDocument =- draft?.text && tiptapDocHasContent(draft.text) ? draft.text : null;+ // 位置存活的状态(语音插入点、草稿装饰锚点)推到 block 边界上。此前把+ // voiceInput.isBusy 放进依赖时,录音开始与结束各会重跑一次——新建对话页的+ // 草稿键固定、常留着一份空正文,于是上屏文字前凭空多出一个空行。+ const draftDocument = draft?.text && tiptapDocHasContent(draft.text) ? draft.text : null;if (draftDocument && composerDocIsEmpty(editor.state.doc)) {isRestoringRef.current = true;try {@@ -2915,6 +2956,7 @@ export function ChatInput({}editorStorageKeyRef.current = storageKey;storageKeyForDraftRef.current = storageKey;+ editorDataOwnerRef.current = dataOwnerAtTransition;// composer-draft-mount-race 修复 (issue #40):放行后续 onUpdate 写 store。hasHydratedRef.current = true;if (@@ -2934,6 +2976,14 @@ export function ChatInput({const transitionSeq = storageKeyTransitionSeqRef.current + 1;storageKeyTransitionSeqRef.current = transitionSeq;+ const transitionRecovery = prevEditorKey+ ? getOrCreateRemoteOptimisticTransitionCheckpoint(+ storageKeyTransitionRecoveryRef.current,+ prevEditorKey,+ )+ : null;+ storageKeyTransitionRecoveryRef.current = transitionRecovery;+ const recoveryCheckpoint = transitionRecovery?.checkpoint ?? null;draftSaveSchedulerRef.current?.flush();const saveCurrentEditorDraft = () => {if (!prevEditorKey) return;@@ -2941,22 +2991,14 @@ export function ChatInput({const existing = getComposerDraft(prevEditorKey);const hasText = !isEditorEmpty(editor);if (!hasText && !existing) return;- saveComposerDraft(- prevEditorKey,- {- text: editor.getJSON(),- attachments: existing?.attachments ?? [],- quotes: existing?.quotes ?? [],- browserComments: existing?.browserComments ?? [],- },- { silent: true },- );+ saveComposerTextAfterAsyncTransition(prevEditorKey, editor.getJSON(), recoveryCheckpoint!);};let cancelled = false;const isCurrentTransition = () =>!cancelled &&!editor.isDestroyed &&+ isDataOwnerGenerationCurrent(dataOwnerAtTransition) &&storageKeyTransitionSeqRef.current === transitionSeq &&latestStorageKeyRef.current === storageKey;@@ -2975,6 +3017,8 @@ export function ChatInput({}editorStorageKeyRef.current = storageKey;storageKeyForDraftRef.current = storageKey;+ editorDataOwnerRef.current = dataOwnerAtTransition;+ storageKeyTransitionRecoveryRef.current = null;hasHydratedRef.current = true;// Reset history-browse bookkeeping when switching sessions —@@ -2996,7 +3040,7 @@ export function ChatInput({};const pendingStopAndSend = voiceInputStopAndSendPromiseRef.current;- if (pendingStopAndSend || voiceInput.isBusy) {+ if (pendingStopAndSend || voiceInputBusyRef.current) {void (async () => {try {if (pendingStopAndSend) {@@ -3019,7 +3063,7 @@ export function ChatInput({// storageKey actually changed — swap the editor's content.saveCurrentEditorDraft();restoreNextDraft();- }, [editor, storageKey, voiceInput.isBusy]);+ }, [editor, storageKey]);// ── External draft writes for the CURRENT session (e.g. rewind / fork// pre-fill called saveComposerDraft from outside) ──@@ -3030,10 +3074,14 @@ export function ChatInput({// so they don't loop back.useEffect(() => {if (!editor || !storageKey) return;+ const dataOwnerAtSubscription = editorDataOwnerRef.current;return subscribeComposerDraft(storageKey, () => {+ if (!isDataOwnerGenerationCurrent(dataOwnerAtSubscription)) return;const draft = getComposerDraft(storageKey);if (!draft) return;- setBrowserComments(draft.browserComments ?? []);+ const nextBrowserComments = [...(draft.browserComments ?? [])];+ browserCommentsRef.current = nextBrowserComments;+ setBrowserComments(nextBrowserComments);// 同值外部写入不做全量 setContent,避免把用户停在中段的光标弹到末尾、// 打断 IME 组合。appendQuoteToDraft 会改变正文文档,自然走下方 setContent。// 空草稿在存储里可能是 `{doc:[空 paragraph]}` 而不是 undefined,而右侧对@@ -3106,11 +3154,14 @@ export function ChatInput({// browser-comment-chip:挂载 / 会话切换时从草稿恢复评论胶囊。useEffect(() => {if (!storageKey) {+ browserCommentsRef.current = [];setBrowserComments([]);return;}const draft = getComposerDraft(storageKey);- setBrowserComments(draft?.browserComments ?? []);+ const nextBrowserComments = [...(draft?.browserComments ?? [])];+ browserCommentsRef.current = nextBrowserComments;+ setBrowserComments(nextBrowserComments);}, [storageKey]);/** browser-comment-chip:按 id 删除单条 / 清空全部评论。同步镜像 state 与@@ -3122,6 +3173,7 @@ export function ChatInput({* 截图前的 validMarkerNumbers 对账剪除。 */const updateBrowserComments = useCallback((next: BrowserCommentDraftItem[]) => {+ browserCommentsRef.current = next;setBrowserComments(next);if (storageKey) {const existing = getComposerDraft(storageKey);@@ -3740,33 +3792,75 @@ export function ChatInput({if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;if (dispatchSendInFlightRef.current) return;const sourceSessionId = sessionId;+ const sourceStorageKey = storageKey;+ const optimisticallyClearRemoteComposer = Boolean(deviceLinkDeviceId && sourceSessionId);+ // Device-link sends freeze the entire composer at click time. Any remote+ // reference hydration happens against this immutable payload after the+ // live composer is cleared, so the user can immediately type the next+ // message without it leaking into or being cleared by this send.+ const serializedAtClick = optimisticallyClearRemoteComposer+ ? serializeEditorContent(editor)+ : null;+ const documentBeforeOptimisticClear = optimisticallyClearRemoteComposer+ ? editor.getJSON()+ : null;+ const attachmentsBeforeOptimisticClear = optimisticallyClearRemoteComposer+ ? [...latestAttachmentsRef.current]+ : [];+ const commentsBeforeOptimisticClear = optimisticallyClearRemoteComposer+ ? [...browserCommentsRef.current]+ : [];+ const dataOwnerAtOptimisticClear = optimisticallyClearRemoteComposer+ ? getDataOwnerGeneration()+ : null;const finishAgentSendDispatch = sourceSessionId? tryBeginAgentSendDispatch(sourceSessionId): () => {};if (!finishAgentSendDispatch) return;draftSaveSchedulerRef.current?.flush();dispatchSendInFlightRef.current = true;+ // Local/SSH sends keep the live composer while references and runtime+ // settings settle; remote sends must stay editable after their+ // click-time snapshot is cleared.+ if (!optimisticallyClearRemoteComposer) setSendDispatchInFlight(true);try {- await resolveSessionMessageReferencesForSend(editor);- // 引用 chip 水合会跨 device-link await;等待期间若旧客户端 / 其他入口登记了切换,- // 必须在真正 onSend 前再查一次,不能让准备阶段前的一次性检查代表发送时刻。- if (sourceSessionId && hasPendingAgentSwitchOperation(sourceSessionId)) return;- if (editor.isDestroyed) return;- const {+ let serializedContent = serializedAtClick;+ if (!serializedContent) {+ await resolveSessionMessageReferencesForSend(editor);+ // Local/SSH keeps the live editor until acceptance. A routed ChatInput+ // may have switched sessions during hydration; never serialize or+ // clear the newly hydrated composer with the old send continuation.+ if (sourceSessionId && hasPendingAgentSwitchOperation(sourceSessionId)) return;+ if (+ editor.isDestroyed ||+ latestStorageKeyRef.current !== sourceStorageKey ||+ storageKeyForDraftRef.current !== sourceStorageKey+ ) {+ return;+ }+ serializedContent = serializeEditorContent(editor);+ }+ let {text: editorText,mentions,hasQuotes,agentReferences,pastedTextRanges,slashCommandRanges,- } = serializeEditorContent(editor);+ } = serializedContent;+ const attachmentsForSend = optimisticallyClearRemoteComposer+ ? attachmentsBeforeOptimisticClear+ : [...latestAttachmentsRef.current];+ const commentsForSend = optimisticallyClearRemoteComposer+ ? commentsBeforeOptimisticClear+ : [...browserCommentsRef.current];// composerQuote 在其正文位置序列化成 markdown blockquote,支持引用与回复交错。// browser-comment-chip:页面评论序列化为 `# Browser comments:` 段拼在正文后// (截图在下方并入 filesToSend,与文本块里的 "attached as a labeled image"// caption 对应)。- const text = formatBrowserCommentsForSend(browserCommentsRef.current, editorText);+ const text = formatBrowserCommentsForSend(commentsForSend, editorText);// Allow send if there is text OR attachments(纯引用 / 纯评论无输入也可发送)- if (!text && !hasAttachments) return;+ if (!text && attachmentsForSend.length === 0) return;// device-link 模型清单未结算或真实读取失败时禁止发送。模型选择器会同步显示// loading / error;这里兜住快捷键、语音等间接派发入口,避免旧快照继续路由。@@ -3805,6 +3899,7 @@ export function ChatInput({// 处理,不误伤。用 chatEligibleSourcesForModel 而非裸 sourcesForModel:// 非聊天来源不该被当成"可以发"放行(issue #882 第 3 点,2026-07 review)。if (+ enforceConnectedSourceGate &¤tModelAgentKind &&// 旧被控端明确不支持 provider:list 时,控制端没有可检查的来源镜像;// 与模型列表一致交给 capabilities + 被控端发送链路做兼容回退。@@ -3813,10 +3908,15 @@ export function ChatInput({// 已建会话按实际路由口径判(includeDisabled,与上方 hasConnectedSendSource// 同则):运行中会话不因停用打断,最终 preflight 若按准入 rail 判会在全停时// 弹「去连接来源」把继续发送挡死(PR #744 review 第十八轮)。草稿保持准入口径。- const connectedSources = chatEligibleSourcesForModel(providers, activeModel, currentModelAgentKind, {- onlyConnected: true,- includeDisabled: !!sessionId,- });+ const connectedSources = chatEligibleSourcesForModel(+ providers,+ activeModel,+ currentModelAgentKind,+ {+ onlyConnected: true,+ includeDisabled: !!sessionId,+ },+ );if (connectedSources.length === 0) {const goConnect = await confirmDialog({title: t('newChat.noProvider.title'),@@ -3832,20 +3932,20 @@ export function ChatInput({// 评论截图并入发送附件(item.screenshot 即 AttachedFile,顺序在用户附件后,// 与评论块的编号 caption 对应)。- const commentScreenshots = browserCommentsRef.current.map((c) => c.screenshot);+ const commentScreenshots = commentsForSend.map((c) => c.screenshot);const filesToSend =- hasAttachments || commentScreenshots.length > 0- ? [...attachments, ...commentScreenshots]+ attachmentsForSend.length > 0 || commentScreenshots.length > 0+ ? [...attachmentsForSend, ...commentScreenshots]: undefined;const mentionsToSend = mentions.length > 0 ? mentions : undefined;// 意识 $指令展开(C3d 双触发):`$画图 ...` 开头且命中已唤醒意识时,// 追加"必须走 cindy 总机"的机器指令;未命中原样发送。// 读取 useInstalledGhosts 的最新窗口级快照。ghosts:changed 会原子更新// 该快照;发送路径无需同步 IPC,仍按当前工作目录执行同一禁用判定。- const eligibleGhosts = filterGhostsForWorkdir(- installedGhostsRef.current,- workingDirRef.current,- );+ const eligibleGhosts = filterGhostsForWorkdir(+ installedGhostsRef.current,+ workingDirRef.current,+ );const ghostCommandWord = parseGhostCommandWord(text);const usedGhost = ghostCommandWord? findGhostByCommand(eligibleGhosts, ghostCommandWord)@@ -3853,7 +3953,7 @@ export function ChatInput({const textToSend = expandGhostCommand(text, eligibleGhosts);const sendSnapshot = captureComposerSendSnapshot(editor.getJSON(),- attachmentsRef.current,+ latestAttachmentsRef.current,browserCommentsRef.current,);let recentUsageMarked = false;@@ -3867,6 +3967,288 @@ export function ChatInput({);});};+ const clearSentComposer = (options?: { preserveNewerContent?: boolean }) => {+ const isCurrentComposer =+ latestStorageKeyRef.current === sourceStorageKey &&+ storageKeyForDraftRef.current === sourceStorageKey &&+ !editor.isDestroyed;+ // Local/SSH sends keep the live composer until onSend is accepted.+ // If the async send crossed a session/editor switch or the user+ // changed the snapshot while it was in flight, leave the current+ // draft untouched rather than clearing newer input.+ if (+ !optimisticallyClearRemoteComposer &&+ (!isCurrentComposer ||+ !isComposerSendSnapshotCurrent(+ sendSnapshot,+ editor.getJSON(),+ latestAttachmentsRef.current,+ browserCommentsRef.current,+ ))+ ) {+ return;+ }+ if (!isCurrentComposer) {+ if (!options?.preserveNewerContent || !sourceStorageKey) {+ if (sourceStorageKey) clearComposerDraft(sourceStorageKey);+ return;+ }+ // The original ChatInput may have unmounted after a session switch,+ // but the old storage slot can already contain newer text/files from+ // another mounted composer. Remove only the click-time fragment;+ // never clear that whole slot from a stale continuation.+ const currentDraft = getComposerDraft(sourceStorageKey);+ if (!currentDraft) return;+ const next = removeRemoteOptimisticDraftFragment(+ {+ text: currentDraft.text,+ attachments: currentDraft.attachments,+ browserComments: currentDraft.browserComments ?? [],+ },+ {+ text: documentBeforeOptimisticClear,+ attachments: attachmentsBeforeOptimisticClear,+ browserComments: commentsBeforeOptimisticClear,+ },+ );+ const changed =+ next.text !== currentDraft.text ||+ next.attachments.length !== currentDraft.attachments.length ||+ next.attachments.some((file, index) => file !== currentDraft.attachments[index]) ||+ next.browserComments.length !== (currentDraft.browserComments ?? []).length ||+ next.browserComments.some(+ (comment, index) => comment !== (currentDraft.browserComments ?? [])[index],+ );+ if (!changed) return;+ saveComposerDraft(+ sourceStorageKey,+ {+ ...currentDraft,+ text: next.text,+ attachments: [...next.attachments],+ browserComments: [...next.browserComments],+ },+ { silent: true, preserveRemoteOptimisticRecovery: true },+ );+ return;+ }+ if (options?.preserveNewerContent) {+ const currentDocument = editor.getJSON();+ const next = removeRemoteOptimisticDraftFragment(+ {+ text: currentDocument,+ attachments: latestAttachmentsRef.current,+ browserComments: browserCommentsRef.current,+ },+ {+ text: documentBeforeOptimisticClear,+ attachments: attachmentsBeforeOptimisticClear,+ browserComments: commentsBeforeOptimisticClear,+ },+ );+ const changed =+ next.text !== currentDocument ||+ next.attachments.length !== latestAttachmentsRef.current.length ||+ next.attachments.some(+ (file, index) => file !== latestAttachmentsRef.current[index],+ ) ||+ next.browserComments.length !== browserCommentsRef.current.length ||+ next.browserComments.some(+ (comment, index) => comment !== browserCommentsRef.current[index],+ );+ if (!changed) return;+ isRestoringRef.current = true;+ try {+ if (next.text !== currentDocument) {+ if (next.text) editor.commands.setContent(next.text);+ else editor.commands.clearContent(true);+ }+ } finally {+ isRestoringRef.current = false;+ }+ // restoreFiles is intentionally additive for failure recovery;+ // this branch is a successful deferred acceptance and must remove+ // the click-time attachments while retaining only newer input.+ clearFiles();+ restoreFiles(next.attachments);+ browserCommentsRef.current = [...next.browserComments];+ setBrowserComments([...next.browserComments]);+ if (sourceStorageKey) {+ const existing = getComposerDraft(sourceStorageKey);+ saveComposerDraft(+ sourceStorageKey,+ {+ text: next.text,+ attachments: [...next.attachments],+ quotes: existing?.quotes ?? [],+ browserComments: [...next.browserComments],+ },+ { silent: true, preserveRemoteOptimisticRecovery: true },+ );+ }+ return;+ }+ // Suppress onUpdate's draft-save during clearContent so we don't write a+ // transient empty-doc entry that we're about to drop.+ isRestoringRef.current = true;+ try {+ editor.commands.clearContent(true);+ } finally {+ isRestoringRef.current = false;+ }+ clearFiles();+ browserCommentsRef.current = [];+ setBrowserComments([]);+ historyIndexRef.current = -1;+ hydratedHistoryDocumentRef.current = null;+ draftRef.current = null;+ if (sourceStorageKey) clearComposerDraft(sourceStorageKey);+ };+ let optimisticComposerRestored = false;+ const immediateRestoreClientId = `local-restore:${crypto.randomUUID()}`;+ const restoreOptimisticallyClearedComposer = (+ clientId = immediateRestoreClientId,+ {+ updateLive = true,+ recoveryBatch,+ }: { updateLive?: boolean; recoveryBatch?: object } = {},+ ) => {+ if (+ !documentBeforeOptimisticClear ||+ optimisticComposerRestored ||+ !sourceStorageKey ||+ (dataOwnerAtOptimisticClear &&+ !isDataOwnerGenerationCurrent(dataOwnerAtOptimisticClear))+ ) {+ return;+ }+ optimisticComposerRestored = true;+ const isCurrentComposer =+ latestStorageKeyRef.current === sourceStorageKey &&+ storageKeyForDraftRef.current === sourceStorageKey &&+ !editor.isDestroyed;+ const restored = restoreRemoteOptimisticDraft(+ sourceStorageKey,+ {+ clientId,+ text: tiptapDocHasContent(documentBeforeOptimisticClear)+ ? documentBeforeOptimisticClear+ : null,+ attachments: attachmentsBeforeOptimisticClear,+ browserComments: commentsBeforeOptimisticClear,+ },+ isCurrentComposer+ ? {+ text: isEditorEmpty(editor) ? null : editor.getJSON(),+ attachments: latestAttachmentsRef.current,+ browserComments: browserCommentsRef.current,+ }+ : undefined,+ recoveryBatch ? { recoveryBatch } : undefined,+ );+ if (!updateLive || !isCurrentComposer) return;+ const composerWasFocused = editor.isFocused;+ isRestoringRef.current = true;+ try {+ if (restored.text && tiptapDocHasContent(restored.text)) {+ editor.commands.setContent(restored.text);+ } else {+ editor.commands.clearContent(true);+ }+ if (composerWasFocused) editor.commands.focus('end');+ } finally {+ isRestoringRef.current = false;+ }+ restoreFiles(restored.attachments);+ const restoredComments = [...(restored.browserComments ?? [])];+ browserCommentsRef.current = restoredComments;+ setBrowserComments(restoredComments);+ };+ const onRemoteOptimisticFailure = optimisticallyClearRemoteComposer+ ? (clientId: string, error?: unknown) => {+ if (isRemoteOptimisticSessionPurgedError(error)) {+ // The user deleted/archived this task while the click-time+ // payload was still hydrating or waiting in the outbox. Mark+ // the transition settled without resurrecting its draft.+ optimisticComposerRestored = true;+ return;+ }+ const isDataOwnerBoundary = isRemoteOptimisticDataOwnerBoundaryError(error);+ restoreOptimisticallyClearedComposer(clientId, {+ updateLive: !isDataOwnerBoundary,+ ...(isDataOwnerBoundary ? { recoveryBatch: error as object } : {}),+ });+ if (!isDataOwnerBoundary && error !== undefined) {+ log.warn(+ 'remote optimistic send failed after reconnect:',+ error instanceof Error ? error.message : String(error ?? ''),+ );+ }+ }+ : undefined;+ const releaseRemoteComposerTransition =+ optimisticallyClearRemoteComposer && sourceSessionId && onRemoteOptimisticFailure+ ? makerChatStore.beginRemoteOptimisticComposerTransition(+ sourceSessionId,+ filesToSend,+ onRemoteOptimisticFailure,+ )+ : () => {};+ const onDeferredAccepted = () => {+ if (optimisticallyClearRemoteComposer) {+ // 缺 workingDir 的第一次尝试会返回 false,并把远程 composer 恢复回来。+ // 补选目录后若真正受理,需要开启一轮新的失败恢复资格,再只清掉原草稿;+ // 否则后续 outbox 永久失败会因为 optimisticComposerRestored=true 而无法恢复。+ optimisticComposerRestored = false;+ clearSentComposer({ preserveNewerContent: true });+ } else {+ // Local/SSH never entered the optimistic-clear path. Reuse the normal+ // snapshot guard so an unchanged accepted draft clears while newer edits survive.+ clearSentComposer();+ }+ markRecentPluginUsage();+ };+ const restoreRemoteComposerAndRelease = () => {+ try {+ restoreOptimisticallyClearedComposer();+ } finally {+ releaseRemoteComposerTransition();+ }+ };+ if (optimisticallyClearRemoteComposer) {+ try {+ clearSentComposer();+ } catch (error) {+ restoreRemoteComposerAndRelease();+ throw error;+ }+ }+ if (+ optimisticallyClearRemoteComposer &&+ sourceSessionId &&+ onRemoteOptimisticFailure &&+ agentReferences.length > 0+ ) {+ try {+ agentReferences =+ await resolveSerializedSessionMessageReferencesForSend(agentReferences);+ } catch (error) {+ restoreRemoteComposerAndRelease();+ log.warn(+ 'remote optimistic reference hydration failed:',+ error instanceof Error ? error.message : String(error),+ );+ return;+ }+ if (+ !isRemoteOptimisticComposerTransitionActive(sourceSessionId, onRemoteOptimisticFailure)+ ) {+ // /clear restores the click-time draft through the normal caller+ // path; purge has already marked the callback as a no-op above.+ restoreRemoteComposerAndRelease();+ return;+ }+ }let result: boolean | void;let effortForSend = activeEffort;try {@@ -3893,12 +4275,17 @@ export function ChatInput({// 会永久阻断后续发送。当前这次发送直接失败;下一次会重新等待真实 settle 结果。if (!runtimeSettled) {toast.error(t('newChat.chatInput.effortRuntimeDirty'));+ if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();return;}// 路由切换后复用的编辑器不能把 A 会话的内容送进 B,也不能清掉 B 的草稿。- if (!isSessionScopeCurrent(sessionId, currentSessionIdRef.current)) return;+ if (!isSessionScopeCurrent(sessionId, currentSessionIdRef.current)) {+ if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();+ return;+ }if (coordinator.isRuntimeDirty(sessionId)) {toast.error(t('newChat.chatInput.effortRuntimeDirty'));+ if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();return;}// 等待 commit 后,闭包里的 activeEffort 可能仍是旧 props;以该 session 已提交的@@ -3920,48 +4307,25 @@ export function ChatInput({...(pastedTextRanges.length > 0 ? { pastedTextRanges } : {}),slashCommandRanges,...(usedGhost ? { onAccepted: markRecentPluginUsage } : {}),+ ...(onRemoteOptimisticFailure ? { onRemoteOptimisticFailure } : {}),+ onDeferredAccepted,},);} catch (error) {+ if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();log.warn('send rejected:', error instanceof Error ? error.message : String(error));return;}- if (result === false) return;- markRecentPluginUsage();- // onSend may wait on auth, commands, a remote device, or attachment work.- // Only clear the exact accepted snapshot; if the user changed anything- // after dispatch, preserve the whole current draft so no unsent work is lost.- if (- !isComposerSendSnapshotCurrent(- sendSnapshot,- editor.getJSON(),- attachmentsRef.current,- browserCommentsRef.current,- )- ) {+ if (result === false) {+ if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();return;}- // Suppress onUpdate's draft-save during the post-send clearContent so- // we don't write a transient empty-doc entry that we're about to drop.- isRestoringRef.current = true;- try {- editor.commands.clearContent(true);- } finally {- isRestoringRef.current = false;- }- clearFiles();- setBrowserComments([]);- historyIndexRef.current = -1;- hydratedHistoryDocumentRef.current = null;- draftRef.current = null;- // composer-draft-per-session: drop the saved draft now that this- // session's content has been sent. Without this, switching away then- // back would re-restore the just-sent text/files into the composer.- if (storageKey) {- clearComposerDraft(storageKey);- }+ releaseRemoteComposerTransition();+ markRecentPluginUsage();+ if (!optimisticallyClearRemoteComposer) clearSentComposer();} finally {dispatchSendInFlightRef.current = false;+ setSendDispatchInFlight(false);finishAgentSendDispatch();}},@@ -3978,10 +4342,12 @@ export function ChatInput({hasAttachments,attachments,clearFiles,+ restoreFiles,storageKey,+ deviceLinkDeviceId,t,currentModelAgentKind,- deviceLinkDeviceId,+ enforceConnectedSourceGate,providers,remoteProviders.unsupported,remoteModelListBlocked,@@ -3994,12 +4360,16 @@ export function ChatInput({dispatchSendRef.current = dispatchSend;}, [dispatchSend]);- const handleQueueSteer = useCallback(async (clientId: string) => {- if (!onQueueSteer) return false;- return onQueueSteer(clientId);- }, [onQueueSteer]);+ const handleQueueSteer = useCallback(+ async (clientId: string) => {+ if (!onQueueSteer) return false;+ return onQueueSteer(clientId);+ },+ [onQueueSteer],+ );- const handleClickSend = useCallback(async (deliveryMode: MessageDeliveryMode = 'queue') => {+ const handleClickSend = useCallback(+ async (deliveryMode: MessageDeliveryMode = 'queue') => {if (voiceInput.isBusy) {const currentCanSend = !isEditorEmpty(editor) || hasAttachments;if (!voiceInput.isListening && !currentCanSend && voiceInput.draftText.trim().length === 0)@@ -4192,7 +4562,11 @@ export function ChatInput({opts.remoteDeviceId ?? getSessionDeviceId(sessionId) ?? deviceLinkDeviceId;if (!remoteDeviceId) {const vendor =- currentModelAgentKind === 'codex' ? 'codex' : currentModelAgentKind === 'pi' ? 'pi' : 'cc';+ currentModelAgentKind === 'codex'+ ? 'codex'+ : currentModelAgentKind === 'pi'+ ? 'pi'+ : 'cc';patchVendorPrefsPreservingModelChoice(vendor, {model: modelId,providerId: activeProviderId ?? null,@@ -4370,7 +4744,10 @@ export function ChatInput({modelId: string,expectedRevision?: number,) => void | boolean | Promise<void | boolean>;- byModel: (modelId: string, expectedRevision?: number) => void | boolean | Promise<void | boolean>;+ byModel: (+ modelId: string,+ expectedRevision?: number,+ ) => void | boolean | Promise<void | boolean>;}>({ byProvider: () => {}, byModel: () => {} });const confirmAgentBrowseSwitch = useCallback(() =>@@ -4510,11 +4887,12 @@ export function ChatInput({if (makerChatStore.getSnapshot(sourceSessionId).agentStatus.isRunning) {toast.success(t('newChat.chatInput.agentSwitch.deferred', {- agent: targetAgentKind === 'codex'- ? 'Codex'- : targetAgentKind === 'pi'- ? 'Pi'- : 'Claude Code',+ agent:+ targetAgentKind === 'codex'+ ? 'Codex'+ : targetAgentKind === 'pi'+ ? 'Pi'+ : 'Claude Code',model: newModelId,}),{ duration: 4000 },@@ -4537,10 +4915,7 @@ export function ChatInput({newModelId,result.sameEngineRevision,)- : await sameEngineReselectRef.current.byModel(- newModelId,- result.sameEngineRevision,- );+ : await sameEngineReselectRef.current.byModel(newModelId, result.sameEngineRevision);if (applied === false) return;makerChatStore.clearAgentSwitchIntent(sourceSessionId);return;@@ -4664,9 +5039,7 @@ export function ChatInput({newModelId,selectedProviderId,expectedAgentSwitchRevision,- useAtomicSelection- ? { effort: newEffort, fastMode: restoredFast }- : undefined,+ useAtomicSelection ? { effort: newEffort, fastMode: restoredFast } : undefined,);if (remoteSetModelResult?.superseded) {if (isSourceSessionCurrent()) setPendingRemoteSwitch(null);@@ -4775,13 +5148,10 @@ export function ChatInput({!getSessionDeviceId(sessionId)) {await window.electronAPI.maker- .setModel(- sessionId,- rollbackModelAfterPersistFailure.model,- undefined,- undefined,- { effort: activeEffort, fastMode },- )+ .setModel(sessionId, rollbackModelAfterPersistFailure.model, undefined, undefined, {+ effort: activeEffort,+ fastMode,+ }).catch((rollbackErr) => {log.warn('model change rollback failed:', rollbackErr);});@@ -5064,9 +5434,7 @@ export function ChatInput({targetModel,newProviderId,expectedAgentSwitchRevision,- useAtomicSelection- ? { effort: targetEffort, fastMode: restoredFast }- : undefined,+ useAtomicSelection ? { effort: targetEffort, fastMode: restoredFast } : undefined,);if (remoteSetModelResult?.superseded) {if (isSourceSessionCurrent()) {@@ -5162,12 +5530,7 @@ export function ChatInput({{ activeProviderId: newProviderId, memoryProviderId: newProviderId },);if (currentModelAgentKind && newProviderId) {- modelMemory?.setFast(- currentModelAgentKind,- newProviderId,- modelId,- restoredFast,- );+ modelMemory?.setFast(currentModelAgentKind, newProviderId, modelId, restoredFast);}// fast live 同步:host 已原子落 DB/runtime,这里只更新 renderer 快照。// 目标模型支持 fast 时把恢复值推进快照(切来源 / 同来源换模型都覆盖);@@ -5228,13 +5591,10 @@ export function ChatInput({!isRemoteSession) {await window.electronAPI.maker- .setModel(- sessionId,- rollbackProvider.model,- rollbackProvider.providerId,- undefined,- { effort: activeEffort, fastMode },- )+ .setModel(sessionId, rollbackProvider.model, rollbackProvider.providerId, undefined, {+ effort: activeEffort,+ fastMode,+ }).catch((rollbackErr) => {log.warn('provider change rollback failed:', rollbackErr);});@@ -5428,7 +5788,9 @@ export function ChatInput({voiceInputCanStopAndSendRef.current = !sendButtonDisabled;composerCanSubmitRef.current = !sendButtonDisabled;}, [sendButtonDisabled]);- const canReleaseVoiceToSend = Boolean(!disabled && (voiceInput.isListening || canSend || hasVoiceDraftText));+ const canReleaseVoiceToSend = Boolean(+ !disabled && (voiceInput.isListening || canSend || hasVoiceDraftText),+ );const folderBasename = workingDir ? workingDir.split(/[\\/]/).pop() : null;// F-QUEUE-DEFER: panel + input fuse into a single visual card when the@@ -5453,8 +5815,7 @@ export function ChatInput({const useNarrowToolbar = narrowToolbar || (toolbarWidth != null && toolbarWidth < 600);const useCompactMiddleToolbar =isCreateAgentVariant && (toolbarWidth == null ? narrowToolbar : toolbarWidth < 600);- const useUltraCompactToolbar =- useNarrowToolbar && (toolbarWidth == null || toolbarWidth < 420);+ const useUltraCompactToolbar = useNarrowToolbar && (toolbarWidth == null || toolbarWidth < 420);return (<div className="relative flex w-full flex-col items-center gap-4" data-chat-input-root>@@ -5462,7 +5823,10 @@ export function ChatInput({root gap-4,让 chip 与输入框间距接近 GoalIndicator 的节奏。 */}{planModeEntry && planModeEnabled && (<div className="-mb-2 w-full">- <PlanModeIndicator onExit={() => void onPlanModeChange?.(false)} disabled={composerMutationLocked} />+ <PlanModeIndicator+ onExit={() => void onPlanModeChange?.(false)}+ disabled={composerMutationLocked}+ /></div>)}{/* Voice-input error + attachment rejections (oversize / blocked /@@ -5583,8 +5947,7 @@ export function ChatInput({isDestroyed: editor.isDestroyed,isEditable: editor.isEditable,isFocused: editor.isFocused,- caretAtDocStart:- selection.empty && selection.from === Selection.atStart(doc).from,+ caretAtDocStart: selection.empty && selection.from === Selection.atStart(doc).from,});if (intent === 'keep-caret') editor.commands.focus();else if (intent === 'doc-end') editor.commands.focus('end');@@ -5937,9 +6300,11 @@ export function ChatInput({)}>{(!useNarrowToolbar || useCompactMiddleToolbar) &&- (useCompactMiddleToolbar- ? compactMiddleToolbarSlot ?? <>{middleToolbarSlot}</>- : <>{middleToolbarSlot}</>)}+ (useCompactMiddleToolbar ? (+ (compactMiddleToolbarSlot ?? <>{middleToolbarSlot}</>)+ ) : (+ <>{middleToolbarSlot}</>+ ))}<div className={useNarrowToolbar ? 'min-w-0 shrink' : undefined}><ModelSelectormodelId={activeModel}diff --git a/apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx b/apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsxindex e62613537f..677fd44e1e 100644--- a/apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx+++ b/apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx@@ -112,7 +112,7 @@ interface FolderPickerPopoverProps {folderPath: string,source: FolderPickerSelectSource,option?: FolderPickerOption,- ) => void;+ ) => void | Promise<void>;projectOptions?: readonly FolderPickerOption[];/*** 非空 = 项目区列的是这台对端设备的项目(本机时不传)。只用于空态文案与「浏览文件夹」@@ -152,13 +152,19 @@ export function FolderPickerPopover({const effectiveProjectOptions = projectOptions ?? [];const recentFolders = open && !isProjectPicker ? getRecentFolders() : [];- const handleSelectPath = (+ const handleSelectPath = async (folderPath: string,source: FolderPickerSelectSource,option?: FolderPickerOption,- ) => {- onSelect(folderPath, source, option);+ ): Promise<void> => {+ try {+ await onSelect(folderPath, source, option);+ } finally {+ // Selection callbacks may persist the directory before handing a pending+ // send back to the parent. Close only after that hand-off completes so a+ // controlled popover cannot clear the pending payload first.onOpenChange(false);+ }};const handleRemoveProject = (project: FolderPickerOption) => {@@ -268,8 +274,7 @@ export function FolderPickerPopover({}const result = await window.electronAPI.showOpenDirectoryDialog();if (!result.canceled && result.path) {- onSelect(result.path, 'browse');- onOpenChange(false);+ await handleSelectPath(result.path, 'browse');}// If canceled, popover stays open per spec};diff --git a/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx b/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsxindex aa75a65e7e..7f9c0ab11b 100644--- a/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx+++ b/apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx@@ -109,7 +109,10 @@ function equalIds(left: string[], right: string[]): boolean {return left.length === right.length && left.every((id, idx) => id === right[idx]);}-function resolveSingleMove(oldIds: string[], nextIds: string[]): { clientId: string; targetIndex: number } | null {+function resolveSingleMove(+ oldIds: string[],+ nextIds: string[],+): { clientId: string; targetIndex: number } | null {if (oldIds.length !== nextIds.length || equalIds(oldIds, nextIds)) return null;for (let oldIndex = 0; oldIndex < oldIds.length; oldIndex += 1) {@@ -173,7 +176,10 @@ export function PendingQueuePanel({const onInteractionLockRef = useRef(onInteractionLock);const visibleQueue = useMemo(- () => (expanded || queue.length <= COLLAPSE_THRESHOLD_ROWS ? queue : queue.slice(0, COLLAPSED_VISIBLE_ROWS)),+ () =>+ expanded || queue.length <= COLLAPSE_THRESHOLD_ROWS+ ? queue+ : queue.slice(0, COLLAPSED_VISIBLE_ROWS),[expanded, queue],);const hiddenCount = Math.max(0, queue.length - visibleQueue.length);@@ -264,9 +270,7 @@ export function PendingQueuePanel({const trimmed = editingDraft.trim();if (trimmed.length > 0) {const entry = queue.find((item) => item.clientId === editingClientId);- const submission = entry- ? resolvePendingQueueEditSubmission(entry, editingDraft)- : null;+ const submission = entry ? resolvePendingQueueEditSubmission(entry, editingDraft) : null;if (submission !== null) onEdit?.(editingClientId, submission);}releaseEditLock(editingClientId);@@ -316,10 +320,11 @@ export function PendingQueuePanel({className="pending-queue-scroll flex max-h-[196px] flex-col gap-0 overflow-y-auto overscroll-contain px-1 pb-0.5 pt-1.5 [scrollbar-gutter:stable_both-edges]"renderItem={(entry, originalIdx) => {const rowPresentation = getPendingQueueRowPresentation(entry);+ const isPendingEnqueue = entry.isPendingEnqueue === true;const isRowActive = isPendingQueueRowActive(rowActivity, entry.clientId);const isRowEditing = entry.clientId === editingClientId;const isSteering = steeringClientIds.includes(entry.clientId);- const showActions = isRowActive || isSteering || isRowEditing;+ const showActions = !isPendingEnqueue && (isRowActive || isSteering || isRowEditing);const canSteerRow = Boolean(onSteer) && rowPresentation.canSteer;const canEditRow = Boolean(onEdit) && rowPresentation.canEdit;const chatMessageContent = entry.chatMessage.content ?? entry.text;@@ -335,12 +340,20 @@ export function PendingQueuePanel({agentReferences.length > 0 ||(entry.mentions?.length ?? 0) > 0);const actionSlotWidth = canSteerRow- ? (canEditRow ? 'w-[68px]' : 'w-[44px]')- : (canEditRow ? 'w-[44px]' : 'w-5');- const dragDisabled = !onReorder || isRowEditing || isSteering;+ ? canEditRow+ ? 'w-[68px]'+ : 'w-[44px]'+ : canEditRow+ ? 'w-[44px]'+ : 'w-5';+ const dragDisabled = !onReorder || isPendingEnqueue || isRowEditing || isSteering;const steerTipText = (() => {if (isSteering) return t('newChat.pendingQueue.steeringAction');- const base = t(turnRunning ? 'newChat.pendingQueue.steerRunningTip' : 'newChat.pendingQueue.steerPausedTip');+ const base = t(+ turnRunning+ ? 'newChat.pendingQueue.steerRunningTip'+ : 'newChat.pendingQueue.steerPausedTip',+ );return steerShortcutLabel ? `${base} · ${steerShortcutLabel}` : base;})();// The surrounding <p> owns the queue row's single-line nowrap +@@ -424,7 +437,7 @@ export function PendingQueuePanel({return (<divrole="listitem"- tabIndex={canSteerRow ? 0 : undefined}+ tabIndex={canSteerRow && !isPendingEnqueue ? 0 : undefined}aria-keyshortcuts={canSteerRow ? 'Meta+Enter Control+Enter' : undefined}onKeyDown={handleRowKeyDown}onMouseEnter={() => {@@ -472,7 +485,8 @@ export function PendingQueuePanel({'pending-queue-drag-handle flex h-5 w-5 shrink-0 touch-none select-none items-center justify-center rounded-[6px]','appearance-none border-0 bg-transparent p-0','text-[var(--cmd-palette-item-meta)] opacity-0 transition-opacity',- !dragDisabled && 'cursor-grab group-hover:opacity-100 focus:opacity-100 active:cursor-grabbing',+ !dragDisabled &&+ 'cursor-grab group-hover:opacity-100 focus:opacity-100 active:cursor-grabbing',dragDisabled && 'cursor-default',)}>@@ -530,9 +544,11 @@ export function PendingQueuePanel({)}>{rowPresentation.isSyntheticTrigger- ? t(rowPresentation.syntheticKind === 'continue'+ ? t(+ rowPresentation.syntheticKind === 'continue'? 'newChat.pendingQueue.syntheticContinueLabel'- : 'newChat.pendingQueue.syntheticTriggerLabel')+ : 'newChat.pendingQueue.syntheticTriggerLabel',+ ): rowPresentation.displayText || t('newChat.pendingQueue.noTextContent')}</span></div>@@ -550,7 +566,14 @@ export function PendingQueuePanel({</p>)}- {isRowEditing ? (+ {isPendingEnqueue ? (+ <span+ aria-hidden+ className="flex h-5 w-5 shrink-0 items-center justify-center text-[var(--cmd-palette-item-meta)]"+ >+ <Spinner size={12} strokeWidth={2.25} />+ </span>+ ) : isRowEditing ? (<div className="flex shrink-0 items-center gap-1"><buttontype="button"@@ -573,12 +596,11 @@ export function PendingQueuePanel({</button></div>) : showActions ? (- <div className={cn('flex shrink-0 items-center justify-end gap-1', actionSlotWidth)}>+ <div+ className={cn('flex shrink-0 items-center justify-end gap-1', actionSlotWidth)}+ >{canSteerRow && onSteer && (- <Tip- text={steerTipText}- side="top"- >+ <Tip text={steerTipText} side="top"><buttontype="button"onClick={() => {@@ -591,7 +613,10 @@ export function PendingQueuePanel({: 'newChat.pendingQueue.steerAria',{ index: originalIdx + 1 },)}- className={cn(iconButtonClassName, 'disabled:cursor-wait disabled:opacity-70')}+ className={cn(+ iconButtonClassName,+ 'disabled:cursor-wait disabled:opacity-70',+ )}>{isSteering ? (<Spinner size={12} strokeWidth={2.25} />@@ -618,7 +643,9 @@ export function PendingQueuePanel({<buttontype="button"onClick={() => onRemove(entry.clientId)}- aria-label={t('newChat.pendingQueue.removeAria', { index: originalIdx + 1 })}+ aria-label={t('newChat.pendingQueue.removeAria', {+ index: originalIdx + 1,+ })}className={iconButtonClassName}><Trash2 size={11} strokeWidth={2.25} aria-hidden />@@ -659,7 +686,11 @@ export function PendingQueuePanel({{expanded? t('newChat.pendingQueue.showLess'): t('newChat.pendingQueue.showMore', { count: hiddenCount })}- {expanded ? <ChevronUp size={13} aria-hidden /> : <ChevronDown size={13} aria-hidden />}+ {expanded ? (+ <ChevronUp size={13} aria-hidden />+ ) : (+ <ChevronDown size={13} aria-hidden />+ )}</button>) : (<span aria-hidden className="col-start-2 h-5" />diff --git a/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts b/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.tsindex bf08656fec..f5ac05899d 100644--- a/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts+++ b/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts@@ -48,24 +48,21 @@ export function getPendingQueueRowPresentation(entry: QueuedMessage): PendingQueconst isSyntheticTrigger = entry.text.startsWith(UI_ACTION_TRIGGER_PREFIX);const isContinueTrigger =entry.text === CONTINUE_AFTER_APP_EXIT_PROMPT || entry.text === CONTINUE_AFTER_ERROR_PROMPT;+ const isPendingEnqueue = entry.isPendingEnqueue === true;return {isOrca,isScheduler,- senderLabel: isOrca- ? origin.senderLabel- : isScheduler- ? origin.scheduleName- : null,+ senderLabel: isOrca ? origin.senderLabel : isScheduler ? origin.scheduleName : null,displayText: isOrca? (origin.displayText ?? entry.text): isScheduler- ? (entry.persistedContent || entry.text)+ ? entry.persistedContent || entry.text: entry.chatMessage.quotesEncoded === true? stripChatQuoteMarkerLines(entry.text): entry.text,- canEdit: !isOrca && !isScheduler && !isSyntheticTrigger,- canSteer: !isOrca && !isScheduler && !isSyntheticTrigger,+ canEdit: !isPendingEnqueue && !isOrca && !isScheduler && !isSyntheticTrigger,+ canSteer: !isPendingEnqueue && !isOrca && !isScheduler && !isSyntheticTrigger,isSyntheticTrigger,syntheticKind: isSyntheticTrigger ? (isContinueTrigger ? 'continue' : 'generic') : null,};@@ -81,7 +78,5 @@ export function resolvePendingQueueEditSubmission(entry: QueuedMessage,visibleText: string,): string | null {- return visibleText === getPendingQueueRowPresentation(entry).displayText- ? null- : visibleText;+ return visibleText === getPendingQueueRowPresentation(entry).displayText ? null : visibleText;}diff --git a/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts b/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.tsindex f48e8d0b73..8c798b2f62 100644--- a/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts+++ b/apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts@@ -19,7 +19,10 @@* ASCII 方括号会破坏 markdown 链接语法,清洗为空格。*/import type { Editor } from '@tiptap/core';-import { boundAgentReferenceText } from '@cindy/maker-shared/agent-input-projection';+import {+ boundAgentReferenceText,+ type AgentInputReference,+} from '@cindy/maker-shared/agent-input-projection';import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';import { i18n } from '@/i18n';@@ -84,6 +87,43 @@ export async function resolvePastedSessionMessageText(return resolveSessionMessageText(sessionId, clientId);}+/**+ * Resolve semantic bodies on an immutable click-time composer snapshot.+ *+ * Device-link optimistic sends clear the live editor before this async work so+ * the user can immediately start the next message. Mutating the live editor+ * here would therefore target either a new draft or another session; enrich the+ * captured AgentInputReference array instead and keep the deep-link wire text+ * unchanged.+ */+export async function resolveSerializedSessionMessageReferencesForSend(+ references: readonly AgentInputReference[],+ resolveMessageText: (+ sessionId: string,+ clientId: string,+ ) => Promise<string | null> = resolvePastedSessionMessageText,+): Promise<AgentInputReference[]> {+ return Promise.all(+ references.map(async (reference): Promise<AgentInputReference> => {+ if (reference.kind !== 'message' || reference.text) return reference;+ try {+ const value = await resolveMessageText(reference.sessionId, reference.messageClientId);+ if (!value) return reference;+ const bounded = boundAgentReferenceText(value);+ return {+ ...reference,+ text: bounded.text,+ truncated: bounded.truncated || undefined,+ };+ } catch {+ // Preserve the deep link when the referenced body is unavailable. The+ // send must remain usable on a weak/offline device-link connection.+ return reference;+ }+ }),+ );+}+/*** 默认标题解析:本地库 → device-link 远程会话镜像 → null(保持短 ID)。* 降级顺序与消息侧 SessionLinkChip 一致。服务依赖走动态 import:本模块的diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsxindex 690a6144c4..cfe57d6106 100644--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx@@ -23,7 +23,10 @@ import {type DesktopLoginActionResult,type User,} from '@/lib/authService';-import { setCurrentUserName } from '@/lib/makerChatStore';+import {+ cancelRemoteOptimisticSendsForDataOwnerBoundary,+ setCurrentUserName,+} from '@/lib/makerChatStore';import { isSecondaryWindow } from '@/lib/secondaryWindow';import { setUserPromptOwner } from '@/lib/userPromptStore';import { bootstrapMemorySettingsFromMain, setMemorySettingsOwner } from '@/lib/memorySettingsStore';@@ -35,10 +38,7 @@ import { setComposerDraftOwner } from '@/lib/composerDraftStore';import { setPendingHandoffOwner } from '@/state/pendingFirstMessage';import { invalidateProvidersSnapshot } from '@/lib/providersSnapshotStore';import { preloadLocalCatalogSnapshot } from '@/lib/localCatalogSnapshot';-import {- getDataOwnerGeneration,- setDataOwnerGeneration,-} from './dataOwnerGeneration';+import { getDataOwnerGeneration, setDataOwnerGeneration } from './dataOwnerGeneration';/*** 登录态上下文:user / isAuthenticated / isCanary / deviceId 全部来自 main 的@@ -52,6 +52,8 @@ export interface AuthContextValue {user: User | null;mode: 'signed-out' | 'local' | 'cloud';dataOwnerId: string | null;+ /** Failed auth boundaries remount owner-scoped routes so stale generations can rehydrate. */+ dataOwnerRecoveryEpoch: number;canEnterApp: boolean;isAuthenticated: boolean;/** 当前账号是否加入 Canary 发布通道。 */@@ -68,21 +70,30 @@ export interface AuthContextValue {exitLocalMode: () => Promise<void>;hasAccountDeletionReceipt: boolean;accountDeletionRestored: boolean;- getAccountDeletionAvailability: ReturnType<typeof createAuthService>['getAccountDeletionAvailability'];- requestAccountDeletionChallenge: ReturnType<typeof createAuthService>['requestAccountDeletionChallenge'];+ getAccountDeletionAvailability: ReturnType<+ typeof createAuthService+ >['getAccountDeletionAvailability'];+ requestAccountDeletionChallenge: ReturnType<+ typeof createAuthService+ >['requestAccountDeletionChallenge'];confirmAccountDeletion: ReturnType<typeof createAuthService>['confirmAccountDeletion'];getAccountDeletionStatus: ReturnType<typeof createAuthService>['getAccountDeletionStatus'];clearAccountDeletionReceipt: ReturnType<typeof createAuthService>['clearAccountDeletionReceipt'];- consumeAccountDeletionRestoredNotice: ReturnType<typeof createAuthService>['consumeAccountDeletionRestoredNotice'];+ consumeAccountDeletionRestoredNotice: ReturnType<+ typeof createAuthService+ >['consumeAccountDeletionRestoredNotice'];}const AuthContext = createContext<AuthContextValue | null>(null);const log = createLogger('AuthContext');-function publishDataOwnerGeneration(dataOwnerId: string | null): void {+function publishDataOwnerGeneration(dataOwnerId: string | null, ownerGeneration?: number): void {const previousOwnerId = getDataOwnerGeneration().dataOwnerId;- setDataOwnerGeneration(dataOwnerId);+ if (previousOwnerId !== dataOwnerId) {+ cancelRemoteOptimisticSendsForDataOwnerBoundary();+ }+ setDataOwnerGeneration(dataOwnerId, ownerGeneration);if (previousOwnerId !== dataOwnerId) invalidateProvidersSnapshot();}@@ -90,6 +101,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {const [user, setUser] = useState<User | null>(null);const [mode, setMode] = useState<'signed-out' | 'local' | 'cloud'>('signed-out');const [dataOwnerId, setDataOwnerId] = useState<string | null>(null);+ const [dataOwnerRecoveryEpoch, setDataOwnerRecoveryEpoch] = useState(0);const [canEnterApp, setCanEnterApp] = useState(false);const [isAuthenticated, setIsAuthenticated] = useState(false);const [isCanary, setIsCanary] = useState(false);@@ -108,6 +120,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {const activeUserIdRef = useRef<string | null>(null);const activeDataOwnerIdRef = useRef<string | null>(null);+ const activeDataOwnerGenerationRef = useRef(0);const authStateVersionRef = useRef(0);// Auth mutations invalidate owner-bound in-flight reads before crossing IPC. If Main rejects@@ -118,7 +131,14 @@ export function AuthProvider({ children }: { children: ReactNode }) {try {return await operation();} catch (error) {- publishDataOwnerGeneration(activeDataOwnerIdRef.current);+ // Restore the exact main-owned generation. Recomputing it locally would+ // make every stamped push from the still-active owner look stale after a+ // rejected auth transition.+ publishDataOwnerGeneration(+ activeDataOwnerIdRef.current,+ activeDataOwnerGenerationRef.current,+ );+ setDataOwnerRecoveryEpoch((epoch) => epoch + 1);void preloadLocalCatalogSnapshot();throw error;}@@ -139,12 +159,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {const applyIncomingState = useCallback((state: AuthState) => {const ownerChanged = activeDataOwnerIdRef.current !== state.dataOwnerId;- publishDataOwnerGeneration(state.dataOwnerId);+ publishDataOwnerGeneration(state.dataOwnerId, state.ownerGeneration);if (ownerChanged) {sessionsStore.reset();clearWorkersCache();}activeDataOwnerIdRef.current = state.dataOwnerId;+ activeDataOwnerGenerationRef.current = state.ownerGeneration;setNewMakerDraftOwner(state.dataOwnerId);setComposerDraftOwner(state.dataOwnerId);setPendingHandoffOwner(state.dataOwnerId);@@ -308,8 +329,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {const enterLocalMode = useCallback(async () => {const state = await runDataOwnerBoundary(() => authServiceRef.current!.enterLocalMode());- publishDataOwnerGeneration(state.dataOwnerId);+ publishDataOwnerGeneration(state.dataOwnerId, state.ownerGeneration);activeDataOwnerIdRef.current = state.dataOwnerId;+ activeDataOwnerGenerationRef.current = state.ownerGeneration;setComposerDraftOwner(state.dataOwnerId);setPendingHandoffOwner(state.dataOwnerId);setMode(state.mode);@@ -321,8 +343,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {const exitLocalMode = useCallback(async () => {const state = await runDataOwnerBoundary(() => authServiceRef.current!.exitLocalMode());- publishDataOwnerGeneration(state.dataOwnerId);+ publishDataOwnerGeneration(state.dataOwnerId, state.ownerGeneration);activeDataOwnerIdRef.current = state.dataOwnerId;+ activeDataOwnerGenerationRef.current = state.ownerGeneration;setComposerDraftOwner(state.dataOwnerId);setPendingHandoffOwner(state.dataOwnerId);setMode(state.mode);@@ -375,6 +398,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {user,mode,dataOwnerId,+ dataOwnerRecoveryEpoch,canEnterApp,isAuthenticated,isCanary,@@ -399,6 +423,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {user,mode,dataOwnerId,+ dataOwnerRecoveryEpoch,canEnterApp,isAuthenticated,isCanary,diff --git a/apps/desktop/src/renderer/contexts/__tests__/AuthContextInitializeCatch.test.tsx b/apps/desktop/src/renderer/contexts/__tests__/AuthContextInitializeCatch.test.tsxindex 887692f8e7..d061719222 100644--- a/apps/desktop/src/renderer/contexts/__tests__/AuthContextInitializeCatch.test.tsx+++ b/apps/desktop/src/renderer/contexts/__tests__/AuthContextInitializeCatch.test.tsx@@ -29,7 +29,10 @@ vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));vi.mock('@/lib/authService', () => ({ createAuthService: () => mocks.service }));-vi.mock('@/lib/makerChatStore', () => ({ setCurrentUserName: vi.fn() }));+vi.mock('@/lib/makerChatStore', () => ({+ cancelRemoteOptimisticSendsForDataOwnerBoundary: vi.fn(),+ setCurrentUserName: vi.fn(),+}));vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { reset: vi.fn() } }));vi.mock('@/features/cc-agent/hooks/useWorkers', () => ({ clearWorkersCache: vi.fn() }));vi.mock('@/components/ui/confirm-dialog-provider', () => ({diff --git a/apps/desktop/src/renderer/contexts/__tests__/LoginHandoffContext.test.tsx b/apps/desktop/src/renderer/contexts/__tests__/LoginHandoffContext.test.tsxindex c11045b8b8..f35bce8a55 100644--- a/apps/desktop/src/renderer/contexts/__tests__/LoginHandoffContext.test.tsx+++ b/apps/desktop/src/renderer/contexts/__tests__/LoginHandoffContext.test.tsx@@ -42,7 +42,10 @@ vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));vi.mock('@/lib/authService', () => ({ createAuthService: () => svc.service }));-vi.mock('@/lib/makerChatStore', () => ({ setCurrentUserName: vi.fn() }));+vi.mock('@/lib/makerChatStore', () => ({+ cancelRemoteOptimisticSendsForDataOwnerBoundary: vi.fn(),+ setCurrentUserName: vi.fn(),+}));vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { reset: vi.fn() } }));vi.mock('@/features/cc-agent/hooks/useWorkers', () => ({ clearWorkersCache: vi.fn() }));vi.mock('@/components/ui/confirm-dialog-provider', () => ({diff --git a/apps/desktop/src/renderer/contexts/dataOwnerGeneration.ts b/apps/desktop/src/renderer/contexts/dataOwnerGeneration.tsindex 714b07445f..a39df212d7 100644--- a/apps/desktop/src/renderer/contexts/dataOwnerGeneration.ts+++ b/apps/desktop/src/renderer/contexts/dataOwnerGeneration.ts@@ -1,3 +1,8 @@+import {+ isDataOwnerPushStamp,+ type DataOwnerPushStamp,+} from '../../shared/dataOwnerPush';+export interface DataOwnerGeneration {readonly dataOwnerId: string | null;readonly generation: number;@@ -9,11 +14,15 @@ let current: DataOwnerGeneration = {};/** Publish the renderer data owner synchronously, before React state updates settle. */-export function setDataOwnerGeneration(dataOwnerId: string | null): void {- if (current.dataOwnerId === dataOwnerId) return;+export function setDataOwnerGeneration(dataOwnerId: string | null, generation?: number): void {+ const nextGeneration =+ typeof generation === 'number' && Number.isInteger(generation) && generation >= 0+ ? generation+ : current.generation + 1;+ if (current.dataOwnerId === dataOwnerId && current.generation === nextGeneration) return;current = {dataOwnerId,- generation: current.generation + 1,+ generation: nextGeneration,};}@@ -30,6 +39,23 @@ export function isDataOwnerGenerationCurrent();}+/** Validate a main-process live push against the renderer's current owner. */+export function isDataOwnerPushStampCurrent(stamp: unknown): stamp is DataOwnerPushStamp {+ if (!isDataOwnerPushStamp(stamp)) return false;+ return (+ current.dataOwnerId === stamp.dataOwnerId &&+ current.generation === stamp.ownerGeneration+ );+}++/**+ * Accept legacy unstamped broadcasts, but fail closed when a sender provides+ * an owner stamp that does not match the renderer's current auth boundary.+ */+export function isDataOwnerPushCurrent(ownerStamp: unknown): boolean {+ return ownerStamp === undefined || isDataOwnerPushStampCurrent(ownerStamp);+}+export const __testing = {reset(): void {current = { dataOwnerId: null, generation: 0 };diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsxindex d32baba000..ce8d1b376f 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx@@ -112,6 +112,8 @@ import { useSessionBinding } from '@/hooks/useSessionBinding';import { useVendorAuthGate } from '@/hooks/useVendorAuthGate';import { useProviders } from '@/hooks/useProviders';import { useAuth } from '@/contexts/AuthContext';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { canAccessBillingSettings } from '@/components/settings/billingVisibility';import { useDeviceProviders } from '@/hooks/useDeviceProviders';import { useAgentCapabilities } from '@/hooks/useAgentCapabilities';@@ -759,8 +761,9 @@ export function CCAgentSessionView({// 旧版被控端无该 channel / 离线:保持空镜像,非选中行回落模型默认。});- const off = window.electronAPI.deviceLink.onRemotePush((push) => {+ const off = window.electronAPI.deviceLink.onRemotePush((push, localOwnerStamp) => {if (push.deviceId !== deviceId || push.channel !== 'maker:new-maker-draft:changed') return;+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;const payload = push.payload as Record<string,{ providerModelMemory?: RemoteModelMemorySnapshot } | undefined@@ -847,7 +850,8 @@ export function CCAgentSessionView({const sessionsPush = window.electronAPI?.localDb?.sessionsPush;if (!sessionsPush) return;const refreshSequence = sessionRefreshSequenceRef.current;- const unsub = sessionsPush.onPatched(({ sessionId: patchedId, patch }) => {+ const unsub = sessionsPush.onPatched(({ sessionId: patchedId, patch }, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;if (patchedId !== sessionId || !refreshSequence.isCurrentSession(patchedId)) return;const patchBuffer = sessionSnapshotPatchBufferRef.current;patchBuffer.stage(patchedId, patch);@@ -1180,17 +1184,21 @@ export function CCAgentSessionView({// Pending send: stored when folder picker needs to open mid-sendconst pendingSendRef = useRef<{+ deliveryMode: MessageDeliveryMode;message: string;model: string;effort: Effort;permissionMode: PermissionMode;files?: AttachedFile[];mentions?: MentionedResource[];+ vendorOptions?: Record<string, unknown>;/** 正文前缀含「选中引用」编码块——补选目录后的派发同样要携带,否则该消息持久化后渲染不出胶囊。 */quotesEncoded?: boolean;agentReferences?: AgentInputReference[];pastedTextRanges?: PastedTextRange[];slashCommandRanges?: SlashCommandRange[];+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;+ onDeferredAccepted?: () => void;} | null>(null);const handleTitleUpdate = useCallback(() => {@@ -1275,8 +1283,7 @@ export function CCAgentSessionView({chatDisplaySnapshot,} = useCCAgentChat(sessionId, handleTitleUpdate, { chatRealtime });// 展示引擎可乐观跟随 intent;真实 event reducer 仍只读 store.agentKind。- const displayAgentKind =- agentSwitchIntent?.target ?? dbToMakerAgentKind(session?.agentKind);+ const displayAgentKind = agentSwitchIntent?.target ?? dbToMakerAgentKind(session?.agentKind);const isCodex = displayAgentKind === 'codex';// live 供应商目录(含内置 + 自定义,按 agent 挂模型)—— vendor↔model 一致性校验的真源,// 与模型选择器同源(见下方 M35 vendor fallback effect)。本地 IPC 极快返回,有模块级缓存。@@ -1286,26 +1293,14 @@ export function CCAgentSessionView({const { providers: deviceProviders } = useDeviceProviders(remoteDeviceId);const providers = remoteDeviceId ? deviceProviders : localProviders;const canSwitchToClaudeSubscription = useMemo(() => {- if (- remoteDeviceId ||- session?.remoteHostId ||- session?.agentKind !== 'cc' ||- !session.model- ) {+ if (remoteDeviceId || session?.remoteHostId || session?.agentKind !== 'cc' || !session.model) {return false;}return connectedProvidersForAgent(localProviders, 'claude-code').some((provider) =>- provider.id === 'anthropic' &&- providerOffersModel(provider, session.model, 'claude-code'),+ provider.id === 'anthropic' && providerOffersModel(provider, session.model, 'claude-code'),);- }, [- localProviders,- remoteDeviceId,- session?.agentKind,- session?.model,- session?.remoteHostId,- ]);+ }, [localProviders, remoteDeviceId, session?.agentKind, session?.model, session?.remoteHostId]);/*** 余额不足横幅的「查看余额」出口 —— 只在计费面对当前账号可见时提供(cloud +* personal,与设置页「用量和计费」同一判据)。org / local / 未登录账号在 Cindy 里@@ -1791,10 +1786,7 @@ export function CCAgentSessionView({// 全在本地,不回 SDK(原生 /workflows 在非交互 SDK 模式下不可用)。if (!sessionId) return;const latest = findLatestWorkflowTask(taskUpdatesRef.current);- void openBackgroundTasksTab(- sessionId,- latest ? { focusTaskId: latest.taskId } : {},- );+ void openBackgroundTasksTab(sessionId, latest ? { focusTaskId: latest.taskId } : {});return;}// 'issue' 命令由下方独立 effect 处理(需要 handleSend,其声明在本 effect 之后)。@@ -1872,7 +1864,7 @@ export function CCAgentSessionView({? routeWorkerHint.hasWorkerParam? routeWorkerHint.workerSessionId: (orcaWorkersReveal?.focusWorkerSessionId ??- (hasWorkerSearchJump ? searchJump?.sessionId ?? null : null))+ (hasWorkerSearchJump ? (searchJump?.sessionId ?? null) : null)): null;const workerSearchJump =focusWorkerSessionId && searchJump?.sessionId === focusWorkerSessionId@@ -2159,19 +2151,24 @@ export function CCAgentSessionView({// Auto-continue: if there's a pending send and a valid dir was selected, execute step ③if (newDir && pendingSendRef.current) {const {+ deliveryMode,message,model,effort,permissionMode,files,mentions,+ vendorOptions,quotesEncoded,agentReferences,pastedTextRanges,slashCommandRanges,+ onRemoteOptimisticFailure,+ onDeferredAccepted,} = pendingSendRef.current;pendingSendRef.current = null;- sendMessage(+ const dispatch = deliveryMode === 'steer' ? steerMessage : sendMessage;+ void dispatch(message,model,effort,@@ -2179,18 +2176,37 @@ export function CCAgentSessionView({newDir,files,mentions,- quotesEncoded || agentReferences?.length || pastedTextRanges?.length || slashCommandRanges !== undefined+ quotesEncoded ||+ vendorOptions !== undefined ||+ agentReferences?.length ||+ pastedTextRanges?.length ||+ slashCommandRanges !== undefined ||+ onRemoteOptimisticFailure !== undefined ||+ onDeferredAccepted !== undefined? {+ ...(vendorOptions ? { vendorOptions } : {}),...(quotesEncoded ? { quotesEncoded: true } : {}),...(agentReferences?.length ? { agentReferences } : {}),...(pastedTextRanges?.length ? { pastedTextRanges } : {}),...(slashCommandRanges !== undefined ? { slashCommandRanges } : {}),+ ...(onRemoteOptimisticFailure ? { onRemoteOptimisticFailure } : {}),+ ...(onDeferredAccepted ? { onDeferredAccepted } : {}),}: undefined,+ ).then(+ (accepted) => {+ if (accepted) onDeferredAccepted?.();+ },+ (error) => {+ log.warn(+ 'pending send after working directory selection failed:',+ error instanceof Error ? error.message : String(error),+ );+ },);}},- [sendMessage, refreshServerSession],+ [refreshServerSession, sendMessage, steerMessage],);const handleFolderPickerOpenChange = useCallback((open: boolean) => {@@ -2367,7 +2383,7 @@ export function CCAgentSessionView({}const createOpts = session?.workingDir? {- agentKind: session.agentKind === 'pi' ? 'pi' as const : 'claude-code' as const,+ agentKind: session.agentKind === 'pi' ? ('pi' as const) : ('claude-code' as const),workingDir: session.workingDir,model: session.model,orcaRole: session.orcaRole ?? null,@@ -2419,6 +2435,8 @@ export function CCAgentSessionView({agentReferences?: AgentInputReference[];pastedTextRanges?: PastedTextRange[];slashCommandRanges?: SlashCommandRange[];+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;+ onDeferredAccepted?: () => void;},) => {const deliveryMode = opts?.deliveryMode ?? 'queue';@@ -2448,22 +2466,19 @@ export function CCAgentSessionView({return;}- // 断线缓存的远程 session 可打开查看,但不可继续发送。返回 false 让 ChatInput 保留草稿。- if (remoteSessionUnavailable) return false;-- // ① Agent readiness check. Claude still gates on the shared API Key;- // Codex gates on the app's Codex connection state. Both use the same- // confirm dialog and settings navigation path as voice input.- // device-link:远程会话就绪态以被控端为准(传 remoteDeviceId 走隧道查被控端- // maker:agent:status);本地会话 remoteDeviceId 为 undefined → 走本机检查(行为不变)。- const authVendor = displayAgentKind === 'pi' ? 'pi' : isCodex ? 'codex' : 'cc';- const { proceed } = await vendorAuthGate.checkAndConfirm(authVendor, {- deviceId: remoteDeviceId,- // 已建会话:suspended 来源计入(停用不打断运行中会话,门禁只看凭证连接态,- // PR #744 review 第十七轮)。- existingSessionRoute: true,- });- if (!proceed) return false;+ // ① 本机会话维持既有 readiness gate。device-link 已建任务不把视图生命周期内+ // 的认证弹窗/导航闭包塞进 outbox:弱网时先建立稳定 clientId 的本地乐观消息,+ // 重连后由被控端 enqueue / steer 路径做权威校验。这样离开任务后旧 outbox 也不会+ // 再弹出旧页面的认证对话框或导航回旧路由。+ if (!remoteDeviceId) {+ const authVendor = displayAgentKind === 'pi' ? 'pi' : isCodex ? 'codex' : 'cc';+ const { proceed } = await vendorAuthGate.checkAndConfirm(authVendor, {+ // 已建会话:suspended 来源计入(停用不打断运行中会话,门禁只看凭证连接态,+ // PR #744 review 第十七轮)。+ existingSessionRoute: true,+ });+ if (!proceed) return false;+ }// Popover open → prevent re-entryif (folderPickerOpen) return false;@@ -2471,21 +2486,32 @@ export function CCAgentSessionView({// 草稿提交的首条之前,顺序倒置。if (sessionHandoffPreparing) return false;+ const orcaLeadVendorOptions =+ sessionId && session !== null && isOrcaLeadSession(session)+ ? { vendorOptions: { orcaRole: 'lead', orcaLeadSessionId: sessionId } }+ : undefined;+// ② Working directory checkif (!session?.workingDir) {pendingSendRef.current = {+ deliveryMode,message,model,effort,permissionMode,files,mentions,+ ...orcaLeadVendorOptions,...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),...(opts?.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),...(opts?.pastedTextRanges?.length ? { pastedTextRanges: opts.pastedTextRanges } : {}),...(opts?.slashCommandRanges !== undefined? { slashCommandRanges: opts.slashCommandRanges }: {}),+ ...(opts?.onRemoteOptimisticFailure+ ? { onRemoteOptimisticFailure: opts.onRemoteOptimisticFailure }+ : {}),+ ...(opts?.onDeferredAccepted ? { onDeferredAccepted: opts.onDeferredAccepted } : {}),};setFolderPickerOpen(true);return false;@@ -2515,12 +2541,7 @@ export function CCAgentSessionView({}// ④ Execute send — effort + permissionMode came straight from ChatInput (fresh value)- const orcaLeadVendorOptions =- sessionId && isOrcaLeadSession(session)- ? { vendorOptions: { orcaRole: 'lead', orcaLeadSessionId: sessionId } }- : undefined;- const dispatch = deliveryMode === 'steer' ? steerMessage : sendMessage;- return dispatch(message, model, effort, permissionMode, session.workingDir, files, mentions, {+ const sendOptions = {...orcaLeadVendorOptions,...(opts?.quotesEncoded ? { quotesEncoded: true } : {}),...(opts?.agentReferences?.length ? { agentReferences: opts.agentReferences } : {}),@@ -2528,7 +2549,33 @@ export function CCAgentSessionView({...(opts?.slashCommandRanges !== undefined? { slashCommandRanges: opts.slashCommandRanges }: {}),- });+ ...(opts?.onRemoteOptimisticFailure+ ? { onRemoteOptimisticFailure: opts.onRemoteOptimisticFailure }+ : {}),+ ...(opts?.onDeferredAccepted ? { onDeferredAccepted: opts.onDeferredAccepted } : {}),+ };+ if (deliveryMode === 'steer') {+ return steerMessage(+ message,+ model,+ effort,+ permissionMode,+ session.workingDir,+ files,+ mentions,+ sendOptions,+ );+ }+ return sendMessage(+ message,+ model,+ effort,+ permissionMode,+ session.workingDir,+ files,+ mentions,+ sendOptions,+ );},[maybeDispatchDesktopSlashCommand,@@ -2545,7 +2592,6 @@ export function CCAgentSessionView({t,vendorAuthGate,remoteDeviceId,- remoteSessionUnavailable,sessionHandoffPreparing,],);@@ -2687,13 +2733,7 @@ export function CCAgentSessionView({await refreshServerSession();await retryLastError();- }, [- canSwitchToClaudeSubscription,- refreshServerSession,- retryLastError,- session,- sessionId,- ]);+ }, [canSwitchToClaudeSubscription, refreshServerSession, retryLastError, session, sessionId]);const handleSilentStopContinue = useCallback(() => {continueAfterSilentStop();@@ -2710,9 +2750,10 @@ export function CCAgentSessionView({kind: 'usage-limit-recovery',requestId,sessionId,- agentKind: session?.agentKind === 'codex' || session?.agentKind === 'pi'- ? session.agentKind- : 'claude-code',+ agentKind:+ session?.agentKind === 'codex' || session?.agentKind === 'pi'+ ? session.agentKind+ : 'claude-code',resetAtMs: usageLimitRecovery.resetAtMs,}),});@@ -2783,7 +2824,14 @@ export function CCAgentSessionView({.update(sessionId, { model: defaultModel.id }).then(() => refreshServerSession()).catch((err) => log.warn('vendor fallback patch failed:', err));- }, [displayAgentKind, providers, refreshServerSession, sessionAgentKind, sessionId, sessionModel]);+ }, [+ displayAgentKind,+ providers,+ refreshServerSession,+ sessionAgentKind,+ sessionId,+ sessionModel,+ ]);// 远程协同交接被 app 关闭打断时的兜底:把上次没能发出去的正文回填到输入框。// 只回填、不自动补发(理由见 pendingFirstMessage 的「可恢复副本」注释)。@@ -3265,7 +3313,7 @@ export function CCAgentSessionView({) : null}{/* 远程会话首屏:等被控端经隧道返回历史/元数据期间的 loading(仅远程、延迟防闪)。 */}- {showRemoteLoading && <RemoteSessionLoading />}+ {showRemoteLoading && remoteConn === 'connected' && <RemoteSessionLoading />}{/* Full-area drop overlay.Keep the event-capture surface for the whole chat area, but leave the@@ -3351,7 +3399,9 @@ export function CCAgentSessionView({}}// 被控端可见性 chip 嵌进状态栏中央槽位,与 thinking / 时间 token 同行// (不再单独占一行)。中央槽位独立于状态栏淡入淡出 → 空闲时仍显示。- centerSlot={showInlineControlledBanner ? <ControlledBanner placement="statusbar" /> : null}+ centerSlot={+ showInlineControlledBanner ? <ControlledBanner placement="statusbar" /> : null+ }/>)}@@ -3415,9 +3465,7 @@ export function CCAgentSessionView({onViewBalance={canAccessBilling ? handleViewBalance : undefined}errorSourceProviderId={errorTailMsg?.errorProviderId ?? null}onSwitchToClaudeSubscription={- canSwitchToClaudeSubscription- ? handleSwitchToClaudeSubscription- : undefined+ canSwitchToClaudeSubscription ? handleSwitchToClaudeSubscription : undefined}silentEncryptedRetryEnabled={silentEncryptedRetryEnabled}onForkStripEncrypted={ownsWindowRoute ? handleForkStripEncrypted : undefined}@@ -3454,9 +3502,7 @@ export function CCAgentSessionView({onRetry={handleRetry}onSilentStopContinue={handleSilentStopContinue}onContinueAfterUsageReset={- usageLimitRecovery && !remoteDeviceId- ? handleContinueAfterUsageReset- : undefined+ usageLimitRecovery && !remoteDeviceId ? handleContinueAfterUsageReset : undefined}onCancel={handleDismissError}agentKind={session?.agentKind}@@ -3621,15 +3667,17 @@ export function CCAgentSessionView({taskHistoryMayBeIncomplete={!historyLoaded || hasMoreMessages || historyWindowHasIsland}- visible={!(- pendingPlanReview ||- pendingPermission ||- pendingAskUser ||- pendingPluginSetup ||- pendingIssueConfirm ||- pendingRenameSessionsConfirm ||- pendingGhostGrantConfirm- )}+ visible={+ !(+ pendingPlanReview ||+ pendingPermission ||+ pendingAskUser ||+ pendingPluginSetup ||+ pendingIssueConfirm ||+ pendingRenameSessionsConfirm ||+ pendingGhostGrantConfirm+ )+ }/>{/* 互斥:有任意 pending interaction 时,下方 takeover/overlay/ChatInput全部静默 — 跟改造前 ternary 链 (Plan ? : Perm ? : Ask ? :@@ -3684,7 +3732,7 @@ export function CCAgentSessionView({isAgentBusy={isAgentBusy}onStop={handleStopSession}pendingQueue={pendingQueue}- disabled={remoteSessionUnavailable || remoteHandoffPreparing}+ disabled={remoteHandoffPreparing}queuePaused={queuePaused}queueExpanded={queueExpanded}onQueueExpandedChange={setQueueExpanded}@@ -3758,25 +3806,23 @@ export function CCAgentSessionView({}: undefined,disabled:- !collabEnabled &&- (collabPolicy.loading || !collabPolicy.enabled),+ !collabEnabled && (collabPolicy.loading || !collabPolicy.enabled),// unsupported(被控端版本过旧、没有 maker:plugins:get-state)// 排在 unavailable 之前:它是确定性的不支持,给「稍后重试」是// 误导,上面的 onDisabledActivate 也只挂在 unavailable 上。- disabledReason:- !collabEnabled- ? collabPolicy.loading- ? t('newChat.collaboration.loadingHint')- : collabPolicy.unsupported- ? t('newChat.collaboration.unsupportedRemoteHint')- : collabPolicy.unavailable || !collabPolicy.enabled- ? t(- collabPolicy.unavailable- ? 'newChat.collaboration.unavailableHint'- : 'newChat.collaboration.disabledHint',- )- : undefined- : undefined,+ disabledReason: !collabEnabled+ ? collabPolicy.loading+ ? t('newChat.collaboration.loadingHint')+ : collabPolicy.unsupported+ ? t('newChat.collaboration.unsupportedRemoteHint')+ : collabPolicy.unavailable || !collabPolicy.enabled+ ? t(+ collabPolicy.unavailable+ ? 'newChat.collaboration.unavailableHint'+ : 'newChat.collaboration.disabledHint',+ )+ : undefined+ : undefined,}: undefined}diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 84bbd505a4..523e174553 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -48,6 +48,7 @@ import { projectDraftSessionTitle } from '@cindy/maker-shared/session-title';import { cn } from '@/lib/utils';import { toast } from '@/lib/toast';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import { useCCSessions } from '@/hooks/useCCSessions';import { refreshPendingAlerts, usePendingAlertAttention } from '@/hooks/usePendingAlertAttention';import { useAppShortcut } from '@/hooks/useAppShortcut';@@ -863,7 +864,8 @@ function ExpandedView({off();if (timer) clearTimeout(timer);};- const off = window.electronAPI.maker.schedule.onEvent((raw) => {+ const off = window.electronAPI.maker.schedule.onEvent((raw, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;const event = raw as SchedulerEvent;if (done) return;// 全局事件不含 scheduleId,提前过滤。diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsxindex c2ea704c9f..18f872a060 100644--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx@@ -175,6 +175,7 @@ import {getDataOwnerGeneration,isDataOwnerGenerationCurrent,} from '@/contexts/dataOwnerGeneration';+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { useDeviceLinkReconnectEpoch } from '@/features/device-link/useDeviceLinkReconnectEpoch';import { extractIpcError } from '@/utils/ipcError';import { matchNavigationCommandName, tryHandleNavigationCommand } from '@/lib/navigationCommands';@@ -1233,8 +1234,9 @@ export function NewMakerDraftRoute() {useEffect(() => {if (!isDeviceLinkDraft || !effectiveDeviceLinkDeviceId) return;const vendorSlot = capabilityAgentKind === 'claude-code' ? 'claudeCode' : capabilityAgentKind;- return window.electronAPI.deviceLink.onRemotePush((push) => {+ return window.electronAPI.deviceLink.onRemotePush((push, localOwnerStamp) => {if (push.deviceId !== effectiveDeviceLinkDeviceId) return;+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;if (push.channel !== 'maker:new-maker-draft:changed') return;const payload = push.payload as Record<string, RemoteDraftDefaults | undefined> | null;const next = payload?.[vendorSlot] ?? null;diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.tsindex fdb989dcdb..134dc85141 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationScheduleSessionIndex.ts@@ -1,6 +1,7 @@import { useCallback, useEffect, useRef, useState } from 'react';import type { SchedulerEvent } from '@cindy/maker-scheduler';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import { createLogger } from '@/lib/logger';import {clearSessionAttention,@@ -149,7 +150,8 @@ export function useAutomationScheduleSessionIndex(): ReadonlyMap<string, AutomatuseEffect(() => {cancelledRef.current = false;void refresh();- const off = window.electronAPI.maker.schedule.onEvent((raw) => {+ const off = window.electronAPI.maker.schedule.onEvent((raw, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;const event = raw as SchedulerEvent;if (event.type === 'session-bound') {// Scheduler notifier 是 schedule.notify 的唯一外发通知 owner;普通 sessiondiff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.tsindex 0fc223e9ef..f224ba6c64 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts@@ -33,6 +33,7 @@import { useEffect } from 'react';import { useAuth } from '@/contexts/AuthContext';+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { createLogger } from '@/lib/logger';import {remoteProjectsStore,@@ -507,9 +508,10 @@ export function useDeviceLinkRemoteProjects(): void {// 被控端 active-catalog 变化:供应商目录与 capabilities.availableModels 必须同代刷新。// 两套缓存订阅会把完整结果原子推给已挂载选择器,刷新期间保留旧列表避免空白跳变。- const offRemotePush = window.electronAPI.deviceLink.onRemotePush((push) => {+ const offRemotePush = window.electronAPI.deviceLink.onRemotePush((push, localOwnerStamp) => {if (disposed || push.channel !== 'maker:provider:changed' || !eligible.has(push.deviceId))return;+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;evictDeviceProviders(push.deviceId);evictDeviceCapabilities(push.deviceId);void prefetchDeviceProviders(push.deviceId);diff --git a/apps/desktop/src/renderer/features/learn/learnTransport.ts b/apps/desktop/src/renderer/features/learn/learnTransport.tsindex e978a341fe..78da870c74 100644--- a/apps/desktop/src/renderer/features/learn/learnTransport.ts+++ b/apps/desktop/src/renderer/features/learn/learnTransport.ts@@ -21,6 +21,7 @@import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import type { LearnEventPayload } from '../../../shared/learnTypes';@@ -81,8 +82,9 @@ export function subscribeLearnEvents(return window.electronAPI.learn.onEvent(cb);}return (- window.electronAPI.deviceLink?.onRemotePush?.((push) => {+ window.electronAPI.deviceLink?.onRemotePush?.((push, localOwnerStamp) => {if (push.deviceId !== deviceId || push.channel !== 'learn:event') return;+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;cb(push.payload as LearnEventPayload);}) ?? (() => {}));diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.tsindex f4ae47a0ee..0e52fa1e95 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useRunNowBusyGuard.ts@@ -22,6 +22,7 @@import { useCallback, useEffect, useRef, useState } from 'react';import type { SchedulerEvent } from '@cindy/maker-scheduler';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';export interface RunNowBusyGuard {/** 当前处于派发窗口内的 scheduleId 集合;驱动按钮 disabled。 */@@ -60,7 +61,8 @@ export function useRunNowBusyGuard(): RunNowBusyGuard {// 提前 release。此时用户若再点击是第二次独立有意操作,不构成同一次意图双发问题。// 两种场景都属可接受的已知行为。useEffect(() => {- const off = window.electronAPI.maker.schedule.onEvent((raw) => {+ const off = window.electronAPI.maker.schedule.onEvent((raw, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;const ev = raw as SchedulerEvent;if (ev.type === 'fired' ||diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useRuns.tsindex e724b68064..338d05fe92 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useRuns.ts@@ -13,6 +13,7 @@import { useCallback, useEffect, useRef, useState } from 'react';import type { ScheduleRun, SchedulerEvent } from '@cindy/maker-scheduler';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import { subscribeScheduleRunReadSync } from '../lib/scheduleRunReadSync';export interface UseRunsResult {@@ -79,7 +80,8 @@ export function useRuns(scheduleId: string | null, limit = 50): UseRunsResult {return;}void refresh();- const off = window.electronAPI.maker.schedule.onEvent((raw) => {+ const off = window.electronAPI.maker.schedule.onEvent((raw, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;const ev = raw as SchedulerEvent;if (ev.type === 'all-read') {void refresh();@@ -105,7 +107,8 @@ export function useRuns(scheduleId: string | null, limit = 50): UseRunsResult {const offReadSync = subscribeScheduleRunReadSync(() => void refresh());// Codex 费用在 done 后异步查价并落 message/run 账本,可能晚于 completed 事件。// 监听费用广播,避免历史卡永久保留 completed 时读到的旧快照。- const offTurnCost = window.electronAPI.onUsageMessageTurnCost?.(() => {+ const offTurnCost = window.electronAPI.onUsageMessageTurnCost?.((_payload, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;void refresh();});return () => {diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.tsindex 450ef4c365..dca18922cc 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleCostSummaries.ts@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import type { Schedule, SchedulerEvent } from '@cindy/maker-scheduler';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import { createLogger } from '@/lib/logger';import type { RegionalMoney } from '../../../../shared/regionalMoney';@@ -79,7 +80,8 @@ export function useScheduleCostSummaries(useEffect(() => {void refresh();- const offSchedule = window.electronAPI.maker.schedule.onEvent((raw) => {+ const offSchedule = window.electronAPI.maker.schedule.onEvent((raw, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;const event = raw as SchedulerEvent;if (event.type === 'fired' ||@@ -92,10 +94,12 @@ export function useScheduleCostSummaries(void refresh();}});- const offSpend = window.electronAPI.onUsageSessionSpendChanged(() => {+ const offSpend = window.electronAPI.onUsageSessionSpendChanged((_payload, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;void refresh();});- const offTurnCost = window.electronAPI.onUsageMessageTurnCost?.(() => {+ const offTurnCost = window.electronAPI.onUsageMessageTurnCost?.((_payload, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;void refresh();});return () => {diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.tsindex 49bfd24ebc..88e8ce532e 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleUnreadRunCounts.ts@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import type { Schedule, SchedulerEvent } from '@cindy/maker-scheduler';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import { createLogger } from '@/lib/logger';import { isUnreadScheduleRun } from '../lib/runUnread';import { loadScheduleSidebarIndexRuns } from '../lib/scheduleSidebarIndexRuns';@@ -48,7 +49,8 @@ export function useScheduleUnreadRunCounts(useEffect(() => {void refresh();- const off = window.electronAPI.maker.schedule.onEvent((raw) => {+ const off = window.electronAPI.maker.schedule.onEvent((raw, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;const event = raw as SchedulerEvent;if (event.type === 'fired' ||diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.tsindex 31cd91a55d..295ddd9ce0 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useSchedules.ts@@ -23,6 +23,7 @@ import type {SchedulerEvent,SchedulerRuntimeSnapshot,} from '@cindy/maker-scheduler';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import {schedulesStore,@@ -75,7 +76,8 @@ export function useSchedules(): UseSchedulesResult {/* 瞬时诊断状态失败不影响任务列表主数据。 */});};- const off = window.electronAPI.maker.schedule.onEvent((raw) => {+ const off = window.electronAPI.maker.schedule.onEvent((raw, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;const ev = raw as SchedulerEvent;if (ev.type === 'runtime-state') {runtimeRevisionRef.current += 1;diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.tsindex acb86ec785..3a247d1922 100644--- a/apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.ts+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useSessionReferences.ts@@ -6,6 +6,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import * as sessionService from '@/lib/sessionService';import type { SessionReference } from '../../../../shared/sessionReference';@@ -47,12 +48,18 @@ export function useSessionReferences(useEffect(() => {void refresh();if (ids.length === 0) return;- const offPatched = window.electronAPI.localDb.sessionsPush.onPatched(({ sessionId }) => {- if (idsRef.current.includes(sessionId)) void refresh();- });- const offCreated = window.electronAPI.localDb.sessionsPush.onCreated(({ sessionId }) => {- if (idsRef.current.includes(sessionId)) void refresh();- });+ const offPatched = window.electronAPI.localDb.sessionsPush.onPatched(+ ({ sessionId }, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;+ if (idsRef.current.includes(sessionId)) void refresh();+ },+ );+ const offCreated = window.electronAPI.localDb.sessionsPush.onCreated(+ ({ sessionId }, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;+ if (idsRef.current.includes(sessionId)) void refresh();+ },+ );return () => {requestRevisionRef.current += 1;offPatched();diff --git a/apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.ts b/apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.tsindex 18900ba8f8..19b2a33e6f 100644--- a/apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.ts+++ b/apps/desktop/src/renderer/features/scheduler/lib/schedulesStore.ts@@ -42,6 +42,7 @@import { useSyncExternalStore } from 'react';import type { Schedule, SchedulerEvent } from '@cindy/maker-scheduler';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';let cache: Schedule[] | null = null;let inflight: Promise<Schedule[]> | null = null;@@ -186,7 +187,10 @@ export function handleAuthStateChange(authState: MinimalAuthState): void {// 模块加载时一次性 wire(SSR / 测试环境 window undefined 时跳过)。// `if (typeof window !== 'undefined')` 守卫照 sessionsStore.ts:214 范式。if (typeof window !== 'undefined' && window.electronAPI?.maker?.schedule?.onEvent) {- window.electronAPI.maker.schedule.onEvent(handleSchedulerEvent);+ window.electronAPI.maker.schedule.onEvent((event, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;+ handleSchedulerEvent(event);+ });}if (typeof window !== 'undefined' && window.electronAPI?.onAuthStateChange) {window.electronAPI.onAuthStateChange(handleAuthStateChange);diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsxindex a6630e37a6..0d6fccbf60 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx+++ b/apps/desktop/src/renderer/hooks/__tests__/useCCAgentChatHiddenFreeze.test.tsx@@ -17,6 +17,7 @@ vi.mock('react-i18next', async (importOriginal) => {});vi.mock('@/features/device-link/remoteProjectsStore', () => ({+ getSessionDeviceId: () => undefined,remoteProjectsStore: {getSessionDeviceId: () => undefined,subscribe: vi.fn(() => () => undefined),@@ -104,6 +105,7 @@ vi.mock('@/lib/imageRef', () => ({vi.mock('@/lib/composerDraftStore', () => ({saveDraft: vi.fn(),+ setRemoteOptimisticAttachmentUrls: vi.fn(),plainTextToTiptapDoc: (text: string) => ({type: 'doc',content: [{ type: 'paragraph', content: [{ type: 'text', text }] }],diff --git a/apps/desktop/src/renderer/hooks/useAttachments.ts b/apps/desktop/src/renderer/hooks/useAttachments.tsindex 02161c062b..b1275bc176 100644--- a/apps/desktop/src/renderer/hooks/useAttachments.ts+++ b/apps/desktop/src/renderer/hooks/useAttachments.ts@@ -14,7 +14,7 @@* is used for the input-area chip and persistent message rendering).*/-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';import { createLogger } from '@/lib/logger';@@ -31,17 +31,21 @@ import {type AttachedFile,type AttachedFileInput,} from '@/lib/fileTypes';+import { inferFileType, base64ToUint8Array, PEEK_BYTES } from '@/lib/fileTypeInference';import {- inferFileType,- base64ToUint8Array,- PEEK_BYTES,-} from '@/lib/fileTypeInference';-import {+ captureDraftDiscardToken,getDraft as getComposerDraft,+ isDraftDiscardTokenCurrent,saveDraft as saveComposerDraft,subscribeDraft as subscribeComposerDraft,+ type ComposerDraftDiscardToken,} from '@/lib/composerDraftStore';import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+ type DataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';/*** A single "this file did not get attached" rejection, surfaced inline in the@@ -87,9 +91,57 @@ export interface UseAttachmentsReturn {updateFile: (id: string, patch: Partial<AttachedFile>) => void;/** Discard unsent files and remove any staged dangerous copies. */discardFiles: () => void;+ /** 失败时按 id 合并恢复本批附件,保留 RTT 期间新加的附件。 */+ restoreFiles: (files: readonly AttachedFile[]) => AttachedFile[];clearFiles: () => void;}+interface AttachmentDraftScope {+ storageKey: string | undefined;+ dataOwner: DataOwnerGeneration;+ discardToken: ComposerDraftDiscardToken | undefined;+}++interface AttachmentOperationScope extends AttachmentDraftScope {+ sessionId: string | undefined;+}++function isSameAttachmentDraftScope(+ left: AttachmentDraftScope | undefined,+ right: AttachmentDraftScope,+): boolean {+ return (+ left !== undefined &&+ left.storageKey === right.storageKey &&+ left.dataOwner.dataOwnerId === right.dataOwner.dataOwnerId &&+ left.dataOwner.generation === right.dataOwner.generation &&+ left.discardToken?.ownerScopedKey === right.discardToken?.ownerScopedKey &&+ left.discardToken?.generation === right.discardToken?.generation+ );+}++function isAttachmentDraftScopeActive(scope: AttachmentDraftScope): boolean {+ return (+ isDataOwnerGenerationCurrent(scope.dataOwner) &&+ (scope.discardToken === undefined || isDraftDiscardTokenCurrent(scope.discardToken))+ );+}++function isSameAttachmentOperationScope(+ left: AttachmentOperationScope,+ right: AttachmentOperationScope,+): boolean {+ return left.sessionId === right.sessionId && isSameAttachmentDraftScope(left, right);+}++function mergeAttachmentsById(+ existing: readonly AttachedFile[],+ incoming: readonly AttachedFile[],+): AttachedFile[] {+ const knownIds = new Set(existing.map((file) => file.id));+ return [...existing, ...incoming.filter((file) => !knownIds.has(file.id))];+}+/*** Read a Blob as base64 (drops the data:URI prefix). Used only as F6* fallback when the cache write fails — the primary clipboard path goes@@ -129,14 +181,25 @@ export function cleanupRemovedCachedImage(file: Pick<AttachedFile, 'url'> | unde* transient draft) when there is no real backend session yet* but you still want sidebar-switch survival.*/-export function useAttachments(- sessionId?: string,- draftKey?: string,-): UseAttachmentsReturn {+export function useAttachments(sessionId?: string, draftKey?: string): UseAttachmentsReturn {const { t } = useTranslation();const [attachments, setAttachments] = useState<AttachedFile[]>([]);const attachmentsRef = useRef<AttachedFile[]>(attachments);- const sessionIdRef = useRef<string | undefined>(sessionId);++ // The persistence layer is keyed by draftKey when provided, else sessionId.+ const storageKey = draftKey ?? sessionId;+ const dataOwner = getDataOwnerGeneration();+ const discardToken = useMemo(+ () => (storageKey ? captureDraftDiscardToken(storageKey) : undefined),+ [dataOwner, storageKey],+ );+ const attachmentOperationScopeRef = useRef<AttachmentOperationScope>({+ sessionId,+ storageKey,+ dataOwner,+ discardToken,+ });+ attachmentOperationScopeRef.current = { sessionId, storageKey, dataOwner, discardToken };// Inline rejections (file-too-large etc.). Surfaced in the composer instead// of a transient top-center toast, which was easy to miss. Transient UI only@@ -156,13 +219,73 @@ export function useAttachments(setRejections([]);}, []);+ const appendAttachments = useCallback((items: readonly AttachedFile[]) => {+ if (items.length === 0) return;+ const knownIds = new Set(attachmentsRef.current.map((file) => file.id));+ attachmentsRef.current = [+ ...attachmentsRef.current,+ ...items.filter((file) => !knownIds.has(file.id)),+ ];+ setAttachments((prev) => {+ const prevIds = new Set(prev.map((file) => file.id));+ const next = [...prev, ...items.filter((file) => !prevIds.has(file.id))];+ attachmentsRef.current = next;+ return next;+ });+ }, []);+// Keep refs in sync with latest props/state — addFiles/addClipboardImage// close over them via ref to avoid stale closures.attachmentsRef.current = attachments;- sessionIdRef.current = sessionId;- // The persistence layer is keyed by draftKey when provided, else sessionId.- const storageKey = draftKey ?? sessionId;+ const isAttachmentOperationScopeCurrent = useCallback(+ (scope: AttachmentOperationScope): boolean =>+ isAttachmentDraftScopeActive(scope) &&+ isSameAttachmentOperationScope(attachmentOperationScopeRef.current, scope),+ [],+ );++ const pushScopedRejections = useCallback(+ (scope: AttachmentOperationScope, messages: string[]) => {+ if (!isAttachmentOperationScopeCurrent(scope)) return;+ pushRejections(messages);+ },+ [isAttachmentOperationScopeCurrent, pushRejections],+ );++ const settleAttachmentsForScope = useCallback(+ (scope: AttachmentOperationScope, items: readonly AttachedFile[]) => {+ if (items.length === 0) return;+ if (!isAttachmentDraftScopeActive(scope)) {+ for (const item of items) cleanupRemovedCachedImage(item);+ cleanupStagedChatAttachmentFiles(items);+ return;+ }+ if (isSameAttachmentOperationScope(attachmentOperationScopeRef.current, scope)) {+ appendAttachments(items);+ return;+ }+ if (!scope.storageKey) {+ for (const item of items) cleanupRemovedCachedImage(item);+ cleanupStagedChatAttachmentFiles(items);+ return;+ }+ const existing = getComposerDraft(scope.storageKey);+ saveComposerDraft(+ scope.storageKey,+ {+ text: existing?.text ?? null,+ attachments: mergeAttachmentsById(existing?.attachments ?? [], items),+ quotes: existing?.quotes ?? [],+ browserComments: existing?.browserComments ?? [],+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),+ },+ { silent: true },+ );+ },+ [appendAttachments],+ );// ── Per-session draft (composer-draft-per-session) ──// Save current attachments back to the store on unmount / sessionId-change,@@ -182,65 +305,74 @@ export function useAttachments(// Text doesn't have this bug because ChatInput.onUpdate writes to the store// on every keystroke — by the time of unmount, text is already in the store.// Attachments only existed in React state, hence the asymmetry the user saw.- const previousStorageKeyRef = useRef<string | undefined>(undefined);+ const previousDraftScopeRef = useRef<AttachmentDraftScope | undefined>(undefined);useEffect(() => {+ if (!isDataOwnerGenerationCurrent(dataOwner)) return;+ const draftScope: AttachmentDraftScope = { storageKey, dataOwner, discardToken };if (storageKey === undefined) {- previousStorageKeyRef.current = storageKey;+ previousDraftScopeRef.current = draftScope;return;}- const prevKey = previousStorageKeyRef.current;+ const previousScope = previousDraftScopeRef.current;+ const draftScopeChanged = !isSameAttachmentDraftScope(previousScope, draftScope);// In-feature session switch (e.g. /cc-agent/:sessionId keeps the same hook// instance): rejections are transient and belong to the previous session,// so drop them. Fresh mounts start at [], so this is a no-op there.- if (prevKey !== undefined && prevKey !== storageKey) {+ if (previousScope !== undefined && draftScopeChanged) {setRejections([]);}// Restore from the store. On a fresh remount (FadeSwitcher), the store// may already hold attachments saved by the previous instance's cleanup.- // On in-place key change, the cleanup that just ran for prevKey has+ // On in-place key change, the cleanup that just ran for the previous key has// already saved the OLD session's attachments — now restore the NEW one.const restored = getComposerDraft(storageKey);if (restored?.attachments && restored.attachments.length > 0) {setAttachments(restored.attachments);- } else if (prevKey !== undefined && prevKey !== storageKey) {+ } else if (previousScope !== undefined && draftScopeChanged) {// In-place switch to a session with no saved attachments: clear stale// state. (Fresh mounts already start at [], so the no-op set is skipped.)setAttachments([]);}- previousStorageKeyRef.current = storageKey;+ previousDraftScopeRef.current = draftScope;return () => {+ if (!isAttachmentDraftScopeActive(draftScope)) return;// Snapshot current attachments under the storageKey we were associated// with at this render. Closure captures the right key for both// unmount and dep-change paths. Preserve any text the ChatInput// keystroke handler last wrote — this writer only owns attachments.const existing = getComposerDraft(storageKey);- saveComposerDraft(storageKey, {- text: existing?.text ?? null,- attachments: attachmentsRef.current,- quotes: existing?.quotes ?? [],- browserComments: existing?.browserComments ?? [],- ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),- ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),- }, { silent: true });+ saveComposerDraft(+ storageKey,+ {+ text: existing?.text ?? null,+ attachments: attachmentsRef.current,+ quotes: existing?.quotes ?? [],+ browserComments: existing?.browserComments ?? [],+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),+ },+ { silent: true },+ );};- }, [storageKey]);+ }, [dataOwner, storageKey]);// Same-session external draft writes (rewind/fork prefill) must replace the// parent-held attachment list immediately. Session switches are handled by// the restore effect above; this covers the "storageKey did not change" path.useEffect(() => {- if (storageKey === undefined) return;+ if (storageKey === undefined || !isDataOwnerGenerationCurrent(dataOwner)) return;return subscribeComposerDraft(storageKey, () => {+ if (!isDataOwnerGenerationCurrent(dataOwner)) return;const draft = getComposerDraft(storageKey);const next = draft?.attachments ?? [];attachmentsRef.current = next;setAttachments(next);});- }, [storageKey]);+ }, [dataOwner, storageKey]);// 附件变化实时(silent)镜像进 composerDraftStore,而非只在 unmount 快照。// 外部写入方(图片 lightbox 的"发送到对话")按 store 内容做合并追加;若 store@@ -250,14 +382,20 @@ export function useAttachments(// 1. 挂载首帧:attachments 仍是初始 [],写入会把待恢复的 draft 清空一拍;// 2. in-place 会话切换帧:attachments 仍是旧会话值,写入会把 A 会话的// 附件串写进 B 会话的 draft。- const lastSyncedKeyRef = useRef<string | undefined>(undefined);+ const lastSyncedDraftScopeRef = useRef<AttachmentDraftScope | undefined>(undefined);useEffect(() => {- if (storageKey === undefined) return;- if (lastSyncedKeyRef.current !== storageKey) {- lastSyncedKeyRef.current = storageKey;+ if (storageKey === undefined || !isDataOwnerGenerationCurrent(dataOwner)) return;+ const draftScope: AttachmentDraftScope = { storageKey, dataOwner, discardToken };+ if (!isAttachmentDraftScopeActive(draftScope)) return;+ if (!isSameAttachmentDraftScope(lastSyncedDraftScopeRef.current, draftScope)) {+ lastSyncedDraftScopeRef.current = draftScope;return;}const existing = getComposerDraft(storageKey);+ // `discardDraft` synchronously clears mounted attachment state. Its state+ // update may render once before navigation; do not recreate an empty Map+ // entry after the explicit discard boundary.+ if (!existing && attachments.length === 0) return;saveComposerDraft(storageKey,// saveDraft 是整对象替换:text / quotes / browserComments 都必须从@@ -273,7 +411,7 @@ export function useAttachments(},{ silent: true },);- }, [storageKey, attachments]);+ }, [attachments, dataOwner, storageKey]);// ── Folder path queue ──// Drop handlers push folder paths here; ChatInput consumes them as@@ -306,331 +444,351 @@ export function useAttachments(return payloads;}, []);- const addFiles = useCallback(async (fileList: FileList | readonly File[]) => {- // Fresh attempt: clear stale rejections so the inline strip reflects only- // this drop's failures.- setRejections([]);- // ── Step 1: collect rawFiles, intercept obvious failure cases up-front ──- // In sandboxed Electron (20+), File.path is unavailable — use- // webUtils.getPathForFile() exposed via preload bridge instead.- type RawFile = { name: string; path: string; size: number; file: File };- const rawFiles: RawFile[] = [];- const earlyErrors: { name: string; reason: string }[] = [];- for (const f of Array.from(fileList)) {- let filePath = '';- try {- filePath = window.electronAPI.getFilePath(f);- } catch {- // Fallback: try legacy File.path (non-sandboxed builds)- filePath = (f as File & { path?: string }).path ?? '';- }- if (!filePath) {- pushRejections([t('logic.toasts.attachmentLocalOnly', { name: f.name })]);- continue;- }- // F-FI-8 spec step 1: 0-byte files are intercepted here so they never- // reach the peek IPC (would otherwise produce an "无法识别" instead of- // the more accurate "文件为空" error).- if (f.size === 0) {- earlyErrors.push({ name: f.name, reason: t('logic.fileTypes.fileEmpty') });- continue;+ const addFiles = useCallback(+ async (fileList: FileList | readonly File[]) => {+ const operationScope = attachmentOperationScopeRef.current;+ const attachmentCountAtStart = attachmentsRef.current.length;+ // Fresh attempt: clear stale rejections so the inline strip reflects only+ // this drop's failures.+ setRejections([]);+ // ── Step 1: collect rawFiles, intercept obvious failure cases up-front ──+ // In sandboxed Electron (20+), File.path is unavailable — use+ // webUtils.getPathForFile() exposed via preload bridge instead.+ type RawFile = { name: string; path: string; size: number; file: File };+ const rawFiles: RawFile[] = [];+ const earlyErrors: { name: string; reason: string }[] = [];+ for (const f of Array.from(fileList)) {+ let filePath = '';+ try {+ filePath = window.electronAPI.getFilePath(f);+ } catch {+ // Fallback: try legacy File.path (non-sandboxed builds)+ filePath = (f as File & { path?: string }).path ?? '';+ }+ if (!filePath) {+ pushScopedRejections(operationScope, [+ t('logic.toasts.attachmentLocalOnly', { name: f.name }),+ ]);+ continue;+ }+ // F-FI-8 spec step 1: 0-byte files are intercepted here so they never+ // reach the peek IPC (would otherwise produce an "无法识别" instead of+ // the more accurate "文件为空" error).+ if (f.size === 0) {+ earlyErrors.push({ name: f.name, reason: t('logic.fileTypes.fileEmpty') });+ continue;+ }+ rawFiles.push({ name: f.name, path: filePath, size: f.size, file: f });}- rawFiles.push({ name: f.name, path: filePath, size: f.size, file: f });- }- // ── Step 2: split into known / unknown by extension/filename ──- const knownRaw: RawFile[] = [];- const unknownRaw: RawFile[] = [];- for (const raw of rawFiles) {- const ext = extractExt(raw.name);- const category = ext ? categorizeFile(ext) : categorizeByFilename(raw.name);- if (category) {- knownRaw.push(raw);- } else {- unknownRaw.push(raw);+ // ── Step 2: split into known / unknown by extension/filename ──+ const knownRaw: RawFile[] = [];+ const unknownRaw: RawFile[] = [];+ for (const raw of rawFiles) {+ const ext = extractExt(raw.name);+ const category = ext ? categorizeFile(ext) : categorizeByFilename(raw.name);+ if (category) {+ knownRaw.push(raw);+ } else {+ unknownRaw.push(raw);+ }}- }- // ── Step 3: enrich unknown files via peek-IPC + magic/UTF-8 inference ──- // Promise.all is fine: max 20 files per drop, IPC pressure negligible.- type EnrichResult =- | { ok: true; raw: RawFile; ext: string }- | { ok: false; raw: RawFile; reason: string };+ // ── Step 3: enrich unknown files via peek-IPC + magic/UTF-8 inference ──+ // Promise.all is fine: max 20 files per drop, IPC pressure negligible.+ type EnrichResult =+ { ok: true; raw: RawFile; ext: string } | { ok: false; raw: RawFile; reason: string };++ const enrichmentResults: EnrichResult[] = await Promise.all(+ unknownRaw.map(async (r): Promise<EnrichResult> => {+ try {+ const peek = await window.electronAPI.peekFileHeader({+ filePath: r.path,+ bytes: PEEK_BYTES,+ });+ if (!peek.success)+ return { ok: false, raw: r, reason: t('logic.fileTypes.readFailed') };+ // Defensive: step 1 already filters f.size === 0, but a file may have+ // been truncated between drop and peek.+ if (peek.actualBytes === 0 || !peek.data) {+ return { ok: false, raw: r, reason: t('logic.fileTypes.fileEmpty') };+ }+ const buffer = base64ToUint8Array(peek.data);+ const inferred = inferFileType(buffer);+ if (!inferred) return { ok: true, raw: r, ext: '' };+ return { ok: true, raw: r, ext: inferred.ext };+ } catch {+ return { ok: false, raw: r, reason: t('logic.fileTypes.readFailed') };+ }+ }),+ );+ if (!isDataOwnerGenerationCurrent(operationScope.dataOwner)) return;++ // ── Step 4: validate known via existing validateFiles, validate enriched+ // locally (cannot reuse validateFiles — it would extractExt(name)+ // on the original filename and discard the inferred ext) ──+ const knownResult = validateFiles(+ knownRaw.map((r) => ({ name: r.name, path: r.path, size: r.size })),+ attachmentCountAtStart,+ );++ const enrichedOk = enrichmentResults.filter(+ (r): r is Extract<EnrichResult, { ok: true }> => r.ok,+ );+ const validInferred: AttachedFileInput[] = [];+ for (const r of enrichedOk) {+ const category = r.ext ? (categorizeFile(r.ext) ?? 'file') : 'file';+ const mimeType = getMimeType(r.ext, category);+ validInferred.push({+ name: r.raw.name, // keep original filename (spec)+ path: r.raw.path,+ size: r.raw.size,+ ext: r.ext, // inferred extension drives mime + downstream branch+ category,+ mimeType,+ });+ }- const enrichmentResults: EnrichResult[] = await Promise.all(- unknownRaw.map(async (r): Promise<EnrichResult> => {+ // ── Step 5: merge errors, toast each one, then merge valid lists ──+ const inferenceErrors = enrichmentResults+ .filter((r): r is Extract<EnrichResult, { ok: false }> => !r.ok)+ .map((r) => ({ name: r.raw.name, reason: r.reason }));++ const allErrors = [...earlyErrors, ...inferenceErrors, ...knownResult.errors];+ pushScopedRejections(+ operationScope,+ allErrors.map((err) =>+ t('logic.toasts.attachmentReadError', { name: err.name, reason: err.reason }),+ ),+ );++ const valid = [...knownResult.valid, ...validInferred];+ if (valid.length === 0) return;++ // IPC read for each valid file+ const newAttachments: AttachedFile[] = [];+ const currentSessionId = operationScope.sessionId;++ for (const item of valid) {+ if (!isDataOwnerGenerationCurrent(operationScope.dataOwner)) break;+ let stagedAttachmentPath: string | null = null;try {- const peek = await window.electronAPI.peekFileHeader({- filePath: r.path,- bytes: PEEK_BYTES,- });- if (!peek.success) return { ok: false, raw: r, reason: t('logic.fileTypes.readFailed') };- // Defensive: step 1 already filters f.size === 0, but a file may have- // been truncated between drop and peek.- if (peek.actualBytes === 0 || !peek.data) {- return { ok: false, raw: r, reason: t('logic.fileTypes.fileEmpty') };+ let attachmentPath = item.path;+ if (isDangerousAttachmentName(item.name) || isDangerousAttachmentName(item.path)) {+ const staged = await window.electronAPI.stageChatAttachment({+ sourcePath: item.path,+ suggestedName: item.name,+ });+ if (!staged.success) {+ pushScopedRejections(operationScope, [+ t('logic.toasts.attachmentReadFailed', {+ name: item.name,+ error: staged.code,+ }),+ ]);+ continue;+ }+ attachmentPath = staged.path;+ stagedAttachmentPath = staged.path;}- const buffer = base64ToUint8Array(peek.data);- const inferred = inferFileType(buffer);- if (!inferred) return { ok: true, raw: r, ext: '' };- return { ok: true, raw: r, ext: inferred.ext };- } catch {- return { ok: false, raw: r, reason: t('logic.fileTypes.readFailed') };- }- }),- );-- // ── Step 4: validate known via existing validateFiles, validate enriched- // locally (cannot reuse validateFiles — it would extractExt(name)- // on the original filename and discard the inferred ext) ──- const currentCount = attachmentsRef.current.length;- const knownResult = validateFiles(- knownRaw.map((r) => ({ name: r.name, path: r.path, size: r.size })),- currentCount,- );-- const enrichedOk = enrichmentResults.filter(- (r): r is Extract<EnrichResult, { ok: true }> => r.ok,- );- const validInferred: AttachedFileInput[] = [];- for (const r of enrichedOk) {- const category = r.ext ? (categorizeFile(r.ext) ?? 'file') : 'file';- const mimeType = getMimeType(r.ext, category);- validInferred.push({- name: r.raw.name, // keep original filename (spec)- path: r.raw.path,- size: r.raw.size,- ext: r.ext, // inferred extension drives mime + downstream branch- category,- mimeType,- });- }- // ── Step 5: merge errors, toast each one, then merge valid lists ──- const inferenceErrors = enrichmentResults- .filter((r): r is Extract<EnrichResult, { ok: false }> => !r.ok)- .map((r) => ({ name: r.raw.name, reason: r.reason }));-- const allErrors = [- ...earlyErrors,- ...inferenceErrors,- ...knownResult.errors,- ];- pushRejections(- allErrors.map((err) =>- t('logic.toasts.attachmentReadError', { name: err.name, reason: err.reason }),- ),- );-- const valid = [...knownResult.valid, ...validInferred];- if (valid.length === 0) return;+ if (item.category === 'image') {+ // image-local-cache primary path: IPC copy → xdt-image:// URL.+ // Falls back to in-memory base64 if cache write fails (F6).+ let cached: { url: string } | null = null;+ if (currentSessionId) {+ try {+ cached = await window.electronAPI.cacheImageFromPath({+ sessionId: currentSessionId,+ sourcePath: attachmentPath,+ originalName: item.name,+ });+ } catch (err) {+ log.warn('cacheImageFromPath failed:', err);+ cached = null;+ }+ }- // IPC read for each valid file- const newAttachments: AttachedFile[] = [];- const currentSessionId = sessionIdRef.current;+ if (!cached && !isDataOwnerGenerationCurrent(operationScope.dataOwner)) {+ cleanupStagedChatAttachmentFiles([{ path: stagedAttachmentPath ?? '' }]);+ break;+ }- for (const item of valid) {- let stagedAttachmentPath: string | null = null;- try {- let attachmentPath = item.path;- if (- isDangerousAttachmentName(item.name) ||- isDangerousAttachmentName(item.path)- ) {- const staged = await window.electronAPI.stageChatAttachment({- sourcePath: item.path,- suggestedName: item.name,- });- if (!staged.success) {- pushRejections([- t('logic.toasts.attachmentReadFailed', {+ if (cached) {+ newAttachments.push({+ id: crypto.randomUUID(),name: item.name,- error: staged.code,- }),- ]);- continue;- }- attachmentPath = staged.path;- stagedAttachmentPath = staged.path;- }-- if (item.category === 'image') {- // image-local-cache primary path: IPC copy → xdt-image:// URL.- // Falls back to in-memory base64 if cache write fails (F6).- let cached: { url: string } | null = null;- if (currentSessionId) {- try {- cached = await window.electronAPI.cacheImageFromPath({- sessionId: currentSessionId,- sourcePath: attachmentPath,+ path: attachmentPath,+ ext: item.ext,+ size: item.size,+ category: 'image',+ mimeType: item.mimeType,+ url: cached.url,+ originalName: item.name,+ });+ } else {+ // F6 fallback: read original file as base64 and warn the user that+ // the image is in-memory only (lost on restart).+ const result = await window.electronAPI.readFileForAttachment({+ filePath: attachmentPath,+ encoding: 'base64',+ });+ if (!result.success) {+ cleanupStagedChatAttachmentFiles([{ path: stagedAttachmentPath ?? '' }]);+ pushScopedRejections(operationScope, [+ t('logic.toasts.attachmentReadFailed', { name: item.name, error: result.error }),+ ]);+ continue;+ }+ // 仅在"有 session 但缓存写失败"时告警;草稿态(无 sessionId)走 base64+ // 是设计行为,不算失败,不该打扰用户。+ if (currentSessionId && isAttachmentOperationScopeCurrent(operationScope)) {+ toast.warning(t('logic.toasts.attachmentLocalCacheFailed'));+ }+ newAttachments.push({+ id: crypto.randomUUID(),+ name: item.name,+ path: attachmentPath,+ ext: item.ext,+ size: item.size,+ category: 'image',+ mimeType: item.mimeType,+ base64: result.data,originalName: item.name,});- } catch (err) {- log.warn('cacheImageFromPath failed:', err);- cached = null;}- }-- if (cached) {+ } else if (item.category === 'pdf') {+ // attachment-path-passthrough F2: do not base64-load PDFs in the+ // renderer; only the absolute path is forwarded. The model uses+ // its Read tool on demand.newAttachments.push({id: crypto.randomUUID(),name: item.name,path: attachmentPath,ext: item.ext,size: item.size,- category: 'image',+ category: 'pdf',mimeType: item.mimeType,- url: cached.url,- originalName: item.name,});} else {- // F6 fallback: read original file as base64 and warn the user that- // the image is in-memory only (lost on restart).- const result = await window.electronAPI.readFileForAttachment({- filePath: attachmentPath,- encoding: 'base64',- });- if (!result.success) {- cleanupStagedChatAttachmentFiles([{ path: stagedAttachmentPath ?? '' }]);- pushRejections([t('logic.toasts.attachmentReadFailed', { name: item.name, error: result.error })]);- continue;- }- // 仅在"有 session 但缓存写失败"时告警;草稿态(无 sessionId)走 base64- // 是设计行为,不算失败,不该打扰用户。- if (currentSessionId) {- toast.warning(t('logic.toasts.attachmentLocalCacheFailed'));- }+ // text / office — attachment-path-passthrough F1: no+ // readFileForAttachment / textContent. Path-only; the model+ // decides whether to read or convert on demand.newAttachments.push({id: crypto.randomUUID(),name: item.name,path: attachmentPath,ext: item.ext,size: item.size,- category: 'image',+ category: item.category,mimeType: item.mimeType,- base64: result.data,- originalName: item.name,});}- } else if (item.category === 'pdf') {- // attachment-path-passthrough F2: do not base64-load PDFs in the- // renderer; only the absolute path is forwarded. The model uses- // its Read tool on demand.- newAttachments.push({- id: crypto.randomUUID(),- name: item.name,- path: attachmentPath,- ext: item.ext,- size: item.size,- category: 'pdf',- mimeType: item.mimeType,- });- } else {- // text / office — attachment-path-passthrough F1: no- // readFileForAttachment / textContent. Path-only; the model- // decides whether to read or convert on demand.- newAttachments.push({- id: crypto.randomUUID(),- name: item.name,- path: attachmentPath,- ext: item.ext,- size: item.size,- category: item.category,- mimeType: item.mimeType,- });+ } catch (err) {+ cleanupStagedChatAttachmentFiles([{ path: stagedAttachmentPath ?? '' }]);+ pushScopedRejections(operationScope, [+ t('logic.toasts.attachmentReadFailed', {+ name: item.name,+ error: err instanceof Error ? err.message : String(err),+ }),+ ]);}- } catch (err) {- cleanupStagedChatAttachmentFiles([{ path: stagedAttachmentPath ?? '' }]);- pushRejections([t('logic.toasts.attachmentReadFailed', { name: item.name, error: err instanceof Error ? err.message : String(err) })]);}- }- if (newAttachments.length > 0) {- setAttachments((prev) => [...prev, ...newAttachments]);- }- }, [t, pushRejections]);+ settleAttachmentsForScope(operationScope, newAttachments);+ },+ [isAttachmentOperationScopeCurrent, pushScopedRejections, settleAttachmentsForScope, t],+ );/*** Add an image directly from the clipboard (Cmd+V / Ctrl+V screenshot).* Primary path: blob → arrayBuffer → IPC writeBuffer → xdt-image:// URL.* Fallback (F6): blob → base64 in-memory + toast warning.*/- const addClipboardImage = useCallback(async (blob: Blob) => {- setRejections([]);+ const addClipboardImage = useCallback(+ async (blob: Blob) => {+ const operationScope = attachmentOperationScopeRef.current;+ setRejections([]);- const mimeType = blob.type || 'image/png';- // Derive extension from MIME type- const extMap: Record<string, string> = {- 'image/png': '.png',- 'image/jpeg': '.jpg',- 'image/gif': '.gif',- 'image/webp': '.webp',- };- const ext = extMap[mimeType] ?? '.png';- const timestamp = Date.now();- const name = `clipboard-${timestamp}${ext}`;+ const mimeType = blob.type || 'image/png';+ // Derive extension from MIME type+ const extMap: Record<string, string> = {+ 'image/png': '.png',+ 'image/jpeg': '.jpg',+ 'image/gif': '.gif',+ 'image/webp': '.webp',+ };+ const ext = extMap[mimeType] ?? '.png';+ const timestamp = Date.now();+ const name = `clipboard-${timestamp}${ext}`;- const currentSessionId = sessionIdRef.current;+ const currentSessionId = operationScope.sessionId;- try {- const buffer = new Uint8Array(await blob.arrayBuffer());+ try {+ const buffer = new Uint8Array(await blob.arrayBuffer());+ if (!isDataOwnerGenerationCurrent(operationScope.dataOwner)) return;- let cached: { url: string } | null = null;- if (currentSessionId) {- try {- cached = await window.electronAPI.cacheImageFromBuffer({- sessionId: currentSessionId,- buffer,- mimeType,- suggestedName: name,- });- } catch (err) {- log.warn('cacheImageFromBuffer failed:', err);- cached = null;+ let cached: { url: string } | null = null;+ if (currentSessionId) {+ try {+ cached = await window.electronAPI.cacheImageFromBuffer({+ sessionId: currentSessionId,+ buffer,+ mimeType,+ suggestedName: name,+ });+ } catch (err) {+ log.warn('cacheImageFromBuffer failed:', err);+ cached = null;+ }}- }- if (cached) {- setAttachments((prev) => [- ...prev,- {- id: crypto.randomUUID(),- name,- path: `clipboard://paste-${timestamp}`,- ext,- size: blob.size,- category: 'image',- mimeType,- url: cached.url,- originalName: name,- },- ]);- } else {- // F6 fallback- const base64 = await blobToBase64(blob);- // 仅在"有 session 但缓存写失败"时告警;草稿态走 base64 是设计行为。- if (currentSessionId) {- toast.warning(t('logic.toasts.attachmentLocalCacheFailed'));+ if (cached) {+ settleAttachmentsForScope(operationScope, [+ {+ id: crypto.randomUUID(),+ name,+ path: `clipboard://paste-${timestamp}`,+ ext,+ size: blob.size,+ category: 'image',+ mimeType,+ url: cached.url,+ originalName: name,+ },+ ]);+ } else {+ if (!isDataOwnerGenerationCurrent(operationScope.dataOwner)) return;+ // F6 fallback+ const base64 = await blobToBase64(blob);+ // 仅在"有 session 但缓存写失败"时告警;草稿态走 base64 是设计行为。+ if (currentSessionId && isAttachmentOperationScopeCurrent(operationScope)) {+ toast.warning(t('logic.toasts.attachmentLocalCacheFailed'));+ }+ settleAttachmentsForScope(operationScope, [+ {+ id: crypto.randomUUID(),+ name,+ path: `clipboard://paste-${timestamp}`,+ ext,+ size: blob.size,+ category: 'image',+ mimeType,+ base64,+ originalName: name,+ },+ ]);}- setAttachments((prev) => [- ...prev,- {- id: crypto.randomUUID(),- name,- path: `clipboard://paste-${timestamp}`,- ext,- size: blob.size,- category: 'image',- mimeType,- base64,- originalName: name,- },+ } catch (err) {+ pushScopedRejections(operationScope, [+ t('logic.toasts.attachmentPasteFailed', {+ message: err instanceof Error ? err.message : String(err),+ }),]);}- } catch (err) {- pushRejections([t('logic.toasts.attachmentPasteFailed', { message: err instanceof Error ? err.message : String(err) })]);- }- }, [t, pushRejections]);+ },+ [isAttachmentOperationScopeCurrent, pushScopedRejections, settleAttachmentsForScope, t],+ );const removeFile = useCallback((id: string) => {const removed = attachmentsRef.current.find((f) => f.id === id);@@ -640,11 +798,35 @@ export function useAttachments(cleanupRemovedCachedImage(removed);}if (removed) cleanupStagedChatAttachmentFiles([removed]);- setAttachments((prev) => prev.filter((f) => f.id !== id));+ setAttachments((prev) => {+ const next = prev.filter((f) => f.id !== id);+ attachmentsRef.current = next;+ return next;+ });}, []);const updateFile = useCallback((id: string, patch: Partial<AttachedFile>) => {- setAttachments((prev) => prev.map((f) => (f.id === id ? { ...f, ...patch } : f)));+ setAttachments((prev) => {+ const next = prev.map((f) => (f.id === id ? { ...f, ...patch } : f));+ attachmentsRef.current = next;+ return next;+ });+ }, []);++ const restoreFiles = useCallback((files: readonly AttachedFile[]): AttachedFile[] => {+ if (files.length === 0) return attachmentsRef.current;+ const restoredIds = new Set(files.map((file) => file.id));+ const immediate = [+ ...files,+ ...attachmentsRef.current.filter((file) => !restoredIds.has(file.id)),+ ];+ attachmentsRef.current = immediate;+ setAttachments((prev) => {+ const restored = [...files, ...prev.filter((file) => !restoredIds.has(file.id))];+ attachmentsRef.current = restored;+ return restored;+ });+ return immediate;}, []);const discardFiles = useCallback(() => {@@ -683,6 +865,7 @@ export function useAttachments(removeFile,updateFile,discardFiles,+ restoreFiles,clearFiles,};}diff --git a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts b/apps/desktop/src/renderer/hooks/useCCAgentChat.tsindex 4ba977dc01..a73d8f5381 100644--- a/apps/desktop/src/renderer/hooks/useCCAgentChat.ts+++ b/apps/desktop/src/renderer/hooks/useCCAgentChat.ts@@ -126,6 +126,8 @@ interface UseCCAgentChatReturn {agentReferences?: AgentInputReference[];pastedTextRanges?: PastedTextRange[];slashCommandRanges?: SlashCommandRange[];+ beforeEnqueue?: () => Promise<boolean>;+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;},) => Promise<boolean>;compactSession: (@@ -149,6 +151,8 @@ interface UseCCAgentChatReturn {agentReferences?: AgentInputReference[];pastedTextRanges?: PastedTextRange[];slashCommandRanges?: SlashCommandRange[];+ beforeEnqueue?: () => Promise<boolean>;+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;},) => Promise<boolean>;steerQueuedMessage: (clientId: string) => Promise<boolean>;@@ -400,6 +404,8 @@ export function useCCAgentChat(agentReferences?: AgentInputReference[];pastedTextRanges?: PastedTextRange[];slashCommandRanges?: SlashCommandRange[];+ beforeEnqueue?: () => Promise<boolean>;+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;},): Promise<boolean> => {if (!sessionId) return Promise.resolve(false);@@ -454,6 +460,8 @@ export function useCCAgentChat(agentReferences?: AgentInputReference[];pastedTextRanges?: PastedTextRange[];slashCommandRanges?: SlashCommandRange[];+ beforeEnqueue?: () => Promise<boolean>;+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;},) => {if (!sessionId) return Promise.resolve(false);@@ -833,7 +841,9 @@ export function useCCAgentChat(errorReason:lightState.error != null? (lightState.errorReason ?? null)- : (lightState.recoverableError != null ? (lightState.errorReason ?? null) : null),+ : lightState.recoverableError != null+ ? (lightState.errorReason ?? null)+ : null,// 当前 error 是非终止 recoverableError(turn 在跑,daemon 自动重试中):// ErrorBanner 网络分支据此显示「正在自动重试…」而非「可点击重试」。errorIsRecoverable: !lightState.error && lightState.recoverableError != null,@@ -841,8 +851,7 @@ export function useCCAgentChat(credentialSwitchWait: lightState.credentialSwitchWait,continuationInFlightClientId: lightState.continuationInFlightClientId,continuationTurnClientId: lightState.continuationTurnClientId,- continuationInFlightProjectionCapability:- lightState.continuationInFlightProjectionCapability,+ continuationInFlightProjectionCapability: lightState.continuationInFlightProjectionCapability,loadOlderMessages,isLoadingMore: lightState.isLoadingMore,hasMoreMessages: lightState.hasMoreMessages,diff --git a/apps/desktop/src/renderer/hooks/usePendingAlertAttention.ts b/apps/desktop/src/renderer/hooks/usePendingAlertAttention.tsindex 78c14e96dd..995bb94b11 100644--- a/apps/desktop/src/renderer/hooks/usePendingAlertAttention.ts+++ b/apps/desktop/src/renderer/hooks/usePendingAlertAttention.ts@@ -36,6 +36,7 @@*/import { useEffect } from 'react';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import {addSessionAttention,clearSessionAttention,@@ -223,7 +224,8 @@ export function usePendingAlertAttention(): void {useEffect(() => {const sessionsPush = window.electronAPI?.localDb?.sessionsPush;if (!sessionsPush) return;- return sessionsPush.onPatched(({ sessionId, patch }) => {+ return sessionsPush.onPatched(({ sessionId, patch }, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;if (patch && typeof patch === 'object' && 'lastTurnEndedAt' in patch) {noteInterruptedAck(sessionId);}@@ -235,7 +237,8 @@ export function usePendingAlertAttention(): void {useEffect(() => {const onErrorPersisted = window.electronAPI?.localDb?.messages?.onErrorPersisted;if (!onErrorPersisted) return;- return onErrorPersisted(() => {+ return onErrorPersisted((_payload, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;void refreshPendingAlerts();});}, []);@@ -248,7 +251,8 @@ export function usePendingAlertAttention(): void {useEffect(() => {const onCreated = window.electronAPI?.localDb?.messages?.onCreated;if (!onCreated) return;- return onCreated(({ message }) => {+ return onCreated(({ message }, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;if (message?.role === 'error') void refreshPendingAlerts();});}, []);diff --git a/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts b/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.tsindex 807eb05d4a..0b6a2b5481 100644--- a/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts+++ b/apps/desktop/src/renderer/hooks/useSessionEstimatedValue.ts@@ -10,6 +10,7 @@import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';import { useChatDisplaySnapshot } from '@/components/chat/ChatDisplaySnapshotContext';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import { makerChatStore, type ChatMessage } from '@/lib/makerChatStore';import { estimatedSessionValueFor } from '@/lib/makerTransport';import { resolveStaleCodexSubscriptionValueEstimate } from '../../shared/codexSubscriptionValue';@@ -301,10 +302,13 @@ export function useSessionEstimatedValue(};}- const unsubscribeTurnCost = window.electronAPI.onUsageMessageTurnCost?.((payload) => {- if (payload.sessionId !== sessionId) return;- mergeEntry(resolveEstimatedValueTurnCostEntry(payload));- });+ const unsubscribeTurnCost = window.electronAPI.onUsageMessageTurnCost?.(+ (payload, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;+ if (payload.sessionId !== sessionId) return;+ mergeEntry(resolveEstimatedValueTurnCostEntry(payload));+ },+ );// 按会话来源路由:device-link 远程会话查被控端(本地库无该会话的行,查本机恒 0)。void estimatedSessionValueFor(sessionId).then((snapshot) => {diff --git a/apps/desktop/src/renderer/hooks/useSessionSpend.ts b/apps/desktop/src/renderer/hooks/useSessionSpend.tsindex 27f8517d1e..f0dcc4396d 100644--- a/apps/desktop/src/renderer/hooks/useSessionSpend.ts+++ b/apps/desktop/src/renderer/hooks/useSessionSpend.ts@@ -10,6 +10,7 @@*/import { useEffect, useState } from 'react';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';import { getSessionFor } from '@/lib/makerTransport';import {legacyUsdMoney,@@ -54,7 +55,8 @@ export function useSessionSpend(: null),);};- const unsubscribe = window.electronAPI.onUsageSessionSpendChanged((res) => {+ const unsubscribe = window.electronAPI.onUsageSessionSpendChanged((res, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;if (res.sessionId === sessionId) {receivedCurrentEvent = true;applyMoney(res.totalMoney, res.totalCostUsd);diff --git a/apps/desktop/src/renderer/hooks/useSessionTokens.ts b/apps/desktop/src/renderer/hooks/useSessionTokens.tsindex bf8ee7a6df..54cf972e91 100644--- a/apps/desktop/src/renderer/hooks/useSessionTokens.ts+++ b/apps/desktop/src/renderer/hooks/useSessionTokens.ts@@ -6,6 +6,7 @@*/import { useEffect, useState } from 'react';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';export function useSessionTokens(sessionId: string | undefined,@@ -21,7 +22,8 @@ export function useSessionTokens(useEffect(() => {if (!sessionId) return;- const unsubscribe = window.electronAPI.onUsageSessionTokensChanged?.((res) => {+ const unsubscribe = window.electronAPI.onUsageSessionTokensChanged?.((res, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;if (res.sessionId === sessionId) {setTokens(res.totalTokens);}diff --git a/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.ts b/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.tsindex e060dc863e..cce02b7b9b 100644--- a/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.ts@@ -2,17 +2,28 @@ import { describe, expect, it, vi } from 'vitest';import type { JSONContent } from '@tiptap/core';import type { AttachedFile } from '@/lib/fileTypes';+import type { BrowserCommentDraftItem } from '@/lib/browserComments';import {+ appendBrowserCommentToDraft,appendQuoteToDraft,+ captureDraftDiscardToken,clearDraft,clearDraftAndNotify,+ discardDraft,draftHasContent,+ getAllDraftAttachmentUrls,getDraft,getDraftPresence,+ getOrCreateRemoteOptimisticTransitionCheckpoint,+ isDraftDiscardTokenCurrent,plainTextToTiptapDoc,quickStartTextToTiptapDoc,+ removeRemoteOptimisticDraftFragment,+ restoreRemoteOptimisticDraft,saveDraft,+ saveComposerTextAfterAsyncTransition,setComposerDraftOwner,+ setRemoteOptimisticAttachmentUrls,subscribeDraft,subscribeDraftPresence,tiptapDocHasContent,@@ -38,16 +49,81 @@ const mentionDoc: JSONContent = {],};+const textSequenceDoc = (...values: string[]): JSONContent => ({+ type: 'doc',+ content: values.map((text) => ({+ type: 'paragraph',+ content: [{ type: 'text', text }],+ })),+});++const recoveredTextDoc = (+ recoveredValues: readonly string[],+ tailValues: readonly string[] = [],+): JSONContent => ({+ type: 'doc',+ content: [+ ...recoveredValues.flatMap((text) => [+ textSequenceDoc(text).content![0],+ { type: 'paragraph' },+ ]),+ ...(tailValues.length > 0+ ? tailValues.map((text) => textSequenceDoc(text).content![0])+ : [{ type: 'paragraph' }]),+ ],+});++const bulletListDoc = (text: string): JSONContent => ({+ type: 'doc',+ content: [+ {+ type: 'bulletList',+ content: [+ {+ type: 'listItem',+ content: [{ type: 'paragraph', content: [{ type: 'text', text }] }],+ },+ ],+ },+ ],+});+/** Minimal attachment — `draftHasContent` only inspects `attachments.length`. */-const fakeAttachment: AttachedFile = {- id: 'att-1',- name: 'pic.png',- path: '/tmp/pic.png',+const attachment = (id: string): AttachedFile => ({+ id,+ name: `${id}.png`,+ path: `/tmp/${id}.png`,ext: '.png',size: 1,category: 'image',mimeType: 'image/png',-};+});+const fakeAttachment = attachment('att-1');++const browserComment = (id: string, markerNumber: number): BrowserCommentDraftItem => ({+ id,+ markerNumber,+ pageUrl: `https://example.com/${id}`,+ target: {+ kind: 'element',+ point: { x: markerNumber, y: markerNumber },+ viewport: { width: 100, height: 100 },+ region: null,+ selectedText: null,+ immediate: false,+ targetTag: 'button',+ targetLabel: id,+ targetRole: 'button',+ targetSelector: `#${id}`,+ targetPath: `html > body > #${id}`,+ nearbyText: id,+ themeVariant: 'light',+ designBaseline: null,+ markerNumber,+ },+ comment: id,+ screenshot: attachment(`${id}-shot`),+});const draft = (over: Partial<ComposerDraft>): ComposerDraft => ({text: null,@@ -127,6 +203,569 @@ describe('owner isolation', () => {clearDraft(key);setComposerDraftOwner(null);});++ it('merges current-owner draft URLs with pending remote attachment URLs', () => {+ const key = 'session-draft-live-media';+ const otherOwnerKey = 'session-other-owner-draft';+ const sharedUrl = 'cindy-media://blobs/shared.png';+ const sharedSourceUrl = 'cindy-media://blobs/shared-source.png';+ const commentUrl = 'cindy-media://blobs/comment.png';+ const commentSourceUrl = 'cindy-media://blobs/comment-source.png';+ const pendingUrl = 'cindy-media://blobs/pending.png';+ const reportDraftUrls = vi.fn();+ const previousWindow = globalThis.window;+ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: {+ electronAPI: {+ cindyMediaStorage: { reportDraftUrls },+ },+ },+ });+ try {+ setComposerDraftOwner('owner-a');+ const comment = browserComment('draft-live-comment', 1);+ comment.screenshot = {+ ...comment.screenshot,+ url: commentUrl,+ annotationSourceUrl: commentSourceUrl,+ };+ saveDraft(+ key,+ draft({+ attachments: [+ {+ ...attachment('draft-live-media'),+ url: sharedUrl,+ annotationSourceUrl: sharedSourceUrl,+ },+ ],+ browserComments: [comment],+ }),+ );+ setRemoteOptimisticAttachmentUrls([pendingUrl, pendingUrl]);++ const expectedUrls = [pendingUrl, sharedUrl, sharedSourceUrl, commentUrl, commentSourceUrl];+ expect(getAllDraftAttachmentUrls().sort()).toEqual(expectedUrls.sort());+ expect(reportDraftUrls).toHaveBeenLastCalledWith(expect.arrayContaining(expectedUrls));++ setComposerDraftOwner('owner-b');+ saveDraft(otherOwnerKey, draft({ text: textDoc }));+ expect(getAllDraftAttachmentUrls().sort()).toEqual(expectedUrls.sort());+ expect(reportDraftUrls).toHaveBeenLastCalledWith(expect.arrayContaining(expectedUrls));+ } finally {+ setRemoteOptimisticAttachmentUrls([]);+ setComposerDraftOwner('owner-b');+ clearDraft(otherOwnerKey);+ setComposerDraftOwner('owner-a');+ clearDraft(key);+ setComposerDraftOwner(null);+ if (previousWindow === undefined) {+ Reflect.deleteProperty(globalThis, 'window');+ } else {+ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: previousWindow,+ });+ }+ }+ });+});++describe('draft discard lifecycle', () => {+ it('invalidates async work only for explicit discard and not an ordinary clear', () => {+ const key = 'session-draft-discard-generation';+ const beforeClear = captureDraftDiscardToken(key);+ clearDraft(key);+ expect(isDraftDiscardTokenCurrent(beforeClear)).toBe(true);++ saveDraft(key, draft({ text: textDoc }));+ const beforeDiscard = captureDraftDiscardToken(key);+ const notifiedDrafts: Array<ComposerDraft | undefined> = [];+ const unsubscribe = subscribeDraft(key, () => notifiedDrafts.push(getDraft(key)));+ discardDraft(key);+ unsubscribe();++ expect(isDraftDiscardTokenCurrent(beforeDiscard)).toBe(false);+ expect(notifiedDrafts).toEqual([{ text: null, attachments: [] }]);+ expect(getDraft(key)).toBeUndefined();+ });+});++describe('remote optimistic draft recovery', () => {+ it('removes a sent prefix while preserving newer composer input', () => {+ const current = {+ text: recoveredTextDoc(['sent'], ['newer']),+ attachments: [attachment('sent-file'), attachment('newer-file')],+ browserComments: [browserComment('sent-comment', 1), browserComment('newer-comment', 2)],+ };+ const next = removeRemoteOptimisticDraftFragment(current, {+ text: textSequenceDoc('sent'),+ attachments: [attachment('sent-file')],+ browserComments: [browserComment('sent-comment', 1)],+ });++ expect(next.text).toEqual(recoveredTextDoc([], ['newer']));+ expect(next.attachments.map((file) => file.id)).toEqual(['newer-file']);+ expect(next.browserComments.map((comment) => comment.id)).toEqual(['newer-comment']);+ });++ it('does not erase text when the user edited the sent prefix', () => {+ const current = {+ text: textSequenceDoc('sent edited'),+ attachments: [attachment('sent-file'), attachment('newer-file')],+ browserComments: [],+ };+ const next = removeRemoteOptimisticDraftFragment(current, {+ text: textSequenceDoc('sent'),+ attachments: [attachment('sent-file')],+ browserComments: [],+ });++ expect(next.text).toEqual(current.text);+ expect(next.attachments.map((file) => file.id)).toEqual(['newer-file']);+ });++ it('keeps an attachment edited in place while the deferred send settles', () => {+ const edited = { ...attachment('sent-file'), name: 'renamed.png', path: '/tmp/renamed.png' };+ const next = removeRemoteOptimisticDraftFragment(+ {+ text: recoveredTextDoc([], ['newer']),+ attachments: [edited, attachment('newer-file')],+ browserComments: [],+ },+ {+ text: textSequenceDoc('sent'),+ attachments: [attachment('sent-file')],+ browserComments: [],+ },+ );++ expect(next.attachments).toEqual([edited, attachment('newer-file')]);+ });++ it('restores text, attachments, and browser comments in FIFO order before newer input', () => {+ const key = 'session-remote-recovery-fifo';+ const attachmentA = attachment('attachment-a');+ const attachmentB = attachment('attachment-b');+ const attachmentC = attachment('attachment-c');+ const commentA = browserComment('comment-a', 1);+ const commentB = browserComment('comment-b', 2);+ const commentC = browserComment('comment-c', 3);+ saveDraft(+ key,+ draft({+ text: textSequenceDoc('C'),+ attachments: [attachmentC],+ browserComments: [commentC],+ }),+ { silent: true },+ );++ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [attachmentA],+ browserComments: [commentA],+ });+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-b',+ text: textSequenceDoc('B'),+ attachments: [attachmentB],+ browserComments: [commentB],+ });++ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['A', 'B'], ['C']));+ expect(getDraft(key)?.attachments.map((file) => file.id)).toEqual([+ 'attachment-a',+ 'attachment-b',+ 'attachment-c',+ ]);+ expect(getDraft(key)?.browserComments?.map((comment) => comment.id)).toEqual([+ 'comment-a',+ 'comment-b',+ 'comment-c',+ ]);+ clearDraft(key);+ });++ it('keeps a data-owner boundary recovery batch cumulative when live state is not updated', () => {+ const key = 'session-remote-recovery-owner-boundary-batch';+ const attachmentA = attachment('attachment-a');+ const attachmentB = attachment('attachment-b');+ const attachmentC = attachment('attachment-c');+ const commentA = browserComment('comment-a', 1);+ const commentB = browserComment('comment-b', 2);+ const commentC = browserComment('comment-c', 3);+ const recoveryBatch = {};+ const staleLiveTail = {+ text: textSequenceDoc('C'),+ attachments: [attachmentC],+ browserComments: [commentC],+ };++ restoreRemoteOptimisticDraft(+ key,+ {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [attachmentA],+ browserComments: [commentA],+ },+ staleLiveTail,+ { recoveryBatch },+ );+ restoreRemoteOptimisticDraft(+ key,+ {+ clientId: 'client-b',+ text: textSequenceDoc('B'),+ attachments: [attachmentB],+ browserComments: [commentB],+ },+ staleLiveTail,+ { recoveryBatch },+ );++ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['A', 'B'], ['C']));+ expect(getDraft(key)?.attachments.map((file) => file.id)).toEqual([+ 'attachment-a',+ 'attachment-b',+ 'attachment-c',+ ]);+ expect(getDraft(key)?.browserComments?.map((comment) => comment.id)).toEqual([+ 'comment-a',+ 'comment-b',+ 'comment-c',+ ]);+ clearDraft(key);+ });++ it('keeps consecutive compatible list fragments in FIFO order', () => {+ const key = 'session-remote-recovery-list-fifo';+ saveDraft(key, draft({ text: bulletListDoc('C') }), { silent: true });++ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-a',+ text: bulletListDoc('A'),+ attachments: [],+ browserComments: [],+ });+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-b',+ text: bulletListDoc('B'),+ attachments: [],+ browserComments: [],+ });++ expect(getDraft(key)?.text?.content).toEqual([+ bulletListDoc('A').content![0],+ { type: 'paragraph' },+ bulletListDoc('B').content![0],+ { type: 'paragraph' },+ bulletListDoc('C').content![0],+ ]);+ clearDraft(key);+ });++ it('keeps each recovery cursor independent when one draft domain changes', () => {+ const key = 'session-remote-recovery-independent-cursors';+ const attachmentA = attachment('attachment-a');+ const attachmentB = attachment('attachment-b');+ const attachmentC = attachment('attachment-c');+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [attachmentA],+ browserComments: [],+ });+ saveDraft(+ key,+ draft({+ text: recoveredTextDoc(['A'], ['C']),+ attachments: [attachmentC],+ }),+ { silent: true },+ );++ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-b',+ text: textSequenceDoc('B'),+ attachments: [attachmentB],+ browserComments: [],+ });++ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['A', 'B'], ['C']));+ expect(getDraft(key)?.attachments.map((file) => file.id)).toEqual([+ 'attachment-b',+ 'attachment-c',+ ]);+ clearDraft(key);+ });++ it('keeps FIFO recovery after incremental quote and browser comment appends', () => {+ const key = 'session-remote-recovery-incremental-appends';+ const commentA = browserComment('comment-a', 1);+ const commentB = browserComment('comment-b', 2);+ const commentC = browserComment('comment-c', 3);+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [],+ browserComments: [commentA],+ });++ appendQuoteToDraft(key, { text: 'C quote' });+ appendBrowserCommentToDraft(key, commentC);+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-b',+ text: textSequenceDoc('B'),+ attachments: [],+ browserComments: [commentB],+ });++ expect(getDraft(key)?.text?.content).toEqual([+ textSequenceDoc('A').content![0],+ { type: 'paragraph' },+ textSequenceDoc('B').content![0],+ { type: 'paragraph' },+ {+ type: 'paragraph',+ content: [+ {+ type: 'composerQuote',+ attrs: {+ text: 'C quote',+ sourcePath: null,+ startLine: null,+ endLine: null,+ },+ },+ ],+ },+ ]);+ expect(getDraft(key)?.browserComments?.map((comment) => comment.id)).toEqual([+ 'comment-a',+ 'comment-b',+ 'comment-c',+ ]);+ clearDraft(key);+ });++ it('preserves recoveries when the same async editor transition reruns while voice settles', () => {+ const key = 'session-remote-recovery-async-transition';+ const attachmentA = attachment('attachment-a');+ const attachmentB = attachment('attachment-b');+ const attachmentC = attachment('attachment-c');+ const commentA = browserComment('comment-a', 1);+ const commentB = browserComment('comment-b', 2);+ const commentC = browserComment('comment-c', 3);+ saveDraft(+ key,+ draft({+ text: textSequenceDoc('C'),+ attachments: [attachmentC],+ browserComments: [commentC],+ }),+ { silent: true },+ );+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [attachmentA],+ browserComments: [commentA],+ });+ const transition = getOrCreateRemoteOptimisticTransitionCheckpoint(null, key);+ const delayedEditorSnapshot = getDraft(key)?.text ?? null;++ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-b',+ text: textSequenceDoc('B'),+ attachments: [attachmentB],+ browserComments: [commentB],+ });+ const repeatedTransition = getOrCreateRemoteOptimisticTransitionCheckpoint(transition, key);+ expect(repeatedTransition).toBe(transition);+ saveComposerTextAfterAsyncTransition(key, delayedEditorSnapshot, repeatedTransition.checkpoint);++ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['A', 'B'], ['C']));+ expect(getDraft(key)?.attachments.map((file) => file.id)).toEqual([+ 'attachment-a',+ 'attachment-b',+ 'attachment-c',+ ]);+ expect(getDraft(key)?.browserComments?.map((comment) => comment.id)).toEqual([+ 'comment-a',+ 'comment-b',+ 'comment-c',+ ]);+ clearDraft(key);+ });++ it('ignores a duplicate clientId', () => {+ const key = 'session-remote-recovery-idempotent';+ const fragment = {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [attachment('attachment-a')],+ browserComments: [browserComment('comment-a', 1)],+ };++ restoreRemoteOptimisticDraft(key, fragment);+ restoreRemoteOptimisticDraft(key, fragment);++ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['A']));+ expect(getDraft(key)?.attachments.map((file) => file.id)).toEqual(['attachment-a']);+ expect(getDraft(key)?.browserComments?.map((comment) => comment.id)).toEqual(['comment-a']);+ clearDraft(key);+ });++ it('keeps the recovery cursor when the user adds newer input between failures', () => {+ const key = 'session-remote-recovery-live-input';+ const attachmentA = attachment('attachment-a');+ const attachmentB = attachment('attachment-b');+ const attachmentC = attachment('attachment-c');+ const commentA = browserComment('comment-a', 1);+ const commentB = browserComment('comment-b', 2);+ const commentC = browserComment('comment-c', 3);++ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [attachmentA],+ browserComments: [commentA],+ });+ saveDraft(+ key,+ draft({+ text: recoveredTextDoc(['A'], ['C']),+ attachments: [attachmentA, attachmentC],+ browserComments: [commentA, commentC],+ }),+ { silent: true },+ );+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-b',+ text: textSequenceDoc('B'),+ attachments: [attachmentB],+ browserComments: [commentB],+ });++ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['A', 'B'], ['C']));+ expect(getDraft(key)?.attachments.map((file) => file.id)).toEqual([+ 'attachment-a',+ 'attachment-b',+ 'attachment-c',+ ]);+ expect(getDraft(key)?.browserComments?.map((comment) => comment.id)).toEqual([+ 'comment-a',+ 'comment-b',+ 'comment-c',+ ]);+ clearDraft(key);+ });++ it('treats an explicit empty live override as authoritative over a stale saved draft', () => {+ const key = 'session-remote-recovery-live-empty';+ saveDraft(key, draft({ text: textSequenceDoc('stale') }), { silent: true });++ restoreRemoteOptimisticDraft(+ key,+ {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [],+ browserComments: [],+ },+ { text: null, attachments: [], browserComments: [] },+ );++ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['A']));+ clearDraft(key);+ });++ it('resets recovery cursors after clear or an external draft replacement', () => {+ const key = 'session-remote-recovery-reset';+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [attachment('attachment-a')],+ browserComments: [browserComment('comment-a', 1)],+ });+ clearDraft(key);+ saveDraft(key, draft({ text: textSequenceDoc('C') }), { silent: true });+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-b',+ text: textSequenceDoc('B'),+ attachments: [],+ browserComments: [],+ });+ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['B'], ['C']));++ saveDraft(key, draft({ text: textSequenceDoc('replacement') }));+ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-c',+ text: textSequenceDoc('C'),+ attachments: [],+ browserComments: [],+ });+ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['C'], ['replacement']));+ clearDraft(key);+ });++ it('isolates recovery state by owner and storage key', () => {+ const sharedKey = 'session-remote-recovery-owner';+ setComposerDraftOwner('owner-a');+ restoreRemoteOptimisticDraft(sharedKey, {+ clientId: 'client-a',+ text: textSequenceDoc('owner-a'),+ attachments: [],+ browserComments: [],+ });+ restoreRemoteOptimisticDraft(`${sharedKey}-other`, {+ clientId: 'client-other',+ text: textSequenceDoc('other-key'),+ attachments: [],+ browserComments: [],+ });++ setComposerDraftOwner('owner-b');+ expect(getDraft(sharedKey)).toBeUndefined();+ restoreRemoteOptimisticDraft(sharedKey, {+ clientId: 'client-b',+ text: textSequenceDoc('owner-b'),+ attachments: [],+ browserComments: [],+ });+ expect(getDraft(sharedKey)?.text).toEqual(recoveredTextDoc(['owner-b']));++ setComposerDraftOwner('owner-a');+ expect(getDraft(sharedKey)?.text).toEqual(recoveredTextDoc(['owner-a']));+ expect(getDraft(`${sharedKey}-other`)?.text).toEqual(recoveredTextDoc(['other-key']));+ clearDraft(sharedKey);+ clearDraft(`${sharedKey}-other`);+ setComposerDraftOwner('owner-b');+ clearDraft(sharedKey);+ setComposerDraftOwner(null);+ });++ it('notifies a newly mounted owner when recovery happens without a live override', () => {+ const key = 'session-remote-recovery-background-notify';+ const listener = vi.fn();+ const unsubscribe = subscribeDraft(key, listener);++ restoreRemoteOptimisticDraft(key, {+ clientId: 'client-a',+ text: textSequenceDoc('A'),+ attachments: [],+ browserComments: [],+ });++ expect(listener).toHaveBeenCalledTimes(1);+ expect(getDraft(key)?.text).toEqual(recoveredTextDoc(['A']));+ unsubscribe();+ clearDraft(key);+ });});describe('appendQuoteToDraft', () => {@@ -345,9 +984,7 @@ describe('quickStartTextToTiptapDoc', () => {walk(doc);expect(textNodes.length).toBeGreaterThanOrEqual(2);for (const tn of textNodes) {- expect(tn.marks).toEqual(- expect.arrayContaining([{ type: 'quickStartPill' }]),- );+ expect(tn.marks).toEqual(expect.arrayContaining([{ type: 'quickStartPill' }]));}});});diff --git a/apps/desktop/src/renderer/lib/authService.ts b/apps/desktop/src/renderer/lib/authService.tsindex 405108f595..dbc2c0bf05 100644--- a/apps/desktop/src/renderer/lib/authService.ts+++ b/apps/desktop/src/renderer/lib/authService.ts@@ -36,6 +36,7 @@ export interface AuthState {user: User | null;mode: 'signed-out' | 'local' | 'cloud';dataOwnerId: string | null;+ ownerGeneration: number;canEnterApp: boolean;isAuthenticated: boolean;isCanary: boolean;@@ -69,6 +70,7 @@ export function createAuthService(): AuthService {user: rawState.user as User | null,mode: rawState.mode,dataOwnerId: rawState.dataOwnerId,+ ownerGeneration: rawState.ownerGeneration,canEnterApp: rawState.canEnterApp,isAuthenticated: rawState.isAuthenticated,isCanary: rawState.isCanary === true,@@ -86,6 +88,7 @@ export function createAuthService(): AuthService {user: raw.user as User | null,mode: raw.mode,dataOwnerId: raw.dataOwnerId,+ ownerGeneration: raw.ownerGeneration,canEnterApp: raw.canEnterApp,isAuthenticated: raw.isAuthenticated,isCanary: raw.isCanary === true,diff --git a/apps/desktop/src/renderer/lib/autoPermissionFallbackToast.ts b/apps/desktop/src/renderer/lib/autoPermissionFallbackToast.tsindex 094bcac109..a107adfddc 100644--- a/apps/desktop/src/renderer/lib/autoPermissionFallbackToast.ts+++ b/apps/desktop/src/renderer/lib/autoPermissionFallbackToast.ts@@ -6,6 +6,7 @@*/import { i18n } from '@/i18n';+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { toast } from './toast';@@ -37,7 +38,8 @@ export function handleAutoPermissionFallback(): void {/** 同时订阅本机与被控端 push;返回统一 unsubscribe。 */export function installAutoPermissionFallbackToastListener(): () => void {const offLocal = window.electronAPI.maker.onAutoPermissionFallback(handleAutoPermissionFallback);- const offRemote = window.electronAPI.deviceLink?.onRemotePush?.((push) => {+ const offRemote = window.electronAPI.deviceLink?.onRemotePush?.((push, localOwnerStamp) => {+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;if (push.channel === 'maker:auto-permission:fallback' &&isAutoPermissionFallbackPayload(push.payload)diff --git a/apps/desktop/src/renderer/lib/composerDraftStore.ts b/apps/desktop/src/renderer/lib/composerDraftStore.tsindex 0f8d17980c..8116797382 100644--- a/apps/desktop/src/renderer/lib/composerDraftStore.ts+++ b/apps/desktop/src/renderer/lib/composerDraftStore.ts@@ -41,7 +41,11 @@ import {import type { JSONContent } from '@tiptap/core';import { createLogger } from '@/lib/logger';import { cleanupStagedChatAttachmentFiles } from './chatAttachmentStageCleanup';-import { plainTextToComposerDocument } from './composerListDocument';+import {+ insertComposerDocumentForRestore,+ normalizeComposerDocumentJSON,+ plainTextToComposerDocument,+} from './composerListDocument';const log = createLogger('ComposerDraftStore');@@ -71,7 +75,145 @@ export interface ComposerDraft {browserComments?: BrowserCommentDraftItem[];}+export interface RemoteOptimisticDraftFragment {+ clientId: string;+ text: JSONContent | null;+ attachments: readonly AttachedFile[];+ browserComments: readonly BrowserCommentDraftItem[];+}++export interface RemoteOptimisticDraftSnapshot {+ text: JSONContent | null;+ attachments: readonly AttachedFile[];+ browserComments: readonly BrowserCommentDraftItem[];+}++/**+ * Process-local discard boundary captured by async composer work. A successful+ * send uses `clearDraft` and deliberately does not invalidate this token:+ * files added while the send is settling are newer composer input. Explicit+ * discard (session delete/archive) advances the generation so late work can+ * recycle its files instead of resurrecting the removed draft.+ */+export interface ComposerDraftDiscardToken {+ ownerScopedKey: string;+ generation: number;+}++const ATTACHED_FILE_SNAPSHOT_KEYS = [+ 'id',+ 'name',+ 'path',+ 'ext',+ 'size',+ 'category',+ 'mimeType',+ 'url',+ 'originalName',+ 'base64',+ 'textContent',+ 'truncated',+ 'annotated',+ 'annotationSourceUrl',+ 'cacheUrlShared',+] as const;++/**+ * An attachment id is stable across edits (especially annotation edits), so+ * id-only cleanup can delete a newer file that happens to reuse the id. Keep+ * every mutable serialized field in the click-time snapshot comparison.+ */+function areAttachedFileSnapshotsEqual(left: AttachedFile, right: AttachedFile): boolean {+ return (+ ATTACHED_FILE_SNAPSHOT_KEYS.every((key) => left[key] === right[key]) &&+ JSON.stringify(left.annotationStrokes ?? null) ===+ JSON.stringify(right.annotationStrokes ?? null)+ );+}++/**+ * Remove one click-time optimistic fragment while retaining newer composer+ * input. Text is removed only when the fragment is still an exact document+ * prefix; if the user edited that prefix, keeping it is safer than erasing+ * their edit. Attachments and comments use their stable ids independently.+ */+export function removeRemoteOptimisticDraftFragment(+ current: RemoteOptimisticDraftSnapshot,+ fragment: RemoteOptimisticDraftSnapshot,+): RemoteOptimisticDraftSnapshot {+ const currentDocument = current.text+ ? normalizeComposerDocumentJSON(current.text)+ : { type: 'doc' as const, content: [] };+ const fragmentDocument = fragment.text+ ? normalizeComposerDocumentJSON(fragment.text)+ : { type: 'doc' as const, content: [] };+ const currentBlocks = currentDocument.content ?? [];+ const fragmentBlocks = fragmentDocument.content ?? [];+ const prefixMatches =+ fragmentBlocks.length > 0 &&+ fragmentBlocks.length <= currentBlocks.length &&+ fragmentBlocks.every(+ (block, index) => JSON.stringify(currentBlocks[index]) === JSON.stringify(block),+ );+ const nextText = prefixMatches+ ? (() => {+ const remaining = currentBlocks.slice(fragmentBlocks.length);+ // Recovery insertion places an empty paragraph between an older+ // fragment and newer content. Remove that separator with the fragment+ // so accepting the deferred send does not leave a blank line behind.+ if (+ remaining.length > 1 &&+ remaining[0]?.type === 'paragraph' &&+ !tiptapDocHasContent(remaining[0])+ ) {+ remaining.shift();+ }+ return {+ type: 'doc' as const,+ content: remaining.length > 0 ? remaining : [{ type: 'paragraph' as const }],+ };+ })()+ : current.text;+ const fragmentAttachmentsById = new Map(fragment.attachments.map((file) => [file.id, file]));+ const fragmentCommentIds = new Set(fragment.browserComments.map((comment) => comment.id));+ return {+ text: nextText,+ attachments: current.attachments.filter((file) => {+ const fragmentFile = fragmentAttachmentsById.get(file.id);+ return !fragmentFile || !areAttachedFileSnapshotsEqual(file, fragmentFile);+ }),+ browserComments: current.browserComments.filter(+ (comment) => !fragmentCommentIds.has(comment.id),+ ),+ };+}++export interface RemoteOptimisticRecoveryCheckpoint {+ revision: number;+ textPrefix: readonly JSONContent[];+}++export interface RemoteOptimisticTransitionCheckpoint {+ storageKey: string;+ checkpoint: RemoteOptimisticRecoveryCheckpoint;+}++interface RemoteOptimisticRecoveryState {+ revision: number;+ seenClientIds: Set<string>;+ textPrefix: JSONContent[];+ attachmentPrefixIds: string[];+ commentPrefixIds: string[];+}+const drafts = new Map<string, ComposerDraft>();+const draftDiscardGenerations = new Map<string, number>();+const remoteOptimisticRecoveries = new Map<string, RemoteOptimisticRecoveryState>();+const remoteOptimisticRecoveryBatchSnapshots = new WeakMap<+ object,+ Map<string, RemoteOptimisticDraftSnapshot>+>();+let remoteOptimisticAttachmentUrls: string[] = [];let activeDataOwnerId: string | null = null;/**@@ -141,7 +283,8 @@ export function tiptapDocHasContent(node: JSONContent | null | undefined): boolenode.type === 'mentionChip' ||node.type === 'pastedTextChip' ||node.type === COMPOSER_QUOTE_NODE_TYPE- ) return true;+ )+ return true;if (node.type === 'bulletList' || node.type === 'orderedList') return true;if (typeof node.text === 'string' && node.text.trim().length > 0) return true;if (Array.isArray(node.content)) {@@ -176,11 +319,14 @@ function recomputeDraftPresence(sessionId: string): void {if (next) presenceCache.set(key, true);else presenceCache.delete(key);const set = presenceListeners.get(key);- if (set) for (const fn of set) {- try { fn(); } catch (err) {- log.warn('presence listener threw:', err);+ if (set)+ for (const fn of set) {+ try {+ fn();+ } catch (err) {+ log.warn('presence listener threw:', err);+ }}- }}/**@@ -192,6 +338,20 @@ export function getDraft(sessionId: string): ComposerDraft | undefined {return drafts.get(draftKey(sessionId));}+/** Capture the current process-local discard generation for async draft work. */+export function captureDraftDiscardToken(sessionId: string): ComposerDraftDiscardToken {+ const ownerScopedKey = draftKey(sessionId);+ return {+ ownerScopedKey,+ generation: draftDiscardGenerations.get(ownerScopedKey) ?? 0,+ };+}++/** Whether a captured draft scope has not been explicitly discarded. */+export function isDraftDiscardTokenCurrent(token: ComposerDraftDiscardToken): boolean {+ return (draftDiscardGenerations.get(token.ownerScopedKey) ?? 0) === token.generation;+}+/*** Whether `sessionId` currently has a non-empty draft (text or attachments).* Computed fresh on each call so it never drifts from the Map — cheap because@@ -208,10 +368,7 @@ export function getDraftPresence(sessionId: string): boolean {* The sidebar's SessionItem uses this (via `useComposerDraftPresence`) to show* / hide its unsent-draft indicator.*/-export function subscribeDraftPresence(- sessionId: string,- handler: DraftListener,-): () => void {+export function subscribeDraftPresence(sessionId: string, handler: DraftListener): () => void {const key = draftKey(sessionId);let set = presenceListeners.get(key);if (!set) {@@ -241,9 +398,12 @@ export function subscribeDraftPresence(export function saveDraft(sessionId: string,draft: ComposerDraft,- opts?: { silent?: boolean },+ opts?: { silent?: boolean; preserveRemoteOptimisticRecovery?: boolean },): void {const key = draftKey(sessionId);+ if (!opts?.silent && !opts?.preserveRemoteOptimisticRecovery) {+ remoteOptimisticRecoveries.delete(key);+ }const withQuotes =draft.quotes && draft.quotes.length > 0? {@@ -255,11 +415,14 @@ export function saveDraft(drafts.set(key, withQuotes);if (!opts?.silent) {const set = listeners.get(key);- if (set) for (const fn of set) {- try { fn(); } catch (err) {- log.warn('listener threw:', err);+ if (set)+ for (const fn of set) {+ try {+ fn();+ } catch (err) {+ log.warn('listener threw:', err);+ }}- }}// Presence notify is independent of `silent` — the sidebar must learn about// keystroke saves (which are silent) too.@@ -275,7 +438,9 @@ export function saveDraft(* - When a session is deleted or archived (avoid Map leak).*/export function clearDraft(sessionId: string): void {- drafts.delete(draftKey(sessionId));+ const key = draftKey(sessionId);+ drafts.delete(key);+ remoteOptimisticRecoveries.delete(key);recomputeDraftPresence(sessionId);syncDraftUrlsToMain();}@@ -287,9 +452,15 @@ export function clearDraft(sessionId: string): void {* the attachment paths.*/export function discardDraft(sessionId: string): void {- const draft = drafts.get(draftKey(sessionId));+ const key = draftKey(sessionId);+ const draft = drafts.get(key);if (draft) cleanupStagedChatAttachmentFiles(draft.attachments);- clearDraft(sessionId);+ draftDiscardGenerations.set(key, (draftDiscardGenerations.get(key) ?? 0) + 1);+ // Empty mounted editors/attachment trays before deleting the Map entry. This+ // mirrors a Mobile attachment controller dispose: unmount snapshots cannot+ // recreate the discarded draft, while late async files are fenced by the+ // generation above and recycled by their owner.+ clearDraftAndNotify(sessionId);}/**@@ -317,33 +488,269 @@ export function clearDraftAndNotify(sessionId: string): void {// `getDraft` (must be present) and, seeing falsy text, clears its editor.drafts.set(key, { text: null, attachments: [] });for (const fn of set) {- try { fn(); } catch (err) {+ try {+ fn();+ } catch (err) {log.warn('clearDraftAndNotify listener threw:', err);}}}drafts.delete(key);+ remoteOptimisticRecoveries.delete(key);recomputeDraftPresence(sessionId);syncDraftUrlsToMain();}+function normalizedDraftBlocks(document: JSONContent | null | undefined): JSONContent[] {+ if (!tiptapDocHasContent(document)) return [];+ const normalized = normalizeComposerDocumentJSON(document!);+ return normalized.type === 'doc' && Array.isArray(normalized.content) ? normalized.content : [];+}++function startsWithJsonBlocks(current: readonly JSONContent[], prefix: readonly JSONContent[]) {+ if (prefix.length > current.length) return false;+ return prefix.every((block, index) => JSON.stringify(current[index]) === JSON.stringify(block));+}++function startsWithIds(current: readonly string[], prefix: readonly string[]): boolean {+ if (prefix.length > current.length) return false;+ return prefix.every((id, index) => current[index] === id);+}++/** Snapshot the recovery prefix before an async editor/session transition. */+export function captureRemoteOptimisticRecoveryCheckpoint(+ sessionId: string,+): RemoteOptimisticRecoveryCheckpoint {+ const recovery = remoteOptimisticRecoveries.get(draftKey(sessionId));+ return {+ revision: recovery?.revision ?? 0,+ textPrefix: [...(recovery?.textPrefix ?? [])],+ };+}++/** Keep the first recovery snapshot while an editor still belongs to the same draft key. */+export function getOrCreateRemoteOptimisticTransitionCheckpoint(+ current: RemoteOptimisticTransitionCheckpoint | null,+ storageKey: string,+): RemoteOptimisticTransitionCheckpoint {+ if (current?.storageKey === storageKey) return current;+ return {+ storageKey,+ checkpoint: captureRemoteOptimisticRecoveryCheckpoint(storageKey),+ };+}++/**+ * Save an editor snapshot taken across an async transition (voice stop/refine).+ * If a remote failure restored text while the transition was waiting, retain+ * the latest recovered prefix and treat the old editor snapshot as its tail.+ */+export function saveComposerTextAfterAsyncTransition(+ sessionId: string,+ liveText: JSONContent | null,+ checkpoint: RemoteOptimisticRecoveryCheckpoint,+): void {+ const key = draftKey(sessionId);+ const recovery = remoteOptimisticRecoveries.get(key);+ let text = liveText;+ if (recovery && recovery.revision !== checkpoint.revision) {+ const liveBlocks = normalizedDraftBlocks(liveText);+ if (startsWithJsonBlocks(liveBlocks, recovery.textPrefix)) {+ text = {+ type: 'doc',+ content:+ liveBlocks.length > recovery.textPrefix.length+ ? liveBlocks+ : [...liveBlocks, { type: 'paragraph' }],+ };+ } else {+ const liveTail = startsWithJsonBlocks(liveBlocks, checkpoint.textPrefix)+ ? liveBlocks.slice(checkpoint.textPrefix.length)+ : liveBlocks;+ text = {+ type: 'doc',+ content: [+ ...recovery.textPrefix,+ ...(liveTail.length > 0 ? liveTail : [{ type: 'paragraph' }]),+ ],+ };+ }+ }++ const existing = drafts.get(key);+ saveDraft(+ sessionId,+ {+ text,+ attachments: existing?.attachments ?? [],+ quotes: existing?.quotes ?? [],+ browserComments: existing?.browserComments ?? [],+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),+ },+ { silent: true, preserveRemoteOptimisticRecovery: true },+ );+}++/**+ * Restore a permanently failed remote optimistic send at the end of the+ * already-restored prefix for this composer key. The cursor lives beside the+ * in-memory draft, so failures that settle across reconnects remain FIFO while+ * text/files/comments added during the wait stay after that prefix.+ */+export function restoreRemoteOptimisticDraft(+ sessionId: string,+ fragment: RemoteOptimisticDraftFragment,+ currentOverride?: RemoteOptimisticDraftSnapshot,+ opts?: { recoveryBatch?: object },+): ComposerDraft {+ const key = draftKey(sessionId);+ const existing = drafts.get(key);+ let batchSnapshots: Map<string, RemoteOptimisticDraftSnapshot> | undefined;+ if (opts?.recoveryBatch) {+ batchSnapshots = remoteOptimisticRecoveryBatchSnapshots.get(opts.recoveryBatch);+ if (!batchSnapshots) {+ batchSnapshots = new Map<string, RemoteOptimisticDraftSnapshot>();+ remoteOptimisticRecoveryBatchSnapshots.set(opts.recoveryBatch, batchSnapshots);+ }+ }+ const effectiveOverride = batchSnapshots?.get(key) ?? currentOverride;+ const currentText = effectiveOverride+ ? effectiveOverride.text+ : prependLegacyQuotesToComposerDocument(existing?.text ?? null, existing?.quotes ?? []);+ const currentAttachments = [...(effectiveOverride?.attachments ?? existing?.attachments ?? [])];+ const currentComments = [+ ...(effectiveOverride?.browserComments ?? existing?.browserComments ?? []),+ ];+ const baseDraft: ComposerDraft = {+ text: currentText,+ attachments: currentAttachments,+ quotes: [],+ browserComments: currentComments,+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),+ };+ const rememberBatchSnapshot = (draft: ComposerDraft): void => {+ batchSnapshots?.set(key, {+ text: draft.text,+ attachments: draft.attachments,+ browserComments: draft.browserComments ?? [],+ });+ };++ let recovery = remoteOptimisticRecoveries.get(key);+ if (!recovery) {+ recovery = {+ revision: 0,+ seenClientIds: new Set<string>(),+ textPrefix: [],+ attachmentPrefixIds: [],+ commentPrefixIds: [],+ };+ remoteOptimisticRecoveries.set(key, recovery);+ }+ if (recovery.seenClientIds.has(fragment.clientId)) {+ rememberBatchSnapshot(baseDraft);+ return baseDraft;+ }++ const currentBlocks = normalizedDraftBlocks(currentText);+ const attachmentIds = currentAttachments.map((file) => file.id);+ const commentIds = currentComments.map((comment) => comment.id);+ if (!startsWithJsonBlocks(currentBlocks, recovery.textPrefix)) recovery.textPrefix = [];+ if (!startsWithIds(attachmentIds, recovery.attachmentPrefixIds)) {+ recovery.attachmentPrefixIds = [];+ }+ if (!startsWithIds(commentIds, recovery.commentPrefixIds)) recovery.commentPrefixIds = [];++ let restoredText = currentText;+ if (tiptapDocHasContent(fragment.text)) {+ const insertion = insertComposerDocumentForRestore(+ fragment.text!,+ currentText ?? { type: 'doc', content: [] },+ recovery.textPrefix.length,+ );+ restoredText = insertion.document;+ recovery.textPrefix.push(...insertion.insertedBlocks);+ }++ const restoredAttachments = [...currentAttachments];+ const attachmentIdSet = new Set(restoredAttachments.map((file) => file.id));+ const insertedAttachments = fragment.attachments.filter((file) => {+ if (attachmentIdSet.has(file.id)) return false;+ attachmentIdSet.add(file.id);+ return true;+ });+ restoredAttachments.splice(recovery.attachmentPrefixIds.length, 0, ...insertedAttachments);+ recovery.attachmentPrefixIds.push(...insertedAttachments.map((file) => file.id));++ const restoredComments = [...currentComments];+ const commentIdSet = new Set(restoredComments.map((comment) => comment.id));+ const insertedComments = fragment.browserComments.filter((comment) => {+ if (commentIdSet.has(comment.id)) return false;+ commentIdSet.add(comment.id);+ return true;+ });+ restoredComments.splice(recovery.commentPrefixIds.length, 0, ...insertedComments);+ recovery.commentPrefixIds.push(...insertedComments.map((comment) => comment.id));+ recovery.seenClientIds.add(fragment.clientId);+ recovery.revision += 1;++ const restored: ComposerDraft = {+ ...baseDraft,+ text: restoredText,+ attachments: restoredAttachments,+ browserComments: restoredComments,+ };+ rememberBatchSnapshot(restored);+ saveDraft(sessionId, restored, {+ // A live caller applies the returned snapshot itself to preserve its focus+ // and selection. A background recovery must notify any mounted view that+ // now owns this key, while keeping the FIFO cursor for later failures.+ silent: effectiveOverride !== undefined,+ preserveRemoteOptimisticRecovery: true,+ });+ return restored;+}+/*** 媒体回收器活引用取证(recycler.ts 的输入框草稿暂存区):全部会话草稿附件的- * URL。草稿附件是合法的零引用 blob(粘贴=草稿、发送才挂引用),而本 Map 是- * renderer 内存、main 读不到——存储清理由设置页发起时把这份清单随 IPC 带给- * main,回收器把它们当活引用豁免。宁可多报(混着老 xdt-image 地址也没关系,- * main 侧只抽 cindy-media 指纹)。+ * URL。草稿附件和尚未受理的远程乐观发送都是合法的零引用 blob,而这些状态+ * 只在 renderer 内存,main 读不到——存储清理由设置页发起时把这份清单随 IPC+ * 带给 main,回收器把它们当活引用豁免。宁可多报(混着老 xdt-image 地址也+ * 没关系,main 侧只抽 cindy-media 指纹)。*/export function getAllDraftAttachmentUrls(): string[] {- const urls: string[] = [];- const prefix = ownerPrefix();- for (const [key, draft] of drafts) {- if (!key.startsWith(prefix)) continue;+ const urls = new Set<string>(remoteOptimisticAttachmentUrls);+ // Owner switches retain each owner's draft so switching back can restore it.+ // Protect every retained namespace as well; reporting only the active owner+ // would leave an old owner's still-restorable attachment eligible for sweep.+ for (const draft of drafts.values()) {for (const att of draft.attachments) {- if (att.url) urls.push(att.url);+ if (att.url) urls.add(att.url);+ if (att.annotationSourceUrl) urls.add(att.annotationSourceUrl);+ }+ for (const comment of draft.browserComments ?? []) {+ if (comment.screenshot.url) urls.add(comment.screenshot.url);+ if (comment.screenshot.annotationSourceUrl) {+ urls.add(comment.screenshot.annotationSourceUrl);+ }}}- return urls;+ return [...urls];+}++/** Keep media referenced by a not-yet-accepted remote outbox item live. */+export function setRemoteOptimisticAttachmentUrls(urls: readonly string[]): void {+ const next = [...new Set(urls)].sort();+ if (+ next.length === remoteOptimisticAttachmentUrls.length &&+ next.every((url, index) => url === remoteOptimisticAttachmentUrls[index])+ ) {+ return;+ }+ remoteOptimisticAttachmentUrls = next;+ syncDraftUrlsToMain();}/**@@ -375,13 +782,17 @@ export function appendQuoteToDraft(sessionId: string, quote: ChatQuote): void {existing?.text,existing?.quotes ?? [],);- saveDraft(sessionId, {- ...existing,- text: appendQuoteToComposerDocument(currentDocument, quote),- attachments: existing?.attachments ?? [],- quotes: [],- browserComments: existing?.browserComments ?? [],- });+ saveDraft(+ sessionId,+ {+ ...existing,+ text: appendQuoteToComposerDocument(currentDocument, quote),+ attachments: existing?.attachments ?? [],+ quotes: [],+ browserComments: existing?.browserComments ?? [],+ },+ { preserveRemoteOptimisticRecovery: true },+ );}/**@@ -394,12 +805,16 @@ export function appendBrowserCommentToDraft(item: BrowserCommentDraftItem,): void {const existing = getDraft(sessionId);- saveDraft(sessionId, {- text: existing?.text ?? null,- attachments: existing?.attachments ?? [],- quotes: existing?.quotes ?? [],- browserComments: [...(existing?.browserComments ?? []), item],- });+ saveDraft(+ sessionId,+ {+ text: existing?.text ?? null,+ attachments: existing?.attachments ?? [],+ quotes: existing?.quotes ?? [],+ browserComments: [...(existing?.browserComments ?? []), item],+ },+ { preserveRemoteOptimisticRecovery: true },+ );}/**@@ -449,10 +864,7 @@ export function quickStartTextToTiptapDoc(text: string): JSONContent {* ChatInput uses this to force-setContent when an outside writer (rewind /* fork pre-fill) updates the draft for the currently-mounted session.*/-export function subscribeDraft(- sessionId: string,- handler: DraftListener,-): () => void {+export function subscribeDraft(sessionId: string, handler: DraftListener): () => void {const key = draftKey(sessionId);let set = listeners.get(key);if (!set) {diff --git a/apps/desktop/src/renderer/lib/composerListDocument.ts b/apps/desktop/src/renderer/lib/composerListDocument.tsindex 9159c03876..45d6be295c 100644--- a/apps/desktop/src/renderer/lib/composerListDocument.ts+++ b/apps/desktop/src/renderer/lib/composerListDocument.ts@@ -87,8 +87,7 @@ function parseListMarker(text: string): ListMarker | null {// CJK ordered markers are valid with or without a following space.// Keep that space in the item body so serialization preserves the// user's original form without adding another list attribute.- prefixLength:- marker === '、' ? ordered[1].length + marker.length : ordered[0].length,+ prefixLength: marker === '、' ? ordered[1].length + marker.length : ordered[0].length,marker,separator: marker === '、' ? '' : ordered[3],start: Number(ordered[1]),@@ -146,9 +145,7 @@ function listFromLines(function sameListMarker(left: ListMarker, right: ListMarker): boolean {return (- left.kind === right.kind &&- left.marker === right.marker &&- left.separator === right.separator+ left.kind === right.kind && left.marker === right.marker && left.separator === right.separator);}@@ -296,9 +293,7 @@ export function normalizeComposerDocumentJSON(document: JSONContent): JSONContenlet fence: FenceState | null = null;for (const node of document.content) {const result: { blocks: JSONContent[]; fence: FenceState | null } =- node.type === 'paragraph'- ? paragraphToBlocks(node, fence)- : { blocks: [node], fence };+ node.type === 'paragraph' ? paragraphToBlocks(node, fence) : { blocks: [node], fence };fence = result.fence;for (const block of result.blocks) {const previous = normalized.at(-1);@@ -312,6 +307,58 @@ export function normalizeComposerDocumentJSON(document: JSONContent): JSONContenreturn { ...document, content: normalized };}+export interface ComposerRestoreInsertion {+ document: JSONContent;+ insertedBlocks: JSONContent[];+ nextInsertAt: number;+}++function emptyComposerParagraph(): JSONContent {+ return { type: 'paragraph' };+}++/**+ * Insert one failed optimistic send at a stable top-level block cursor.+ *+ * Each failed document contributes a trailing empty paragraph. It is the+ * structural equivalent of Mobile's `\n\n` recovery separator and prevents a+ * later editor hydration/normalization pass from merging compatible lists+ * across FIFO message boundaries. When there is no newer draft, keep one extra+ * empty tail paragraph so the user can type without mutating that separator.+ */+export function insertComposerDocumentForRestore(+ failedSendDocument: JSONContent,+ currentDraftDocument: JSONContent,+ insertAt = 0,+): ComposerRestoreInsertion {+ const normalizedFailed = normalizeComposerDocumentJSON(failedSendDocument);+ const normalizedCurrent = normalizeComposerDocumentJSON(currentDraftDocument);+ const insertedBlocks =+ normalizedFailed.type === 'doc' && Array.isArray(normalizedFailed.content)+ ? [...normalizedFailed.content, emptyComposerParagraph()]+ : [];+ const normalizedCurrentBlocks =+ normalizedCurrent.type === 'doc' && Array.isArray(normalizedCurrent.content)+ ? normalizedCurrent.content+ : [];+ const currentBlocks =+ normalizedCurrentBlocks.length > 0 ? normalizedCurrentBlocks : [emptyComposerParagraph()];+ const boundedInsertAt = Math.max(0, Math.min(insertAt, currentBlocks.length));++ return {+ document: {+ type: 'doc',+ content: [+ ...currentBlocks.slice(0, boundedInsertAt),+ ...insertedBlocks,+ ...currentBlocks.slice(boundedInsertAt),+ ],+ },+ insertedBlocks,+ nextInsertAt: boundedInsertAt + insertedBlocks.length,+ };+}+/** Build a normalized composer document from plain clipboard/history text. */export function plainTextToComposerDocument(text: string): JSONContent {const content = textdiff --git a/apps/desktop/src/renderer/lib/fileBrowserTransport.ts b/apps/desktop/src/renderer/lib/fileBrowserTransport.tsindex 4aaf941b19..b0d2158d4c 100644--- a/apps/desktop/src/renderer/lib/fileBrowserTransport.ts+++ b/apps/desktop/src/renderer/lib/fileBrowserTransport.ts@@ -18,6 +18,7 @@*/import { createLogger } from '@/lib/logger';+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { gzipTextToBase64, gunzipBase64ToText } from './gzipBase64';@@ -230,9 +231,10 @@ export function onFileTreeEventFor(cb: (event: FileTreeEventPayload) => void,): () => void {if (!deviceId) return window.electronAPI.fileBrowser.onEvent(cb);- return window.electronAPI.deviceLink.onRemotePush((push) => {+ return window.electronAPI.deviceLink.onRemotePush((push, localOwnerStamp) => {if (push.deviceId !== deviceId) return;if (push.channel !== FILE_BROWSER_EVENT_CHANNEL) return;+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;cb(push.payload as FileTreeEventPayload);});}diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 495574b417..402377c992 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -22,8 +22,20 @@*/import type { CindyRegion } from '@cindy/maker-shared/brand-identity';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+ isDataOwnerPushStampCurrent,+ type DataOwnerGeneration,+} from '@/contexts/dataOwnerGeneration';+import { isDataOwnerPushStamp } from '../../shared/dataOwnerPush';import { dbToMakerAgentKind } from '../../shared/agentKindConversion';import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';+import {+ formatRemoteError,+ isDeviceUnresponsiveRemoteError,+ isTransientRemoteError,+} from '@cindy/maker-shared/device-link-contract';import {applyCodexPlanSnapshotOnDone,getLatestMessageTodoState,@@ -43,10 +55,10 @@ import type {AgentInputSessionRef,AgentInputReference,} from '../../shared/agentInputQueue';+import { normalizeAgentInputClearBoundaryMs } from '../../shared/agentInputQueue';import { hasUserVisibleText } from '../../shared/visibleText';import {deriveAutoTitleSeed,- getAgentFacingText,reconcileSessionRefsForText,type AutoTitleFallbackLabels,type AutoTitleSeed,@@ -74,8 +86,10 @@ import {listMessagesFor,aroundMessagesFor,aroundMessagesByClientIdFor,+ aroundMessagesByClientIdForDevice,dismissErrorMessageFor,isRemoteSession,+ isRemoteSessionSticky,type RoutableMaker,} from '@/lib/makerTransport';import {@@ -83,10 +97,7 @@ import {requestRemoteReseed,} from '@/features/device-link/remoteProjectsStore';import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';-import {- clearCachedMessages,- readCachedMessages,-} from '@/features/device-link/mirrorCacheClient';+import { clearCachedMessages, readCachedMessages } from '@/features/device-link/mirrorCacheClient';import {noteRemoteSessionSyncCompleted,noteRemoteSessionSyncStarted,@@ -99,16 +110,16 @@ import {import { setMirrorEffort, setMirrorFast } from '@/state/deviceLinkModelMirror';import type { AgentKind } from '@/hooks/useAgentCapabilities';import type { Effort } from '@/lib/userPreferences.types';-import {- emitAutoTitlePreview,- emitAutoTitlePreviewCleared,- emitPatch,-} from '@/lib/sessionsBus';+import { emitAutoTitlePreview, emitAutoTitlePreviewCleared, emitPatch } from '@/lib/sessionsBus';import { createLogger } from '@/lib/logger';import { extractIpcError } from '@/utils/ipcError';import { tryBeginAgentSendDispatch } from '@/lib/agentSwitchCoordinator';import { getUserPrompt } from '@/lib/userPromptStore';import { getMakerMemoryEnabled } from '@/lib/memorySettingsStore';+import {+ isRemoteDataOwnerPushCurrent,+ resetRemoteDataOwnerPushFence,+} from '@/lib/remoteDataOwnerPushFence';import { buildUserMessageAttachmentPayload } from '@/lib/messageAttachmentPayload';import {parseIssueEnvRegion,@@ -183,6 +194,64 @@ const REMOTE_HEAVY_INBOUND_CHANNELS: ReadonlySet<string> = new Set(['maker:session-model-pref:changed',]);+type RemoteTerminalSessionTombstone = {+ deviceId: string;+ status: 'deleted' | 'archived';+};++/**+ * A terminal session push is a lifecycle boundary, not just another clear.+ * Keep that fact outside the evictable session slice so late remote frames+ * cannot call getOrCreateState and resurrect a deleted/archived task.+ */+const remoteTerminalSessionTombstones = new Map<string, RemoteTerminalSessionTombstone>();++function markRemoteTerminalSessionTombstone(+ deviceId: string,+ sessionId: string,+ status: 'deleted' | 'archived',+): void {+ const previous = remoteTerminalSessionTombstones.get(sessionId);+ if (previous?.status === 'deleted') return;+ remoteTerminalSessionTombstones.set(sessionId, { deviceId, status });+}++function isRemoteTerminalSessionTombstoned(sessionId: string, deviceId: string): boolean {+ const tombstone = remoteTerminalSessionTombstones.get(sessionId);+ return tombstone !== undefined && tombstone.deviceId === deviceId;+}++function isRemoteDeletedSessionSendBlocked(sessionId: string): boolean {+ const deviceId = getStickySessionDeviceId(sessionId);+ if (!deviceId) return false;+ return (+ remoteTerminalSessionTombstones.get(sessionId)?.deviceId === deviceId &&+ remoteTerminalSessionTombstones.get(sessionId)?.status === 'deleted'+ );+}++/**+ * Archived tasks may be explicitly unarchived. Only an authoritative active+ * session row from a fresh remote snapshot can release that tombstone; an+ * out-of-order `status: active` patch is intentionally ignored and merely+ * requests a reseed through remoteProjectsStore.+ */+function releaseArchivedRemoteTerminalTombstones(): void {+ if (remoteTerminalSessionTombstones.size === 0) return;+ const activeSessions = remoteProjectsStore.getMergedRemoteSessions();+ for (const [sessionId, tombstone] of remoteTerminalSessionTombstones) {+ if (tombstone.status !== 'archived') continue;+ const active = activeSessions.some(+ (session) =>+ session.id === sessionId &&+ session.deviceLinkDeviceId === tombstone.deviceId &&+ session.status !== 'archived' &&+ session.status !== 'deleted',+ );+ if (active) remoteTerminalSessionTombstones.delete(sessionId);+ }+}+function resolveEstimatedTurnCostUsd(rawCostUsd: number,turnCostIsEstimate: boolean,@@ -228,7 +297,11 @@ import {parseUserContent,stringifyUserContent,} from '@/lib/imageRef';-import { saveDraft as saveComposerDraft, plainTextToTiptapDoc } from '@/lib/composerDraftStore';+import {+ saveDraft as saveComposerDraft,+ plainTextToTiptapDoc,+ setRemoteOptimisticAttachmentUrls,+} from '@/lib/composerDraftStore';import {clearIssueConfirmDraft,clearIssueConfirmDraftsForSession,@@ -697,64 +770,1424 @@ export interface PendingGhostGrantConfirm {}>;}-/**- * rename_sessions 工具的写入前确认卡片数据(kind='rename_sessions_confirm')。- * main 侧确认桥 broadcast 当前将写入的变更清单;用户确认后 main 才继续写库。- */-export interface PendingRenameSessionsConfirm {- requestId: string;- changes: Array<{- sessionId: string;- currentTitle: string | null;- newTitle: string;- workingDir: string | null;- updatedAt: string;- }>;+/**+ * rename_sessions 工具的写入前确认卡片数据(kind='rename_sessions_confirm')。+ * main 侧确认桥 broadcast 当前将写入的变更清单;用户确认后 main 才继续写库。+ */+export interface PendingRenameSessionsConfirm {+ requestId: string;+ changes: Array<{+ sessionId: string;+ currentTitle: string | null;+ newTitle: string;+ workingDir: string | null;+ updatedAt: string;+ }>;+}++/** FP-3: Plan Viewer Card display state. */+export type PlanViewerState = 'expanded' | 'half' | 'minimized' | 'edit';++/**+ * F-AUQ-MIN-1: AskUserQuestion viewer display state.+ * - expanded: full-height Prompt card (default for every new pendingAskUser)+ * - minimized: 880×44 collapsed bar in the ChatInput slot (UI-only fold; SDK+ * stays suspended, pendingAskUser is unchanged)+ *+ * Lives at SessionChatState top level for symmetry with `planViewerState`.+ * Only meaningful when `pendingAskUser != null`. Never persisted (no IPC, no+ * localStorage, no DB column).+ *+ * 重置行为:会话切换后回到 'expanded' 由 CCAgentSessionView 的 sessionId useEffect+ * 负责(不在 store 内做,因为 store 不感知"当前活跃 sessionId")。+ */+export type AskUserViewerState = 'expanded' | 'minimized';++/**+ * F-QUEUE-1 / F-QUEUE-DEFER: Queued user message — captured at send time so+ * subsequent UI changes (model swap, permission mode swap, workingDir change)+ * don't affect already-queued messages.+ *+ * F-QUEUE-DEFER (2026-05): The user-facing ChatMessage (the bubble in the+ * message stream) is NOT pushed to `messages[]` at sendMessage time anymore.+ * It rides along inside `chatMessage`; main input projection decides whether+ * it remains queued or has been accepted into the visible message stream.+ * Until then, the message lives only in `pendingQueue` and is rendered by+ * `PendingQueuePanel` above the ChatInput.+ */+export interface QueuedMessage extends Omit<+ AgentInputQueuedMessage,+ 'chatMessage' | 'files' | 'mentions'+> {+ files?: SerializedAttachedFile[];+ mentions?: MentionedResource[];+ /**+ * F-QUEUE-DEFER: 预构建的 user ChatMessage 形态。sendMessage 时一次性 build+ * 好(含 images/files/createdAt),交给 main input coordinator 做接受/排队判定。+ * 在 main projection 确认接受前 UI 只能在 `pendingQueue` 里看到这条(由+ * PendingQueuePanel 渲染),消息流里不出现。+ */+ chatMessage: ChatMessage & { role: 'user' };+ /** device-link 控制端本地态:enqueue 尚未确认受理;不进入 wire / DB。 */+ isPendingEnqueue?: boolean;+}++interface RemoteOptimisticSendRecord {+ queued: QueuedMessage;+ recoverySequence: number;+ /** 注册发送时的账号代际;切号后任何迟到 Promise 都必须失效。 */+ dataOwner: DataOwnerGeneration;+ /** 首次解析到的被控设备;重试期间绝不重新按 sessionId 路由。 */+ deviceId: string;+ /** Click-time remote `/clear` token; null means the controller knew no clear yet. */+ /** `undefined` means the controller has not observed a boundary yet. */+ expectedClearBoundaryMs: number | null | undefined;+ /** Clear generation captured at click time, used when the token was unknown. */+ clearGeneration: number;+ /** An unknown-token record is probing the pinned host before first dispatch. */+ clearBoundaryProbeInFlight: boolean;+ /** The first probe settled, including the legacy projection-without-token path. */+ clearBoundaryProbeCompleted: boolean;+ /** A stale-token rejection may reopen the boundary probe at most once. */+ clearBoundaryRecoveryAttempted: boolean;+ /** Skip the cached boundary once after a stale-token rejection. */+ forceClearBoundaryProbe: boolean;+ deliveryMode: MessageDeliveryMode;+ accepted: boolean;+ currentlyQueued: boolean;+ phase: 'preflight' | 'dispatching' | 'waiting-for-connection' | 'accepted';+ dispatching: boolean;+ attempt: number;+ beforeEnqueue?: () => Promise<boolean>;+ preflightCompleted: boolean;+ /** 标注附件仍在本机烧录;完成前必须挡住本条及后续 FIFO 派发。 */+ materializationPending: boolean;+ /** steer 已可能送达但 ACK 丢失;后续 pump 只对账,绝不再次 steer。 */+ steerDispatchUncertain: boolean;+ authRetryPersistOnProjectionError?: SendMessageOpts['authRetryPersistOnProjectionError'];+ onRemoteOptimisticFailure?: SendMessageOpts['onRemoteOptimisticFailure'];+ /** Media needed by either dispatch or composer recovery while this item is pending. */+ attachmentUrls: string[];+ /** 点击时副作用中必须等附件烧录成功的部分(当前为自动起名)。 */+ onMaterializationReady?: (queued: QueuedMessage) => void;+ /** Composer already resolved true; a later pump failure must restore it. */+ composerResolvedOptimistically: boolean;+}++interface RemoteOptimisticSendScope {+ /** 点击发送时解析到的被控设备;附件物化期间不得重新路由。 */+ deviceId: string;+ /** 点击发送时的账号代际;附件物化迟到后必须按它判失效。 */+ dataOwner: DataOwnerGeneration;+ /** 跨物化/outbox 的点击顺序;owner boundary 恢复 composer 时保持 FIFO。 */+ recoverySequence: number;+ /** 点击时的 /clear 代际;预注册等待期间发生 clear 时旧发送必须失效。 */+ clearGeneration: number;+ /** Click-time remote `/clear` token used as the main-side precondition. */+ /** `undefined` means the controller has not observed a boundary yet. */+ expectedClearBoundaryMs: number | null | undefined;+}++let nextRemoteOptimisticRecoverySequence = 0;++function captureRemoteOptimisticSendScope(+ sessionId: string,+ callback?: NonNullable<SendMessageOpts['onRemoteOptimisticFailure']>,+): RemoteOptimisticSendScope | null {+ const transition = findRemoteOptimisticComposerTransition(sessionId, callback);+ if (transition) {+ return {+ deviceId: transition.deviceId,+ dataOwner: transition.dataOwner,+ recoverySequence: transition.recoverySequence,+ clearGeneration: transition.clearGeneration,+ expectedClearBoundaryMs: transition.expectedClearBoundaryMs,+ };+ }+ const deviceId = getStickySessionDeviceId(sessionId);+ return deviceId+ ? {+ deviceId,+ dataOwner: getDataOwnerGeneration(),+ recoverySequence: nextRemoteOptimisticRecoverySequence++,+ clearGeneration: rendererClearGenerationBySession.get(sessionId) ?? 0,+ expectedClearBoundaryMs: getKnownRemoteInputClearBoundary(sessionId),+ }+ : null;+}++interface RemoteOptimisticMaterializationRecovery {+ clientId: string;+ sessionId: string;+ deviceId: string;+ dataOwner: DataOwnerGeneration;+ recoverySequence: number;+ clearGeneration: number;+ /** `undefined` means the controller has not observed a boundary yet. */+ expectedClearBoundaryMs: number | null | undefined;+ attachmentUrls: string[];+ kind: 'composer-transition' | 'materialization';+ /** Delete/archive ended the task; a late ChatInput continuation must not restore it. */+ invalidatedByPurge: boolean;+ callback?: NonNullable<SendMessageOpts['onRemoteOptimisticFailure']>;+}++/** device-link 乐观发送事实账本,独立于可被 projection 覆盖的 pendingQueue。 */+const remoteOptimisticSends = new Map<string, Map<string, RemoteOptimisticSendRecord>>();+/**+ * Last clear token observed from the remote mirror/projection. Missing map entry+ * means unknown (for example an older controlled desktop omitted the field);+ * an entry with `null` is an explicit "never cleared" boundary.+ */+const remoteInputClearBoundaryBySession = new Map<string, number | null>();+type RemoteInputProjectionProbeState = {+ deviceId: string;+ dataOwner: DataOwnerGeneration;+ clearGeneration: number;+ status: 'ready' | 'blocked';+ /** `undefined` is a successful legacy projection with no boundary field. */+ boundary: number | null | undefined;+ error?: unknown;+};++type RemoteInputProjectionRequest = {+ deviceId: string;+ dataOwner: DataOwnerGeneration;+ clearGeneration: number;+ settled: boolean;+ promise: Promise<InputProjectionRequestResult>;+};++type InputProjectionRequestResult = {+ projection: AgentInputProjection;+ current: boolean;+};++/**+ * Projection reads are shared between the normal session hydration path and+ * the optimistic outbox preflight. Auto-title / origin reconciliation can+ * start a read in the same tick as a send; issuing a second read here both+ * wastes a weak-link round trip and can consume a different transient result.+ */+const remoteInputProjectionProbeStateBySession = new Map<string, RemoteInputProjectionProbeState>();+const remoteInputProjectionRequests = new Map<string, RemoteInputProjectionRequest>();+const remoteOptimisticMaterializationRecoveries = new Map<+ string,+ RemoteOptimisticMaterializationRecovery+>();+const remoteOptimisticLocallyRemoved = new Map<string, Set<string>>();+const remoteOptimisticSettlingTimers = new Map<+ string,+ Map<string, ReturnType<typeof setTimeout>>+>();+const remoteOptimisticSettlingChecks = new Set<string>();+const REMOTE_OPTIMISTIC_SETTLING_TIMEOUT_MS = 10_000;+const REMOTE_OUTBOX_RETRY_DELAY_MS = 1_500;+const remoteOptimisticPumps = new Map<string, Promise<void>>();+const remoteOptimisticRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();+/** Last remote presence state observed by this renderer, used to detect real reconnect edges. */+const remotePresenceOnlineByDevice = new Map<string, boolean>();+const remoteClearInFlight = new Set<string>();+/**+ * A remote clear is a content fence, not just a renderer-side reset. When the+ * controlled device is offline the local UI may still accept new messages, but+ * those messages must not be sent until the host has acknowledged the clear.+ * Keep this state separate from `remoteClearInFlight`: the latter only covers+ * the initial invoke, while this fence survives a timeout/rejection and retries+ * on reconnect.+ */+interface RemoteClearFence {+ sessionId: string;+ deviceId: string;+ dataOwner: DataOwnerGeneration;+ clearedAt: string;+ /** Host-owned boundary observed before this clear request was dispatched. */+ clearBoundaryBeforeRequest: number | null | undefined;+ clearGeneration: number;+ /** The last clear invoke may have reached the host but lost its response. */+ deliveryUncertain: boolean;+ dispatching: boolean;+}++const remoteClearFences = new Map<string, RemoteClearFence>();+const remoteClearRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();+const REMOTE_CLEAR_RETRY_DELAY_MS = 1_500;+const DEFINITELY_UNDELIVERED_REMOTE_STEER_MARKERS = [+ 'DEVICE_LINK_DEVICE_OFFLINE',+ 'DEVICE_UNRESPONSIVE',+] as const;+const REMOTE_OPTIMISTIC_DATA_OWNER_BOUNDARY_ERROR_CODE = 'REMOTE_OPTIMISTIC_DATA_OWNER_BOUNDARY';+const REMOTE_OPTIMISTIC_SESSION_PURGED_ERROR_CODE = 'REMOTE_OPTIMISTIC_SESSION_PURGED';++function clearRemoteClearRetryTimer(sessionId: string): void {+ const timer = remoteClearRetryTimers.get(sessionId);+ if (timer) clearTimeout(timer);+ remoteClearRetryTimers.delete(sessionId);+}++function isRemoteClearFenceCurrent(sessionId: string, fence?: RemoteClearFence): boolean {+ const current = fence ?? remoteClearFences.get(sessionId);+ return Boolean(+ current &&+ remoteClearFences.get(sessionId) === current &&+ isDataOwnerGenerationCurrent(current.dataOwner) &&+ getStickySessionDeviceId(sessionId) === current.deviceId &&+ (rendererClearGenerationBySession.get(sessionId) ?? 0) === current.clearGeneration,+ );+}++function hasPendingRemoteClearFence(sessionId: string): boolean {+ const fence = remoteClearFences.get(sessionId);+ if (!fence) return false;+ if (isRemoteClearFenceCurrent(sessionId, fence)) return true;+ clearRemoteClearRetryTimer(sessionId);+ remoteClearFences.delete(sessionId);+ return false;+}++function scheduleRemoteClearRetry(sessionId: string): void {+ if (!hasPendingRemoteClearFence(sessionId) || remoteClearRetryTimers.has(sessionId)) return;+ const timer = setTimeout(() => {+ remoteClearRetryTimers.delete(sessionId);+ void retryRemoteClearFence(sessionId);+ }, REMOTE_CLEAR_RETRY_DELAY_MS);+ remoteClearRetryTimers.set(sessionId, timer);+}++function armRemoteClearFence(sessionId: string, deviceId: string, clearedAt: string): void {+ const dataOwner = getDataOwnerGeneration();+ const clearGeneration = rendererClearGenerationBySession.get(sessionId) ?? 0;+ // `clearedAt` is the request identity and local renderer fence only. The+ // controlled host owns the authoritative boundary and may have a different+ // wall clock, so never seed the remote boundary map with the controller's+ // timestamp. The ACK projection below is the first value allowed to update+ // `remoteInputClearBoundaryBySession`.+ clearRemoteClearRetryTimer(sessionId);+ remoteClearFences.set(sessionId, {+ sessionId,+ deviceId,+ dataOwner,+ clearedAt,+ clearBoundaryBeforeRequest: getKnownRemoteInputClearBoundary(sessionId),+ clearGeneration,+ deliveryUncertain: true,+ dispatching: false,+ });+}++function noteRemoteClearDispatchError(+ sessionId: string,+ deviceId: string,+ clearedAt: string,+ error: unknown,+): void {+ const fence = remoteClearFences.get(sessionId);+ if (+ !fence ||+ fence.deviceId !== deviceId ||+ fence.clearedAt !== clearedAt ||+ !isRemoteClearFenceCurrent(sessionId, fence)+ ) {+ return;+ }+ fence.deliveryUncertain = !isDefinitelyUndeliveredRemoteMutationError(error);+}++function clearRemoteClearFence(sessionId: string, opts: { pump?: boolean } = {}): void {+ clearRemoteClearRetryTimer(sessionId);+ if (!remoteClearFences.delete(sessionId)) return;+ if (opts.pump !== false) pumpRemoteOptimisticSendsAfterCurrent(sessionId);+}++type RemoteClearProbeAssessment = 'applied' | 'not-applied' | 'inconclusive';++function assessRemoteClearProbe(+ fence: RemoteClearFence,+ projection: AgentInputProjection,+): RemoteClearProbeAssessment {+ if (!Object.prototype.hasOwnProperty.call(projection, 'clearBoundaryMs')) {+ // Legacy hosts cannot prove the clear through a projection. Preserve their+ // existing retry behavior after a successful round trip confirms the host+ // is reachable again.+ return 'not-applied';+ }+ const observed = normalizeAgentInputClearBoundaryMs(projection.clearBoundaryMs);+ if (observed === undefined) return 'inconclusive';+ const baseline = fence.clearBoundaryBeforeRequest;+ if (baseline === undefined) {+ // A current authoritative numeric projection is safer to treat as the lost+ // clear ACK than to risk destructively clearing post-request messages a+ // second time. Normal hydrated sessions always have a null/numeric baseline;+ // this is only the legacy/incomplete-hydration edge.+ return typeof observed === 'number' ? 'applied' : 'not-applied';+ }+ if (baseline === null) {+ return typeof observed === 'number' ? 'applied' : 'not-applied';+ }+ if (typeof observed !== 'number' || observed < baseline) return 'inconclusive';+ return observed > baseline ? 'applied' : 'not-applied';+}++function resolveRemoteClearFenceFromProjection(+ sessionId: string,+ deviceId: string,+ clearedAt: string,+ projection: AgentInputProjection,+ opts: { pump?: boolean; acknowledgment?: 'direct' | 'probe' } = {},+): boolean {+ const fence = remoteClearFences.get(sessionId);+ if (+ !fence ||+ fence.deviceId !== deviceId ||+ fence.clearedAt !== clearedAt ||+ !isRemoteClearFenceCurrent(sessionId, fence)+ ) {+ return false;+ }+ if (opts.acknowledgment === 'probe' && assessRemoteClearProbe(fence, projection) !== 'applied') {+ return false;+ }+ const hasAuthoritativeBoundary = Object.prototype.hasOwnProperty.call(+ projection,+ 'clearBoundaryMs',+ );+ if (hasAuthoritativeBoundary) {+ const observed = normalizeAgentInputClearBoundaryMs(projection.clearBoundaryMs);+ const known = remoteInputClearBoundaryBySession.get(sessionId);+ // The host timestamp is authoritative; do not compare it with the+ // controller's `clearedAt`. We can still reject malformed or regressing+ // host projections against a token already observed from that same host.+ if (+ observed === undefined ||+ (typeof known === 'number' &&+ (observed === null || (typeof observed === 'number' && observed < known)))+ ) {+ return false;+ }+ }+ // For modern projections, record the host token and retire the fence through+ // the same acknowledgement path used by push/session patches. This keeps+ // the clock-independent ordering rule in one place even if the caller later+ // drops the rest of the projection as stale. Legacy projections omit the+ // field, so resolve immediately for compatibility.+ if (hasAuthoritativeBoundary) {+ observeRemoteInputClearBoundary(sessionId, projection.clearBoundaryMs, {+ acknowledgePendingFence: true,+ });+ } else {+ clearRemoteClearFence(sessionId, opts);+ }+ return true;+}++type RemoteClearOperationResult<T> =+ | { kind: 'value'; value: T }+ | { kind: 'error'; error: unknown }+ | { kind: 'timeout' };++async function awaitRemoteClearOperation<T>(promise: Promise<T>): Promise<RemoteClearOperationResult<T>> {+ let timeoutId: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ promise.then(+ (value) => ({ kind: 'value' as const, value }),+ (error) => ({ kind: 'error' as const, error }),+ ),+ new Promise<{ kind: 'timeout' }>((resolve) => {+ timeoutId = setTimeout(() => resolve({ kind: 'timeout' }), CLEAR_SESSION_GUARD_TIMEOUT_MS);+ }),+ ]);+ } finally {+ if (timeoutId) clearTimeout(timeoutId);+ }+}++async function retryRemoteClearFence(sessionId: string): Promise<void> {+ const fence = remoteClearFences.get(sessionId);+ if (!isRemoteClearFenceCurrent(sessionId, fence) || fence!.dispatching) return;+ const current = fence!;+ current.dispatching = true;+ try {+ if (current.deliveryUncertain) {+ const probeOperation = beginInputProjectionOperation(sessionId, current.deviceId);+ const probeResult = await awaitRemoteClearOperation(+ probeOperation.api.input.getProjection(sessionId),+ );+ if (!isRemoteClearFenceCurrent(sessionId, current)) return;+ if (probeResult.kind !== 'value') {+ scheduleRemoteClearRetry(sessionId);+ return;+ }+ const assessment = assessRemoteClearProbe(current, probeResult.value);+ if (assessment === 'applied') {+ const resolved = resolveRemoteClearFenceFromProjection(+ sessionId,+ current.deviceId,+ current.clearedAt,+ probeResult.value,+ { pump: false, acknowledgment: 'probe' },+ );+ applyInputProjectionOperationResponse(sessionId, probeOperation, probeResult.value);+ if (resolved) pumpRemoteOptimisticSendsAfterCurrent(sessionId);+ else scheduleRemoteClearRetry(sessionId);+ return;+ }+ const applied = applyInputProjectionOperationResponse(+ sessionId,+ probeOperation,+ probeResult.value,+ );+ if (!applied || assessment === 'inconclusive') {+ scheduleRemoteClearRetry(sessionId);+ return;+ }+ current.deliveryUncertain = false;+ }++ if (!isRemoteClearFenceCurrent(sessionId, current)) return;+ const operation = beginInputProjectionOperation(sessionId, current.deviceId);+ current.deliveryUncertain = true;+ const result = await awaitRemoteClearOperation(+ operation.api.input.clearSession(sessionId, current.clearedAt),+ );+ if (!isRemoteClearFenceCurrent(sessionId, current)) return;+ if (result.kind === 'value') {+ const resolved = resolveRemoteClearFenceFromProjection(+ sessionId,+ current.deviceId,+ current.clearedAt,+ result.value,+ { pump: false },+ );+ applyInputProjectionOperationResponse(sessionId, operation, result.value);+ if (resolved) pumpRemoteOptimisticSendsAfterCurrent(sessionId);+ else scheduleRemoteClearRetry(sessionId);+ } else {+ if (result.kind === 'error') {+ current.deliveryUncertain = !isDefinitelyUndeliveredRemoteMutationError(result.error);+ }+ scheduleRemoteClearRetry(sessionId);+ }+ } catch (error) {+ if (isRemoteClearFenceCurrent(sessionId, current)) {+ log.warn('remote clear retry failed; keeping clear fence:', error);+ scheduleRemoteClearRetry(sessionId);+ }+ } finally {+ if (remoteClearFences.get(sessionId) === current) current.dispatching = false;+ }+}++function createRemoteOptimisticSessionPurgedError(): Error {+ return Object.assign(+ new Error('Remote optimistic send cancelled because the session was purged'),+ {+ code: REMOTE_OPTIMISTIC_SESSION_PURGED_ERROR_CODE,+ },+ );+}++export function isRemoteOptimisticDataOwnerBoundaryError(error: unknown): boolean {+ return (+ typeof error === 'object' &&+ error !== null &&+ (error as { code?: unknown }).code === REMOTE_OPTIMISTIC_DATA_OWNER_BOUNDARY_ERROR_CODE+ );+}++export function isRemoteOptimisticSessionPurgedError(error: unknown): boolean {+ return (+ typeof error === 'object' &&+ error !== null &&+ (error as { code?: unknown }).code === REMOTE_OPTIMISTIC_SESSION_PURGED_ERROR_CODE+ );+}++function remoteOptimisticSendRecords(+ sessionId: string,+ create = false,+): Map<string, RemoteOptimisticSendRecord> | undefined {+ const current = remoteOptimisticSends.get(sessionId);+ if (current || !create) return current;+ const next = new Map<string, RemoteOptimisticSendRecord>();+ remoteOptimisticSends.set(sessionId, next);+ return next;+}++function collectRemoteOptimisticAttachmentUrls(+ files: readonly { url?: string; annotationSourceUrl?: string }[] | undefined,+): string[] {+ const urls = new Set<string>();+ for (const file of files ?? []) {+ if (file.url) urls.add(file.url);+ if (file.annotationSourceUrl) urls.add(file.annotationSourceUrl);+ }+ return [...urls];+}++function syncRemoteOptimisticAttachmentUrls(): void {+ const urls = new Set<string>();+ for (const recovery of remoteOptimisticMaterializationRecoveries.values()) {+ for (const url of recovery.attachmentUrls) urls.add(url);+ }+ for (const records of remoteOptimisticSends.values()) {+ for (const record of records.values()) {+ for (const url of record.attachmentUrls) urls.add(url);+ }+ }+ setRemoteOptimisticAttachmentUrls([...urls]);+}++function findRemoteOptimisticComposerTransition(+ sessionId: string,+ callback: NonNullable<SendMessageOpts['onRemoteOptimisticFailure']> | undefined,+): RemoteOptimisticMaterializationRecovery | undefined {+ if (!callback) return undefined;+ for (const recovery of remoteOptimisticMaterializationRecoveries.values()) {+ if (+ recovery.kind === 'composer-transition' &&+ recovery.sessionId === sessionId &&+ recovery.callback === callback+ ) {+ return recovery;+ }+ }+ return undefined;+}++function isRemoteOptimisticMaterializationRecoveryActive(+ recovery: RemoteOptimisticMaterializationRecovery,+): boolean {+ return (+ !recovery.invalidatedByPurge &&+ isDataOwnerGenerationCurrent(recovery.dataOwner) &&+ (rendererClearGenerationBySession.get(recovery.sessionId) ?? 0) === recovery.clearGeneration+ );+}++export function isRemoteOptimisticComposerTransitionActive(+ sessionId: string,+ callback: NonNullable<SendMessageOpts['onRemoteOptimisticFailure']>,+): boolean {+ const transition = findRemoteOptimisticComposerTransition(sessionId, callback);+ return Boolean(transition && isRemoteOptimisticMaterializationRecoveryActive(transition));+}++function isRemoteOptimisticSendScopeActive(+ sessionId: string,+ scope: RemoteOptimisticSendScope,+): boolean {+ return (+ scope.dataOwner.dataOwnerId !== null &&+ isDataOwnerGenerationCurrent(scope.dataOwner) &&+ (rendererClearGenerationBySession.get(sessionId) ?? 0) === scope.clearGeneration+ );+}++function registerRemoteOptimisticSend(+ sessionId: string,+ queued: QueuedMessage,+ deviceId: string,+ deliveryMode: MessageDeliveryMode,+ dataOwner: DataOwnerGeneration,+ recoverySequence: number,+ expectedClearBoundaryMs: number | null | undefined,+ opts?: SendMessageOpts,+ recoveryFiles?: readonly AttachedFile[],+ materializationPending = false,+): RemoteOptimisticSendRecord {+ const record: RemoteOptimisticSendRecord = {+ queued,+ recoverySequence,+ dataOwner,+ deviceId,+ expectedClearBoundaryMs,+ clearGeneration: rendererClearGenerationBySession.get(sessionId) ?? 0,+ clearBoundaryProbeInFlight: false,+ clearBoundaryProbeCompleted: false,+ clearBoundaryRecoveryAttempted: false,+ forceClearBoundaryProbe: false,+ deliveryMode,+ accepted: false,+ currentlyQueued: false,+ phase: 'preflight',+ dispatching: false,+ attempt: 0,+ beforeEnqueue: opts?.beforeEnqueue,+ preflightCompleted: opts?.beforeEnqueue === undefined,+ materializationPending,+ steerDispatchUncertain: false,+ authRetryPersistOnProjectionError: opts?.authRetryPersistOnProjectionError,+ onRemoteOptimisticFailure: opts?.onRemoteOptimisticFailure,+ attachmentUrls: [+ ...new Set([+ ...collectRemoteOptimisticAttachmentUrls(queued.files),+ ...collectRemoteOptimisticAttachmentUrls(recoveryFiles),+ ]),+ ],+ composerResolvedOptimistically: false,+ };+ remoteOptimisticSendRecords(sessionId, true)!.set(queued.clientId, record);+ const composerTransition = findRemoteOptimisticComposerTransition(+ sessionId,+ opts?.onRemoteOptimisticFailure,+ );+ if (+ composerTransition?.recoverySequence === recoverySequence &&+ composerTransition.deviceId === deviceId+ ) {+ // The outbox record is now the live recovery/media owner. Remove the+ // click-time bridge only after installing it, then publish one atomic URL+ // projection so another window can never observe a zero-reference gap.+ remoteOptimisticMaterializationRecoveries.delete(composerTransition.clientId);+ }+ syncRemoteOptimisticAttachmentUrls();+ return record;+}++function registerRemoteOptimisticMaterializationRecovery(+ scope: RemoteOptimisticSendScope,+ sessionId: string,+ recoveryFiles?: readonly AttachedFile[],+ callback?: NonNullable<SendMessageOpts['onRemoteOptimisticFailure']>,+ kind: RemoteOptimisticMaterializationRecovery['kind'] = 'materialization',+): string {+ if (kind === 'materialization') {+ const transition = findRemoteOptimisticComposerTransition(sessionId, callback);+ if (+ transition?.recoverySequence === scope.recoverySequence &&+ transition.deviceId === scope.deviceId+ ) {+ transition.attachmentUrls = [+ ...new Set([+ ...transition.attachmentUrls,+ ...collectRemoteOptimisticAttachmentUrls(recoveryFiles),+ ]),+ ];+ syncRemoteOptimisticAttachmentUrls();+ return transition.clientId;+ }+ }+ const clientId = `materializing:${crypto.randomUUID()}`;+ remoteOptimisticMaterializationRecoveries.set(clientId, {+ clientId,+ sessionId,+ deviceId: scope.deviceId,+ dataOwner: scope.dataOwner,+ recoverySequence: scope.recoverySequence,+ clearGeneration: scope.clearGeneration,+ expectedClearBoundaryMs: scope.expectedClearBoundaryMs,+ attachmentUrls: collectRemoteOptimisticAttachmentUrls(recoveryFiles),+ kind,+ invalidatedByPurge: false,+ ...(callback ? { callback } : {}),+ });+ syncRemoteOptimisticAttachmentUrls();+ return clientId;+}++/**+ * Bridge the click-time composer clear to the store's synchronous outbox+ * registration. This closes the only interval where the draft has already+ * disappeared but neither recovery ownership nor media live refs existed.+ */+export function beginRemoteOptimisticComposerTransition(+ sessionId: string,+ recoveryFiles: readonly AttachedFile[] | undefined,+ callback: NonNullable<SendMessageOpts['onRemoteOptimisticFailure']>,+): () => void {+ if (isRemoteDeletedSessionSendBlocked(sessionId)) return () => {};+ const scope = captureRemoteOptimisticSendScope(sessionId);+ if (!scope || scope.dataOwner.dataOwnerId === null) return () => {};+ const recoveryId = registerRemoteOptimisticMaterializationRecovery(+ scope,+ sessionId,+ recoveryFiles,+ callback,+ 'composer-transition',+ );+ let released = false;+ return () => {+ if (released) return;+ released = true;+ clearRemoteOptimisticMaterializationRecovery(recoveryId);+ };+}++function clearRemoteOptimisticMaterializationRecovery(clientId: string | null): void {+ if (!clientId) return;+ const recovery = remoteOptimisticMaterializationRecoveries.get(clientId);+ if (!recovery || !remoteOptimisticMaterializationRecoveries.delete(clientId)) return;+ syncRemoteOptimisticAttachmentUrls();+ // A later FIFO item may have been waiting behind this click-time bridge.+ pumpRemoteOptimisticSendsAfterCurrent(recovery.sessionId);+}++function clearRemoteOptimisticMaterializationRecoveriesForSession(+ sessionId: string,+ opts: {+ preserveComposerTransitions?: boolean;+ markComposerTransitionsPurged?: boolean;+ } = {},+): void {+ let changed = false;+ for (const [clientId, recovery] of remoteOptimisticMaterializationRecoveries) {+ if (recovery.sessionId !== sessionId) continue;+ if (opts.preserveComposerTransitions && recovery.kind === 'composer-transition') {+ // 保留旧 clear generation 的零引用 tombstone,直到 ChatInput 的迟到 onSend+ // continuation 自己 release。否则删掉后它会重新捕获当前 generation,把已删除 /+ // 已清空任务复活。+ if (recovery.attachmentUrls.length > 0) {+ recovery.attachmentUrls = [];+ changed = true;+ }+ if (opts.markComposerTransitionsPurged) {+ recovery.invalidatedByPurge = true;+ }+ continue;+ }+ remoteOptimisticMaterializationRecoveries.delete(clientId);+ changed = true;+ }+ if (changed) syncRemoteOptimisticAttachmentUrls();+}++function restoreRemoteOptimisticMaterializationRecovery(+ clientId: string | null,+ error?: unknown,+): void {+ const recovery = clientId ? remoteOptimisticMaterializationRecoveries.get(clientId) : undefined;+ if (!recovery?.callback || !isRemoteOptimisticMaterializationRecoveryActive(recovery)) {+ return;+ }+ try {+ recovery.callback(recovery.clientId, error);+ } catch (restoreError) {+ log.warn('remote optimistic materialization restore failed:', restoreError);+ }+}++async function runRemoteOptimisticMaterialization(+ recoveryId: string | null,+ materialize: Promise<AttachedFile[] | undefined>,+ dispatch: (prepared: AttachedFile[] | undefined) => Promise<boolean>,+): Promise<boolean> {+ try {+ const prepared = await materialize;+ const accepted = await dispatch(prepared);+ if (!accepted) restoreRemoteOptimisticMaterializationRecovery(recoveryId);+ return accepted;+ } catch (error) {+ restoreRemoteOptimisticMaterializationRecovery(recoveryId, error);+ throw error;+ } finally {+ // On success dispatch has synchronously registered the outbox record before+ // its Promise resolves. On failure the callback has synchronously restored+ // the draft. Either way another live-ref domain is in place before release.+ clearRemoteOptimisticMaterializationRecovery(recoveryId);+ }+}++function markRemoteOptimisticSendAccepted(+ sessionId: string,+ clientId: string,+ queued?: QueuedMessage,+): void {+ const record = remoteOptimisticSendRecords(sessionId)?.get(clientId);+ if (!record) return;+ record.accepted = true;+ record.currentlyQueued = true;+ record.phase = 'accepted';+ record.preflightCompleted = true;+ if (queued) record.queued = queued;+}++function markRemoteOptimisticSendWaiting(sessionId: string, clientId: string): void {+ const record = remoteOptimisticSendRecords(sessionId)?.get(clientId);+ if (!record || record.accepted) return;+ record.phase = 'waiting-for-connection';+ record.dispatching = false;+ scheduleRemoteOptimisticRetry(sessionId);+}++function isDeferredRemoteSendError(error: unknown): boolean {+ // DEVICE_UNRESPONSIVE is intentionally permanent for bounded retry helpers,+ // but an input message is different: keeping it locally is safer than+ // presenting a false failure while the circuit is open.+ return (+ isTransientRemoteError(error) ||+ isDeviceUnresponsiveRemoteError(error) ||+ isRemoteInputStateUnavailableError(error)+ );+}++function isRemoteInputStateUnavailableError(error: unknown): boolean {+ return formatRemoteError(error).includes('REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE');+}++function isRemoteInputPreparationSupersededError(error: unknown): boolean {+ return formatRemoteError(error).includes('REMOTE_OPTIMISTIC_INPUT_SUPERSEDED');+}++function isRemoteInputClearBoundaryError(error: unknown): boolean {+ return formatRemoteError(error).includes('REMOTE_OPTIMISTIC_INPUT_CLEARED');+}++/**+ * Steer is not idempotent on older controlled desktops. Retry only failures+ * that the renderer-facing IPC contract can prove happened before dispatch.+ * DEVICE_LINK_NOT_CONNECTED intentionally does not qualify: main folds both+ * local NOT_CONNECTED/LINK_NOT_OPEN/BACKPRESSURE and an in-flight disconnect+ * into that one code, so retrying it could duplicate a steer that already ran.+ */+function isDefinitelyUndeliveredRemoteMutationError(error: unknown): boolean {+ const formatted = formatRemoteError(error);+ return DEFINITELY_UNDELIVERED_REMOTE_STEER_MARKERS.some((marker) => formatted.includes(marker));+}++function isDefinitelyUndeliveredRemoteSteerError(error: unknown): boolean {+ return isDefinitelyUndeliveredRemoteMutationError(error);+}++function isAmbiguousRemoteSteerError(error: unknown): boolean {+ return (+ isDeferredRemoteSendError(error) &&+ !isDefinitelyUndeliveredRemoteSteerError(error) &&+ !isRemoteInputStateUnavailableError(error)+ );+}++function isRemoteAroundClientIdMiss(error: unknown): boolean {+ return formatRemoteError(error).includes('NOT_FOUND');+}++/**+ * A terminal session-state rejection must never enter the ambiguous-delivery+ * reconciliation path. That path intentionally retries a steer as enqueue+ * when both authorities report no evidence; doing that for a deleted/missing+ * task would turn a definitive failure into a duplicate or a permanently+ * settling outbox record.+ */+function isTerminalRemoteInputError(error: unknown): boolean {+ const formatted = formatRemoteError(error);+ return formatted.includes('NOT_FOUND') || formatted.includes('REMOTE_OPTIMISTIC_SESSION_PURGED');+}++function clearRemoteOptimisticRetryTimer(sessionId: string): void {+ const timer = remoteOptimisticRetryTimers.get(sessionId);+ if (timer) clearTimeout(timer);+ remoteOptimisticRetryTimers.delete(sessionId);+}++function scheduleRemoteOptimisticRetry(sessionId: string): void {+ if (remoteOptimisticRetryTimers.has(sessionId)) return;+ const timer = setTimeout(() => {+ remoteOptimisticRetryTimers.delete(sessionId);+ void pumpRemoteOptimisticSends(sessionId);+ }, REMOTE_OUTBOX_RETRY_DELAY_MS);+ remoteOptimisticRetryTimers.set(sessionId, timer);+}++function firstUnacceptedRemoteOptimisticSend(+ sessionId: string,+): RemoteOptimisticSendRecord | undefined {+ const records = remoteOptimisticSendRecords(sessionId);+ let first: RemoteOptimisticSendRecord | undefined;+ for (const record of records?.values() ?? []) {+ if (!isDataOwnerGenerationCurrent(record.dataOwner)) {+ clearRemoteOptimisticSend(sessionId, record.queued.clientId);+ continue;+ }+ if (+ !record.accepted &&+ (first === undefined || record.recoverySequence < first.recoverySequence)+ ) {+ first = record;+ }+ }+ // beginRemoteOptimisticComposerTransition 与 outbox 注册之间仍有一个同步桥。+ // 若更早点击还停在桥上,后发记录即使已就绪也不能越过它。+ let oldestBridgeSequence = Number.POSITIVE_INFINITY;+ for (const recovery of remoteOptimisticMaterializationRecoveries.values()) {+ if (+ recovery.sessionId === sessionId &&+ isRemoteOptimisticMaterializationRecoveryActive(recovery) &&+ recovery.recoverySequence < oldestBridgeSequence+ ) {+ oldestBridgeSequence = recovery.recoverySequence;+ }+ }+ if (first && oldestBridgeSequence < first.recoverySequence) return undefined;+ return first;+}++function scheduleRemoteOptimisticSettlingRetirement(sessionId: string, clientId: string): void {+ let timers = remoteOptimisticSettlingTimers.get(sessionId);+ if (!timers) {+ timers = new Map();+ remoteOptimisticSettlingTimers.set(sessionId, timers);+ }+ if (timers.has(clientId)) return;+ const timer = setTimeout(() => {+ timers!.delete(clientId);+ if (timers!.size === 0) remoteOptimisticSettlingTimers.delete(sessionId);+ const checkKey = `${sessionId}\u0000${clientId}`;+ if (remoteOptimisticSettlingChecks.has(checkKey)) return;+ remoteOptimisticSettlingChecks.add(checkKey);+ void reconcileRemoteOptimisticSettling(sessionId, clientId).finally(() => {+ remoteOptimisticSettlingChecks.delete(checkKey);+ });+ }, REMOTE_OPTIMISTIC_SETTLING_TIMEOUT_MS);+ timers.set(clientId, timer);+}++/**+ * A projected queue item can disappear before the durable `messages:created`+ * push reaches the controller. The settling timer is therefore only a+ * reconciliation trigger; it is never permission to delete an accepted+ * message. Keep the record alive and retry against the pinned device until+ * the authoritative row is found (or another terminal boundary clears it).+ */+async function reconcileRemoteOptimisticSettling(+ sessionId: string,+ clientId: string,+): Promise<void> {+ const record = remoteOptimisticSendRecords(sessionId)?.get(clientId);+ if (!record || !record.accepted || !isDataOwnerGenerationCurrent(record.dataOwner)) return;++ let settled = false;+ try {+ const rows = await aroundMessagesByClientIdForDevice(record.deviceId, sessionId, clientId, {+ radius: 0,+ });+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return;+ const persisted = rows.find((message) => message.clientId === clientId);+ if (persisted) {+ const [mapped] = mapServerMessages([persisted]);+ // Do not resurrect a purged/LRU session merely to settle a late ACK.+ if (mapped && sessions.has(sessionId)) {+ setState(sessionId, (s) => {+ const existing = s.messages.find((message) => message.clientId === clientId);+ const messages = existing+ ? s.messages.map((message) =>+ message.clientId === clientId+ ? hydratePersistedMessage(message, mapped, {+ preserveExistingToolResultContent: true,+ preserveExistingCodexPlanContent: true,+ })+ : message,+ )+ : mergeMessages([mapped], s.messages, {+ preserveExistingToolResultContent: true,+ preserveExistingCodexPlanContent: true,+ });+ const pendingQueue = s.pendingQueue.filter((item) => item.clientId !== clientId);+ if (messages === s.messages && pendingQueue.length === s.pendingQueue.length) return s;+ return {+ ...s,+ messages,+ pendingQueue,+ isFirstMessage: mapped.role === 'user' ? false : s.isFirstMessage,+ };+ });+ }+ clearRemoteOptimisticSend(sessionId, clientId);+ settled = true;+ markSessionHasUserMessage(sessionId);+ void reconcileRemoteMessages(sessionId);+ }+ } catch (error) {+ // NOT_FOUND is a conclusive negative for this attempt, not a terminal+ // failure. A delayed DB commit or a dropped push must remain recoverable.+ if (!isRemoteAroundClientIdMiss(error)) {+ log.warn('remote optimistic settling reconciliation failed:', error);+ }+ } finally {+ const current = remoteOptimisticSendRecords(sessionId)?.get(clientId);+ if (!settled && current === record && record.accepted) {+ scheduleRemoteOptimisticSettlingRetirement(sessionId, clientId);+ }+ }+}++function cancelRemoteOptimisticSettlingRetirement(sessionId: string, clientId: string): void {+ const timers = remoteOptimisticSettlingTimers.get(sessionId);+ const timer = timers?.get(clientId);+ if (timer) clearTimeout(timer);+ timers?.delete(clientId);+ if (timers?.size === 0) remoteOptimisticSettlingTimers.delete(sessionId);+}++function retainOrClearRemoteOptimisticSendAfterProjection(+ sessionId: string,+ clientId: string,+): void {+ const hasPendingMessage = getOrCreateState(sessionId).messages.some(+ (message) => message.clientId === clientId && message.isPendingPersist,+ );+ if (hasPendingMessage) {+ scheduleRemoteOptimisticSettlingRetirement(sessionId, clientId);+ } else {+ clearRemoteOptimisticSend(sessionId, clientId);+ }+}++function clearRemoteOptimisticSend(sessionId: string, clientId: string): void {+ const records = remoteOptimisticSends.get(sessionId);+ const deleted = records?.delete(clientId) === true;+ if (records?.size === 0) remoteOptimisticSends.delete(sessionId);+ cancelRemoteOptimisticSettlingRetirement(sessionId, clientId);+ const removed = remoteOptimisticLocallyRemoved.get(sessionId);+ removed?.delete(clientId);+ if (removed?.size === 0) remoteOptimisticLocallyRemoved.delete(sessionId);+ remoteOptimisticSettlingChecks.delete(`${sessionId}\u0000${clientId}`);+ if (deleted) syncRemoteOptimisticAttachmentUrls();+}++function clearRemoteOptimisticSendsForSession(sessionId: string): void {+ const deleted = remoteOptimisticSends.delete(sessionId);+ remoteInputProjectionRequests.delete(sessionId);+ remoteInputProjectionProbeStateBySession.delete(sessionId);+ clearRemoteOptimisticRetryTimer(sessionId);+ remoteOptimisticPumps.delete(sessionId);+ const timers = remoteOptimisticSettlingTimers.get(sessionId);+ if (timers) {+ for (const timer of timers.values()) clearTimeout(timer);+ remoteOptimisticSettlingTimers.delete(sessionId);+ }+ for (const key of remoteOptimisticSettlingChecks) {+ if (key.startsWith(`${sessionId}\u0000`)) remoteOptimisticSettlingChecks.delete(key);+ }+ remoteOptimisticLocallyRemoved.delete(sessionId);+ if (deleted) syncRemoteOptimisticAttachmentUrls();+}++/**+ * AuthContext 在发布新 data owner 之前同步调用。先在旧 owner 的 composer 命名空间+ * 恢复尚未确认受理的正文/附件,再清账本与 UI;之后任何迟到 invoke / projection+ * 都会同时被 Map identity 与 data-owner generation 挡住,不能跨账号继续投递或恢复。+ */+export function cancelRemoteOptimisticSendsForDataOwnerBoundary(): void {+ invalidateLiveIngressForDataOwnerBoundary();+ // Invalidate standalone projection reads/operations before restoring drafts+ // or publishing the next owner. Their promises may settle independently of+ // the optimistic outbox and must not write old-owner state into the new slice.+ invalidateInputProjectionRequestsForDataOwnerBoundary();+ for (const sessionId of remoteClearFences.keys()) {+ clearRemoteClearFence(sessionId, { pump: false });+ }++ const recoveries: Array<{+ clientId: string;+ recoverySequence: number;+ callback: NonNullable<SendMessageOpts['onRemoteOptimisticFailure']>;+ }> = [];++ for (const recovery of remoteOptimisticMaterializationRecoveries.values()) {+ if (+ recovery.invalidatedByPurge ||+ !isDataOwnerGenerationCurrent(recovery.dataOwner) ||+ !recovery.callback+ ) {+ continue;+ }+ recoveries.push({+ clientId: recovery.clientId,+ recoverySequence: recovery.recoverySequence,+ callback: recovery.callback,+ });+ }++ const clientIdsBySession = new Map<string, Set<string>>();+ for (const [sessionId, records] of remoteOptimisticSends) {+ clientIdsBySession.set(sessionId, new Set(records.keys()));+ for (const record of records.values()) {+ if (+ !record.accepted &&+ record.composerResolvedOptimistically &&+ record.onRemoteOptimisticFailure &&+ isDataOwnerGenerationCurrent(record.dataOwner)+ ) {+ recoveries.push({+ clientId: record.queued.clientId,+ recoverySequence: record.recoverySequence,+ callback: record.onRemoteOptimisticFailure,+ });+ }+ }+ }++ const error = Object.assign(+ new Error('Remote optimistic send cancelled at data-owner boundary'),+ { code: REMOTE_OPTIMISTIC_DATA_OWNER_BOUNDARY_ERROR_CODE },+ );+ recoveries.sort((left, right) => left.recoverySequence - right.recoverySequence);+ for (const recovery of recoveries) {+ try {+ recovery.callback(recovery.clientId, error);+ } catch (restoreError) {+ log.warn('remote optimistic composer restore failed at data-owner boundary:', restoreError);+ }+ }++ // Restore callbacks synchronously publish their draft attachment URLs while+ // the outbox/materialization refs are still live. Only then retire the old+ // owner records, so main never observes a cleanup-eligible gap between the+ // two ownership domains.+ for (const [clientId, recovery] of remoteOptimisticMaterializationRecoveries) {+ if (+ recovery.kind === 'composer-transition' &&+ isDataOwnerGenerationCurrent(recovery.dataOwner)+ ) {+ // Keep a zero-ref tombstone until ChatInput's pending onSend settles.+ // A late continuation then reuses the original owner generation and is+ // rejected instead of capturing the newly signed-in owner.+ recovery.attachmentUrls = [];+ continue;+ }+ remoteOptimisticMaterializationRecoveries.delete(clientId);+ }+ syncRemoteOptimisticAttachmentUrls();+ for (const [sessionId, clientIds] of clientIdsBySession) {+ clearRemoteOptimisticSendsForSession(sessionId);+ if (sessions.has(sessionId)) {+ setState(sessionId, (state) => ({+ ...state,+ pendingQueue: state.pendingQueue.filter((item) => !clientIds.has(item.clientId)),+ messages: state.messages.filter(+ (message) => !(clientIds.has(message.clientId) && message.isPendingPersist),+ ),+ }));+ }+ }+}++/** Clear deferred live ingress work before AuthContext publishes a new owner. */+export function invalidateLiveIngressForDataOwnerBoundary(): void {+ clearTextDeltaFlushTimer();+ pendingTextDeltaBatches.clear();+ clearDeferredStateNotificationTimer();+ pendingDeferredStateNotifications.clear();+ pendingMessageCreatedPatches.clear();+ remotePresenceOnlineByDevice.clear();+ resetRemoteDataOwnerPushFence();+}++function cancelRemoteOptimisticSendsForSessionPurge(sessionId: string): void {+ bumpInteractionReconcileEpoch(sessionId);+ clearRemoteClearFence(sessionId, { pump: false });+ const recoveries: Array<{+ clientId: string;+ recoverySequence: number;+ callback: NonNullable<SendMessageOpts['onRemoteOptimisticFailure']>;+ }> = [];++ for (const recovery of remoteOptimisticMaterializationRecoveries.values()) {+ if (+ recovery.sessionId === sessionId &&+ recovery.callback &&+ isDataOwnerGenerationCurrent(recovery.dataOwner)+ ) {+ recoveries.push({+ clientId: recovery.clientId,+ recoverySequence: recovery.recoverySequence,+ callback: recovery.callback,+ });+ }+ }+ for (const record of remoteOptimisticSendRecords(sessionId)?.values() ?? []) {+ if (+ !record.accepted &&+ record.composerResolvedOptimistically &&+ record.onRemoteOptimisticFailure &&+ isDataOwnerGenerationCurrent(record.dataOwner)+ ) {+ recoveries.push({+ clientId: record.queued.clientId,+ recoverySequence: record.recoverySequence,+ callback: record.onRemoteOptimisticFailure,+ });+ }+ }++ clearRemoteOptimisticMaterializationRecoveriesForSession(sessionId, {+ preserveComposerTransitions: true,+ markComposerTransitionsPurged: true,+ });+ const error = createRemoteOptimisticSessionPurgedError();+ recoveries.sort((left, right) => left.recoverySequence - right.recoverySequence);+ for (const recovery of recoveries) {+ try {+ recovery.callback(recovery.clientId, error);+ } catch (callbackError) {+ log.warn('remote optimistic composer purge callback failed:', callbackError);+ }+ }++ clearRemoteOptimisticSendsForSession(sessionId);+}++/**+ * A remote `/clear` is a non-terminal owner boundary. Drop only the optimistic+ * state that predates the new token, restore drafts with the ordinary failure+ * callback, and leave a composer-transition tombstone for late ChatInput+ * continuations. Unlike purge/delete this must not surface a purge error.+ */+function cancelRemoteOptimisticSendsForRemoteClear(+ sessionId: string,+ clearBoundaryMs: number,+ opts: { historicalHydration?: boolean } = {},+): void {+ bumpMessagesEpoch(sessionId);+ bumpInteractionReconcileEpoch(sessionId);+ invalidateInputProjectionRequests(sessionId);+ const pinnedDeviceId = getStickySessionDeviceId(sessionId);+ invalidateRemoteMessageCache(sessionId, pinnedDeviceId);++ const recoveries: Array<{+ clientId: string;+ recoverySequence: number;+ callback: NonNullable<SendMessageOpts['onRemoteOptimisticFailure']>;+ }> = [];+ const recordClientIds = new Set<string>();+ const currentClearGeneration = rendererClearGenerationBySession.get(sessionId) ?? 0;+ const isRecordSupersededByClear = (record: RemoteOptimisticSendRecord): boolean => {+ if (opts.historicalHydration) {+ // This is the first numeric token observed after a controller restart.+ // The token and click timestamps may come from different devices, so no+ // wall-clock comparison can prove that an existing optimistic record was+ // created after the clear. Retire every pre-hydration record; sends made+ // after this observation capture the known token synchronously.+ return true;+ }+ // A generation change is the authoritative click-time ordering signal. It+ // handles unknown-token records without misclassifying a send created after+ // a historical clear was first observed.+ if (record.clearGeneration < currentClearGeneration) return true;+ // The record was created after this clear was observed but the controller+ // still has no token (legacy host or a pending probe). Let its own probe /+ // main-side precondition decide; it belongs to the new generation.+ if (record.expectedClearBoundaryMs === undefined) return false;+ if (record.expectedClearBoundaryMs === null) return true;+ return (+ typeof record.expectedClearBoundaryMs === 'number' &&+ record.expectedClearBoundaryMs < clearBoundaryMs+ );+ };+ const isRecoverySupersededByClear = (+ recovery: RemoteOptimisticMaterializationRecovery,+ ): boolean => {+ if (opts.historicalHydration) {+ // Materialisation has no authoritative remote token until dispatch. For+ // the same clock-independent first-hydration rule as queue records,+ // retire every recovery that predates this observation; new recoveries+ // capture the known token in their scope.+ return true;+ }+ if (recovery.clearGeneration < currentClearGeneration) return true;+ if (recovery.expectedClearBoundaryMs === undefined) return false;+ if (recovery.expectedClearBoundaryMs === null) return true;+ return (+ typeof recovery.expectedClearBoundaryMs === 'number' &&+ recovery.expectedClearBoundaryMs < clearBoundaryMs+ );+ };+ for (const recovery of remoteOptimisticMaterializationRecoveries.values()) {+ if (recovery.sessionId !== sessionId || !recovery.callback) continue;+ if (!isDataOwnerGenerationCurrent(recovery.dataOwner)) continue;+ if (!isRecoverySupersededByClear(recovery)) continue;+ recoveries.push({+ clientId: recovery.clientId,+ recoverySequence: recovery.recoverySequence,+ callback: recovery.callback,+ });+ }+ for (const record of remoteOptimisticSendRecords(sessionId)?.values() ?? []) {+ if (!isRecordSupersededByClear(record)) continue;+ recordClientIds.add(record.queued.clientId);+ if (+ !record.accepted &&+ record.composerResolvedOptimistically &&+ record.onRemoteOptimisticFailure &&+ isDataOwnerGenerationCurrent(record.dataOwner)+ ) {+ recoveries.push({+ clientId: record.queued.clientId,+ recoverySequence: record.recoverySequence,+ callback: record.onRemoteOptimisticFailure,+ });+ }+ }++ for (const [clientId, recovery] of remoteOptimisticMaterializationRecoveries) {+ if (recovery.sessionId !== sessionId || !isRecoverySupersededByClear(recovery)) continue;+ if (recovery.kind === 'composer-transition') {+ // Keep a tombstone until the late ChatInput continuation releases it; it+ // must not capture the post-clear generation and recreate the send.+ recovery.attachmentUrls = [];+ recovery.invalidatedByPurge = true;+ } else {+ remoteOptimisticMaterializationRecoveries.delete(clientId);+ }+ }+ syncRemoteOptimisticAttachmentUrls();+ recoveries.sort((left, right) => left.recoverySequence - right.recoverySequence);+ const restored = new Set<string>();+ for (const recovery of recoveries) {+ if (restored.has(recovery.clientId)) continue;+ restored.add(recovery.clientId);+ try {+ recovery.callback(recovery.clientId, undefined);+ } catch (error) {+ log.warn('remote optimistic composer restore failed at clear boundary:', error);+ }+ }+ for (const clientId of recordClientIds) {+ clearRemoteOptimisticSend(sessionId, clientId);+ }++ if (sessions.has(sessionId)) {+ setState(sessionId, (state) => {+ const pendingQueue = state.pendingQueue.filter((item) => !recordClientIds.has(item.clientId));+ const messages = state.messages.filter(+ (message) => !(recordClientIds.has(message.clientId) && message.isPendingPersist),+ );+ const steeringQueueClientIds = state.steeringQueueClientIds.filter(+ (clientId) => !recordClientIds.has(clientId),+ );+ if (+ pendingQueue === state.pendingQueue &&+ messages === state.messages &&+ steeringQueueClientIds === state.steeringQueueClientIds+ ) {+ return state;+ }+ return {+ ...state,+ pendingQueue,+ messages,+ steeringQueueClientIds,+ queueAbortPending: false,+ queueInteractionLocks: [],+ queueEditLocks: [],+ };+ });+ }+}++function markRemoteOptimisticLocallyRemoved(sessionId: string, clientId: string): void {+ let removed = remoteOptimisticLocallyRemoved.get(sessionId);+ if (!removed) {+ removed = new Set<string>();+ remoteOptimisticLocallyRemoved.set(sessionId, removed);+ }+ removed.add(clientId);}-/** FP-3: Plan Viewer Card display state. */-export type PlanViewerState = 'expanded' | 'half' | 'minimized' | 'edit';--/**- * F-AUQ-MIN-1: AskUserQuestion viewer display state.- * - expanded: full-height Prompt card (default for every new pendingAskUser)- * - minimized: 880×44 collapsed bar in the ChatInput slot (UI-only fold; SDK- * stays suspended, pendingAskUser is unchanged)- *- * Lives at SessionChatState top level for symmetry with `planViewerState`.- * Only meaningful when `pendingAskUser != null`. Never persisted (no IPC, no- * localStorage, no DB column).- *- * 重置行为:会话切换后回到 'expanded' 由 CCAgentSessionView 的 sessionId useEffect- * 负责(不在 store 内做,因为 store 不感知"当前活跃 sessionId")。- */-export type AskUserViewerState = 'expanded' | 'minimized';--/**- * F-QUEUE-1 / F-QUEUE-DEFER: Queued user message — captured at send time so- * subsequent UI changes (model swap, permission mode swap, workingDir change)- * don't affect already-queued messages.- *- * F-QUEUE-DEFER (2026-05): The user-facing ChatMessage (the bubble in the- * message stream) is NOT pushed to `messages[]` at sendMessage time anymore.- * It rides along inside `chatMessage`; main input projection decides whether- * it remains queued or has been accepted into the visible message stream.- * Until then, the message lives only in `pendingQueue` and is rendered by- * `PendingQueuePanel` above the ChatInput.- */-export interface QueuedMessage extends Omit<- AgentInputQueuedMessage,- 'chatMessage' | 'files' | 'mentions'-> {- files?: SerializedAttachedFile[];- mentions?: MentionedResource[];- /**- * F-QUEUE-DEFER: 预构建的 user ChatMessage 形态。sendMessage 时一次性 build- * 好(含 images/files/createdAt),交给 main input coordinator 做接受/排队判定。- * 在 main projection 确认接受前 UI 只能在 `pendingQueue` 里看到这条(由- * PendingQueuePanel 渲染),消息流里不出现。- */- chatMessage: ChatMessage & { role: 'user' };+function unmarkRemoteOptimisticLocallyRemoved(sessionId: string, clientId: string): void {+ const removed = remoteOptimisticLocallyRemoved.get(sessionId);+ removed?.delete(clientId);+ if (removed?.size === 0) remoteOptimisticLocallyRemoved.delete(sessionId);}export type MessageDeliveryMode = 'queue' | 'steer';@@ -1286,10 +2719,7 @@ function flushPendingMessageCreatedPatch(sessionId: string): void {function flushDeferredStateNotifications(): void {deferredStateNotificationTimer = null;const sessionIds = [- ...new Set([- ...pendingDeferredStateNotifications,- ...pendingMessageCreatedPatches.keys(),- ]),+ ...new Set([...pendingDeferredStateNotifications, ...pendingMessageCreatedPatches.keys()]),].slice(0, HIGH_FREQUENCY_NOTIFY_MAX_SESSIONS_PER_TICK);let stateChanged = false;for (const sessionId of sessionIds) {@@ -1370,6 +2800,199 @@ function _touchSession(sessionId: string): void {*/const _lastInboundEventAt = new Map<string, number>();const rendererClearBoundaryBySession = new Map<string, number>();+const rendererClearGenerationBySession = new Map<string, number>();++type RemoteInputClearBoundary = number | null | undefined;++function observeRemoteInputClearBoundary(+ sessionId: string,+ rawBoundary: unknown,+ opts: { acknowledgePendingFence?: boolean } = {},+): RemoteInputClearBoundary {+ const normalized = normalizeAgentInputClearBoundaryMs(rawBoundary);+ if (normalized === undefined) {+ return remoteInputClearBoundaryBySession.has(sessionId)+ ? remoteInputClearBoundaryBySession.get(sessionId)+ : undefined;+ }++ const hadPrevious = remoteInputClearBoundaryBySession.has(sessionId);+ const previous = remoteInputClearBoundaryBySession.get(sessionId);+ const pendingFence = remoteClearFences.get(sessionId);+ const pendingFenceIsCurrent = Boolean(+ pendingFence && isRemoteClearFenceCurrent(sessionId, pendingFence),+ );+ const acknowledgesPendingFence = Boolean(+ pendingFenceIsCurrent &&+ typeof normalized === 'number' &&+ (opts.acknowledgePendingFence === true ||+ pendingFence!.clearBoundaryBeforeRequest === null ||+ (typeof pendingFence!.clearBoundaryBeforeRequest === 'number' &&+ normalized > pendingFence!.clearBoundaryBeforeRequest)),+ );+ let advanced = false;+ if (!hadPrevious) {+ remoteInputClearBoundaryBySession.set(sessionId, normalized);+ // The first numeric token may describe a historical clear that happened+ // before this controller received its first snapshot. The controller and+ // the controlled host do not share a clock, so timestamps cannot establish+ // ordering here. Retire every record/recovery that has not already captured+ // an authoritative token; a record created after hydration captures the+ // known token synchronously and is therefore preserved.+ if (typeof normalized === 'number' && !acknowledgesPendingFence && !pendingFenceIsCurrent) {+ cancelRemoteOptimisticSendsForRemoteClear(sessionId, normalized, {+ historicalHydration: true,+ });+ }+ advanced = false;+ } else if (+ typeof normalized === 'number' &&+ (previous === null || (typeof previous === 'number' && normalized > previous))+ ) {+ // Clear boundaries are an append-only log. A delayed /clear patch or an+ // older reseed must never move the controller back to an earlier epoch.+ remoteInputClearBoundaryBySession.set(sessionId, normalized);+ advanced = true;+ }++ if (typeof normalized === 'number') {+ const rendererBoundary = rendererClearBoundaryBySession.get(sessionId);+ if (rendererBoundary === undefined || normalized > rendererBoundary) {+ rendererClearBoundaryBySession.set(sessionId, normalized);+ }+ }++ // A generic projection/session patch only acknowledges the pending clear+ // when it strictly advances the host boundary captured before dispatch. A+ // direct clear response passes the explicit option above because the response+ // itself proves execution even if two host events share one millisecond.+ if (acknowledgesPendingFence) {+ clearRemoteClearFence(sessionId, { pump: false });+ }++ if (advanced && typeof normalized === 'number' && !acknowledgesPendingFence) {+ remoteInputProjectionProbeStateBySession.delete(sessionId);+ remoteInputProjectionRequests.delete(sessionId);+ bumpRendererClearGeneration(sessionId);+ // A clear received from another controller invalidates the local outbox at+ // the same boundary. This is deliberately scoped to the session; it must+ // not tear down the device-link/relay shared connection.+ cancelRemoteOptimisticSendsForRemoteClear(sessionId, normalized);+ }+ return remoteInputClearBoundaryBySession.get(sessionId);+}++function isRemoteInputProjectionProbeStateCurrent(+ sessionId: string,+ state: RemoteInputProjectionProbeState,+ deviceId: string,+): boolean {+ return (+ state.deviceId === deviceId &&+ isDataOwnerGenerationCurrent(state.dataOwner) &&+ getStickySessionDeviceId(sessionId) === deviceId &&+ (rendererClearGenerationBySession.get(sessionId) ?? 0) === state.clearGeneration+ );+}++function isAcceptedRemoteProjectionBoundary(+ sessionId: string,+ projection: AgentInputProjection,+): boolean {+ if (!Object.prototype.hasOwnProperty.call(projection, 'clearBoundaryMs')) return true;+ const incoming = normalizeAgentInputClearBoundaryMs(projection.clearBoundaryMs);+ if (incoming === undefined) return false;+ const known = remoteInputClearBoundaryBySession.get(sessionId);+ return !(+ typeof known === 'number' &&+ (incoming === null || (typeof incoming === 'number' && incoming < known))+ );+}++function noteRemoteInputProjectionSuccess(+ sessionId: string,+ deviceId: string,+ dataOwner: DataOwnerGeneration,+ clearGeneration: number,+ projection: AgentInputProjection,+): void {+ if (+ !isDataOwnerGenerationCurrent(dataOwner) ||+ getStickySessionDeviceId(sessionId) !== deviceId ||+ (rendererClearGenerationBySession.get(sessionId) ?? 0) !== clearGeneration ||+ !isAcceptedRemoteProjectionBoundary(sessionId, projection)+ ) {+ return;+ }+ const boundary = Object.prototype.hasOwnProperty.call(projection, 'clearBoundaryMs')+ ? normalizeAgentInputClearBoundaryMs(projection.clearBoundaryMs)+ : undefined;+ remoteInputProjectionProbeStateBySession.set(sessionId, {+ deviceId,+ dataOwner,+ clearGeneration,+ status: 'ready',+ boundary,+ });+}++function noteRemoteInputProjectionFailure(+ sessionId: string,+ deviceId: string,+ dataOwner: DataOwnerGeneration,+ clearGeneration: number,+ error: unknown,+): void {+ if (+ !isDataOwnerGenerationCurrent(dataOwner) ||+ getStickySessionDeviceId(sessionId) !== deviceId ||+ (rendererClearGenerationBySession.get(sessionId) ?? 0) !== clearGeneration+ ) {+ return;+ }+ remoteInputProjectionProbeStateBySession.set(sessionId, {+ deviceId,+ dataOwner,+ clearGeneration,+ status: 'blocked',+ boundary: undefined,+ error,+ });+}++function clearRemoteInputProjectionProbeFailure(sessionId: string, deviceId?: string): void {+ const state = remoteInputProjectionProbeStateBySession.get(sessionId);+ if (!state || state.status !== 'blocked' || (deviceId && state.deviceId !== deviceId)) return;+ remoteInputProjectionProbeStateBySession.delete(sessionId);+}++function getKnownRemoteInputClearBoundary(sessionId: string): RemoteInputClearBoundary {+ if (remoteInputClearBoundaryBySession.has(sessionId)) {+ return remoteInputClearBoundaryBySession.get(sessionId);+ }+ const deviceId = getStickySessionDeviceId(sessionId);+ if (!deviceId) return undefined;+ const session = remoteProjectsStore+ .getDeviceSessions(deviceId)+ .find((candidate) => candidate.id === sessionId);+ if (!session || !Object.prototype.hasOwnProperty.call(session, 'clearedAt')) return undefined;+ return observeRemoteInputClearBoundary(sessionId, session.clearedAt);+}++function getRemoteInputClearBoundaryOpts(+ sessionId: string,+): { expectedClearBoundaryMs: number | null } | undefined {+ if (!getStickySessionDeviceId(sessionId)) return undefined;+ const boundary = getKnownRemoteInputClearBoundary(sessionId);+ return boundary === undefined ? undefined : { expectedClearBoundaryMs: boundary };+}++function observeRemoteInputClearBoundariesFromSnapshot(): void {+ for (const session of remoteProjectsStore.getMergedRemoteSessions()) {+ if (!Object.prototype.hasOwnProperty.call(session, 'clearedAt')) continue;+ observeRemoteInputClearBoundary(session.id, session.clearedAt);+ }+}/** 标记该 session 刚收到一帧入站事件(O(1) 原始数写入,无分配、无 notify)。 */function _markInboundEvent(sessionId: string): void {@@ -1385,12 +3008,20 @@ function getLastInboundEventAt(sessionId: string): number | undefined {return _lastInboundEventAt.get(sessionId);}+function bumpRendererClearGeneration(sessionId: string): void {+ rendererClearGenerationBySession.set(+ sessionId,+ (rendererClearGenerationBySession.get(sessionId) ?? 0) + 1,+ );+}+function noteRendererClearBoundary(sessionId: string, clearedAt: string): void {- const parsed = new Date(clearedAt).getTime();- if (!Number.isFinite(parsed)) return;+ const parsed = normalizeAgentInputClearBoundaryMs(clearedAt);+ if (typeof parsed !== 'number') return;const current = rendererClearBoundaryBySession.get(sessionId);if (current === undefined || parsed > current) {rendererClearBoundaryBySession.set(sessionId, parsed);+ bumpRendererClearGeneration(sessionId);}}@@ -1415,6 +3046,10 @@ function _purgeSession(sessionId: string): void {// 避免其提交把旧窗口 merge 进 purge 后重建的空 slice。bumpMessagesEpoch(sessionId);invalidateInputProjectionRequests(sessionId);+ // 删除 / 归档 / LRU 都是 renderer owner 边界。作废仍在附件物化或 composer+ // 交接中的迟到 continuation,且不写入 /clear 的历史时间边界。+ bumpRendererClearGeneration(sessionId);+ cancelRemoteOptimisticSendsForSessionPurge(sessionId);sessions.delete(sessionId);// 状态快照同步失效:该会话若有 running / pending / 待投递 transition 条目,// 不能在缓存里残留(purge 不走 setState,需单独置位)。@@ -1433,7 +3068,6 @@ function _purgeSession(sessionId: string): void {_cacheHydrateSuppressed.delete(sessionId);_lastViewedAt.delete(sessionId);_lastInboundEventAt.delete(sessionId);- rendererClearBoundaryBySession.delete(sessionId);const i = _accessOrder.indexOf(sessionId);if (i !== -1) _accessOrder.splice(i, 1);}@@ -1457,6 +3091,11 @@ function _evictLruIfNeeded(): void {!s.isStreaming &&!s.agentStatus.isRunning &&!hasBackgroundAgentWork(id, s) &&+ !remoteOptimisticSends.has(id) &&+ ![...remoteOptimisticMaterializationRecoveries.values()].some(+ (recovery) =>+ recovery.sessionId === id && isRemoteOptimisticMaterializationRecoveryActive(recovery),+ ) &&!_activeViewSessions.has(id));});@@ -1477,6 +3116,15 @@ function _isSessionBusy(sessionId: string, s: SessionChatState): boolean {return !!(s.isStreaming ||s.agentStatus.isRunning ||+ // A device-link optimistic send is still an in-flight user action even if+ // the remote projection has not materialized it into pendingQueue yet.+ // Keep trim/demote from dropping its local bubble while the relay recovers.+ remoteOptimisticSends.has(sessionId) ||+ [...remoteOptimisticMaterializationRecoveries.values()].some(+ (recovery) =>+ recovery.sessionId === sessionId &&+ isRemoteOptimisticMaterializationRecoveryActive(recovery),+ ) ||// wake 型后台任务在跑 / 唤醒桥接中 — turn 间空窗但会话仍在工作,demote /// trim 掉会把 taskUpdates 清空,running 快照当场熄灭(等于把 bug 换个姿势复现)。// 远程会话豁免(与折算口径一致,保留 demote 这条自愈路径)。@@ -1588,9 +3236,7 @@ function leaveView(sessionId: string): void {setState(sessionId, (s) => ({...s,...(s.historyLoaded ? { historyLoaded: false } : {}),- ...(s.error- ? { error: null, usageLimitRecovery: null, errorRetryText: null }- : {}),+ ...(s.error ? { error: null, usageLimitRecovery: null, errorRetryText: null } : {}),}));}_trimMessagesIfNeeded(sessionId);@@ -1713,6 +3359,29 @@ function applyInputProjection(opts: { supersedeQueries?: boolean } = {},): void {if (!projection.sessionId) return;+ const knownClearBoundary = remoteInputClearBoundaryBySession.get(projection.sessionId);+ if (typeof knownClearBoundary === 'number') {+ const hasBoundary = Object.prototype.hasOwnProperty.call(projection, 'clearBoundaryMs');+ const incomingBoundary = hasBoundary+ ? normalizeAgentInputClearBoundaryMs(projection.clearBoundaryMs)+ : undefined;+ // Once a numeric clear token is known, a modern projection carrying an+ // older/null token is not authoritative for *any* field. Even an empty+ // stale projection could otherwise overwrite the new epoch's error or+ // lock state. An omitted field is the legacy-client compatibility path.+ if (+ hasBoundary &&+ (typeof incomingBoundary !== 'number' || incomingBoundary < knownClearBoundary)+ ) {+ return;+ }+ }+ // A clear projection is emitted before the sessions row patch. Observe it+ // before applying queue state or pumping the optimistic outbox, otherwise an+ // old local item can be re-enqueued into the freshly cleared context.+ if (Object.prototype.hasOwnProperty.call(projection, 'clearBoundaryMs')) {+ observeRemoteInputClearBoundary(projection.sessionId, projection.clearBoundaryMs);+ }if (opts.supersedeQueries !== false) {supersedeInputProjectionRequests(projection.sessionId);}@@ -1723,7 +3392,68 @@ function applyInputProjection(? 'supported': 'legacy';const projectedContinuationTurnClientId = projection.continuationTurnClientId ?? null;+ // A reconnect can briefly clear remoteProjectsStore. The projection still+ // belongs to the remote task during that window, so use the sticky origin+ // for optimistic settling/rollback semantics.+ const remoteProjection = isRemoteSessionSticky(projection.sessionId);+ const optimisticRecords = remoteOptimisticSendRecords(projection.sessionId);+ const projectedQueue = projection.pendingQueue as QueuedMessage[];+ const projectedIds = new Set(projectedQueue.map((item) => item.clientId));+ for (const queued of projectedQueue) {+ markRemoteOptimisticSendAccepted(projection.sessionId, queued.clientId, queued);+ cancelRemoteOptimisticSettlingRetirement(projection.sessionId, queued.clientId);+ }+ if (optimisticRecords) {+ for (const record of optimisticRecords.values()) {+ record.currentlyQueued = projectedIds.has(record.queued.clientId);+ }+ }+ let settlingClientIds: string[] = [];setState(projection.sessionId, (s) => {+ // DB created 可能先于 projection 回来;正式消息已经占据 transcript 的同一+ // clientId 位置时,不要让稍晚的旧 pendingQueue 再造一行重复队列项。+ const persistedMessageIds = new Set(+ s.messages.filter((message) => !message.isPendingPersist).map((message) => message.clientId),+ );+ const authoritativeQueue = projectedQueue.filter(+ (item) => !persistedMessageIds.has(item.clientId),+ );+ // 旧 projection 先到时保留仍在 enqueue RPC 在途中的本地 sending 行;+ // 一旦权威队列出现同 clientId,就由权威条目接管并移除本地标记。+ const authoritativeIds = new Set(authoritativeQueue.map((item) => item.clientId));+ const pendingQueue = [...authoritativeQueue];+ if (optimisticRecords) {+ for (const record of optimisticRecords.values()) {+ if (record.accepted || authoritativeIds.has(record.queued.clientId)) continue;+ if (s.messages.some((message) => message.clientId === record.queued.clientId)) continue;+ pendingQueue.push({ ...record.queued, isPendingEnqueue: true });+ }+ }++ // 队首连续出队 / steer 标记才进入 settling;中段删除不制造幽灵气泡。+ const currentQueueIds = new Set(pendingQueue.map((item) => item.clientId));+ let vanishedPrefixEnd = 0;+ while (+ vanishedPrefixEnd < s.pendingQueue.length &&+ !currentQueueIds.has(s.pendingQueue[vanishedPrefixEnd].clientId)+ ) {+ vanishedPrefixEnd += 1;+ }+ const locallyRemoved = remoteOptimisticLocallyRemoved.get(projection.sessionId);+ const previousSteeringIds = new Set(s.steeringQueueClientIds);+ const currentSteeringIds = new Set(projection.steeringQueueClientIds);+ const settlingQueueItems = s.pendingQueue.filter((item, index) => {+ if (!remoteProjection) return false;+ if (persistedMessageIds.has(item.clientId)) return false;+ if (currentQueueIds.has(item.clientId)) return false;+ if (locallyRemoved?.has(item.clientId)) return false;+ return (+ index < vanishedPrefixEnd ||+ previousSteeringIds.has(item.clientId) ||+ currentSteeringIds.has(item.clientId)+ );+ });+ settlingClientIds = settlingQueueItems.map((item) => item.clientId);// Only trigger if the retried message is still stuck in the pending queue:// projection.error is queue-level (string | null, no clientId), so we correlate// via pendingQueue. If the retry message was already dispatched and the agent@@ -1749,16 +3479,20 @@ function applyInputProjection(// 或派发失败回退 —— 这条不该同时以消息流气泡 + 队列灰字两种形态出现。撤回乐观// 气泡, 回落到队列态。真正被立即派发的那条 clientId 不在 pendingQueue 里, 气泡// 保留, 之后 localDb.messages.onCreated 广播按 clientId dedupe 不会重复。- const queuedIds = new Set(projection.pendingQueue.map((q) => q.clientId));+ const queuedIds = new Set(pendingQueue.map((q) => q.clientId));const dedupedMessages =queuedIds.size > 0 && s.messages.some((m) => m.isPendingPersist && queuedIds.has(m.clientId))? s.messages.filter((m) => !(m.isPendingPersist && queuedIds.has(m.clientId))): s.messages;+ const withSettlingMessages = settlingQueueItems.reduce<ChatMessage[]>((messages, item) => {+ if (messages.some((message) => message.clientId === item.clientId)) return messages;+ return [...messages, { ...item.chatMessage, isPendingPersist: true }];+ }, dedupedMessages);// 中断自愈接管中 → 在流末尾挂一条 ephemeral 的「正在自动继续」分隔条(不落库);// 接管结束(补发已发出 / 放弃 / 用户自己接手)由同一处撤掉。红横幅只留给最终失败,// 所以这几秒里 projection.error 是 null,用户看到的就只有这条低调提示。const autoResumePending = !!projection.autoResumePending;- const hasPendingCard = dedupedMessages.some(+ const hasPendingCard = withSettlingMessages.some((m) => m.clientId === AUTO_RESUME_PENDING_CLIENT_ID,);const pendingCardData = projection.autoResumePending@@ -1766,10 +3500,10 @@ function applyInputProjection(: null;const withPendingCard = autoResumePending? hasPendingCard- // 卡已在:必须把最新展示信息写回去 —— 同一次中断的进度会连续更新- // (1/5 → 2/5 …),原样保留旧卡的话进度永远停在第一次(copilot review)。- // 只在内容真的变了时才换引用,避免每次 projection 都触发无谓重渲染。- ? dedupedMessages.map((m) =>+ ? // 卡已在:必须把最新展示信息写回去 —— 同一次中断的进度会连续更新+ // (1/5 → 2/5 …),原样保留旧卡的话进度永远停在第一次(copilot review)。+ // 只在内容真的变了时才换引用,避免每次 projection 都触发无谓重渲染。+ withSettlingMessages.map((m) =>m.clientId === AUTO_RESUME_PENDING_CLIENT_ID &&pendingCardData &&!shallowEqualRecord(m.systemCardData, pendingCardData)@@ -1777,7 +3511,7 @@ function applyInputProjection(: m,): [- ...dedupedMessages,+ ...withSettlingMessages,{clientId: AUTO_RESUME_PENDING_CLIENT_ID,role: 'assistant' as const,@@ -1789,8 +3523,8 @@ function applyInputProjection(},]: hasPendingCard- ? dedupedMessages.filter((m) => m.clientId !== AUTO_RESUME_PENDING_CLIENT_ID)- : dedupedMessages;+ ? withSettlingMessages.filter((m) => m.clientId !== AUTO_RESUME_PENDING_CLIENT_ID)+ : withSettlingMessages;// 折叠:同一次中断事件里,ephemeral 进行中行与它前面那些已落库的重连行只显示最新// 一条(否则第 2 次重连时会看到「未成功」+「重新连接中 2/5」两行并存)。const messages = collapseConsecutiveAutoResumeRows(withPendingCard);@@ -1804,7 +3538,7 @@ function applyInputProjection(return {...s,messages,- pendingQueue: projection.pendingQueue as QueuedMessage[],+ pendingQueue,steeringQueueClientIds: projection.steeringQueueClientIds,queuePaused: projection.queuePaused,queueExpanded: projection.queueExpanded,@@ -1829,28 +3563,133 @@ function applyInputProjection(...(authRetryProjectionError ? { _authRetryPersistOnProjectionError: undefined } : {}),};});+ for (const clientId of settlingClientIds) {+ scheduleRemoteOptimisticSettlingRetirement(projection.sessionId, clientId);+ }+ if (optimisticRecords) {+ const current = getOrCreateState(projection.sessionId);+ for (const [clientId, record] of optimisticRecords) {+ record.currentlyQueued = current.pendingQueue.some(+ (item) => item.clientId === clientId && item.isPendingEnqueue !== true,+ );+ if (!record.accepted || record.currentlyQueued) continue;+ const hasPendingMessage = current.messages.some(+ (message) => message.clientId === clientId && message.isPendingPersist,+ );+ if (hasPendingMessage) {+ scheduleRemoteOptimisticSettlingRetirement(projection.sessionId, clientId);+ } else {+ clearRemoteOptimisticSend(projection.sessionId, clientId);+ }+ }+ }+ if (remoteProjection) void pumpRemoteOptimisticSends(projection.sessionId);}function markSessionHasUserMessage(sessionId: string): void {+ // A late DB acknowledgement must not recreate a session slice that was+ // already purged by delete/archive/LRU cleanup.+ if (!sessions.has(sessionId)) return;setState(sessionId, (s) => {if (!s.isFirstMessage) return s;return { ...s, isFirstMessage: false };});}-function requestInputProjection(sessionId: string): void {- if (!sessionId) return;- if (typeof window === 'undefined' || !window.electronAPI?.maker?.input?.getProjection) return;- const origin = remoteProjectsStore.getSessionDeviceId(sessionId);+function requestInputProjection(+ sessionId: string,+ pinnedDeviceId?: string,+): Promise<InputProjectionRequestResult | undefined> {+ if (!sessionId) return Promise.resolve(undefined);+ const origin = pinnedDeviceId ?? getStickySessionDeviceId(sessionId);+ if (origin) {+ const existing = remoteInputProjectionRequests.get(sessionId);+ if (+ existing &&+ !existing.settled &&+ existing.deviceId === origin &&+ isDataOwnerGenerationCurrent(existing.dataOwner) &&+ (rendererClearGenerationBySession.get(sessionId) ?? 0) === existing.clearGeneration+ ) {+ return existing.promise;+ }+ } else if (typeof window === 'undefined' || !window.electronAPI?.maker?.input?.getProjection) {+ return Promise.resolve(undefined);+ }++ const dataOwner = getDataOwnerGeneration();const epoch = beginInputProjectionRequest(sessionId, origin);- const api = makerApiFor(sessionId);- api.input- .getProjection(sessionId)- .then((projection) => {- if (!isCurrentInputProjectionRequest(sessionId, origin, epoch)) return;- applyInputProjection(projection, { supersedeQueries: false });- })- .catch((err) => log.warn('get input projection failed:', err));+ const clearGeneration = rendererClearGenerationBySession.get(sessionId) ?? 0;+ const api = origin ? makerApiForDevice(origin) : makerApiFor(sessionId);+ let request!: RemoteInputProjectionRequest;+ let promise: Promise<InputProjectionRequestResult>;+ try {+ promise = api.input.getProjection(sessionId).then(+ (projection) => {+ request.settled = true;+ const current = isCurrentInputProjectionRequest(sessionId, origin, epoch, dataOwner);+ if (origin && current) {+ noteRemoteInputProjectionSuccess(+ sessionId,+ origin,+ dataOwner,+ clearGeneration,+ projection,+ );+ }+ if (current) {+ applyInputProjection(projection, { supersedeQueries: false });+ }+ return { projection, current };+ },+ (error) => {+ request.settled = true;+ if (origin && isCurrentInputProjectionRequest(sessionId, origin, epoch, dataOwner)) {+ noteRemoteInputProjectionFailure(sessionId, origin, dataOwner, clearGeneration, error);+ }+ throw error;+ },+ );+ } catch (error) {+ const rejected = Promise.reject<InputProjectionRequestResult>(error);+ request = {+ deviceId: origin ?? '',+ dataOwner,+ clearGeneration,+ settled: true,+ promise: rejected,+ };+ if (origin && isCurrentInputProjectionRequest(sessionId, origin, epoch, dataOwner)) {+ noteRemoteInputProjectionFailure(sessionId, origin, dataOwner, clearGeneration, error);+ }+ void rejected.catch((err) => log.warn('get input projection failed:', err));+ return rejected;+ }+ request = {+ deviceId: origin ?? '',+ dataOwner,+ clearGeneration,+ settled: false,+ promise,+ };+ if (origin) remoteInputProjectionRequests.set(sessionId, request);+ // Keep cleanup/logging detached from the returned chain. The outbox awaits+ // the one-hop result above, so a fast projection still reaches dispatch in+ // the same microtask budget as the former direct probe.+ void promise.then(+ () => {+ if (origin && remoteInputProjectionRequests.get(sessionId) === request) {+ remoteInputProjectionRequests.delete(sessionId);+ }+ },+ (err) => {+ if (origin && remoteInputProjectionRequests.get(sessionId) === request) {+ remoteInputProjectionRequests.delete(sessionId);+ }+ log.warn('get input projection failed:', err);+ },+ );+ return promise;}// ---------------------------------------------------------------------------@@ -2122,7 +3961,7 @@ function normalizeAgentTaskUpdate(? 'codex': source === 'pi'? 'pi'- : 'claude-code';+ : 'claude-code';const usageRaw =raw.usage && typeof raw.usage === 'object' ? (raw.usage as Record<string, unknown>) : null;const usage = usageRaw@@ -2640,8 +4479,7 @@ export function handleStreamEvent(const existingUpdatableToolIdx =toolName === 'update_plan' || toolName === 'web_search'? finalized.messages.findIndex(- (m) =>- m.role === 'tool_use' && m.toolName === toolName && m.toolUseId === toolUseId,+ (m) => m.role === 'tool_use' && m.toolName === toolName && m.toolUseId === toolUseId,): -1;if (existingUpdatableToolIdx >= 0) {@@ -2760,20 +4598,21 @@ export function handleStreamEvent(return next;});- const terminalData =- event.data as { plan?: unknown; raw?: { id?: unknown; status?: unknown } } | null | undefined;+ const terminalData = event.data as+ { plan?: unknown; raw?: { id?: unknown; status?: unknown } } | null | undefined;const terminalTurnId = typeof terminalData?.raw?.id === 'string' ? terminalData.raw.id : null;const terminalTurnStatus =typeof terminalData?.raw?.status === 'string' ? terminalData.raw.status : null;- const doneMessages = event.source === 'codex'- ? applyCodexPlanSnapshotOnDone(- cleanedMessages,- terminalData?.plan,- terminalTurnId,- terminalTurnStatus,- Date.now(),- ).messages- : cleanedMessages;+ const doneMessages =+ event.source === 'codex'+ ? applyCodexPlanSnapshotOnDone(+ cleanedMessages,+ terminalData?.plan,+ terminalTurnId,+ terminalTurnStatus,+ Date.now(),+ ).messages+ : cleanedMessages;// F1-a Option C: tool-result-image 孤儿 flush(turn 末残留 pendingFullText)已收口// main(messagePersistBroadcaster.flushOrphanToolResults),落库后经 onCreated append@@ -3478,8 +5317,51 @@ type MakerEventPayload = {resolvedContent?: string;} | null;+/** Metadata carried beside a live main → renderer or device-link push. */+type LiveIngressContext = {+ ownerStamp?: unknown;+ remoteDeviceId?: string;+ ownerStampPresent?: boolean;+};++function isCurrentLiveIngress(context?: LiveIngressContext): boolean {+ if (!context) return true;+ const hasStamp = context.ownerStampPresent ?? context.ownerStamp !== undefined;+ if (!context.remoteDeviceId) {+ // Older preload builds did not expose Electron's third IPC argument. Keep+ // their local event stream compatible; stamped frames are fail-closed.+ return !hasStamp || isDataOwnerPushStampCurrent(context.ownerStamp);+ }++ return isRemoteDataOwnerPushCurrent(+ context.remoteDeviceId,+ context.ownerStamp,+ hasStamp,+ );+}++function isCurrentLocalLiveIngress(ownerStamp: unknown): boolean {+ return isCurrentLiveIngress({+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ });+}++function sameLiveIngressScope(a: LiveIngressContext, b: LiveIngressContext): boolean {+ if (a.remoteDeviceId !== b.remoteDeviceId) return false;+ const aStamp = isDataOwnerPushStamp(a.ownerStamp) ? a.ownerStamp : null;+ const bStamp = isDataOwnerPushStamp(b.ownerStamp) ? b.ownerStamp : null;+ if (aStamp === null || bStamp === null) return aStamp === bStamp;+ return (+ aStamp.dataOwnerId === bStamp.dataOwnerId &&+ aStamp.ownerGeneration === bStamp.ownerGeneration+ );+}+type PendingTextDeltaBatch = {text: string;+ dataOwner: DataOwnerGeneration;+ ingress: LiveIngressContext;source?: 'claude-code' | 'codex' | 'pi';persistId?: string;agentMeta?: Record<string, unknown>;@@ -3494,11 +5376,20 @@ let textDeltaFlushTimer: ReturnType<typeof setTimeout> | null = null;* the teardown list.*/function bindIpc(- subscribe: (cb: (data: unknown) => void) => unknown,- handler: (data: unknown) => void,+ subscribe: unknown,+ handler: (data: unknown, ownerStamp?: unknown) => void,label: string,): void {- const result = subscribe(handler);+ if (typeof subscribe !== 'function') {+ log.warn(`${label}: subscribe is not available; teardown will no-op`);+ ipcUnsubscribers.push(() => {});+ return;+ }+ const result = (+ subscribe as (+ cb: (data: unknown, ownerStamp?: unknown) => void,+ ) => unknown+ )(handler);if (typeof result === 'function') {ipcUnsubscribers.push(result as () => void);} else {@@ -3513,9 +5404,7 @@ function isTextDeltaEvent(event: NonNullable<MakerEventPayload>['event']): boolereturn data?.isFinal === false && typeof data.text === 'string';}-function isHighFrequencyStreamEvent(- event: NonNullable<MakerEventPayload>['event'],-): boolean {+function isHighFrequencyStreamEvent(event: NonNullable<MakerEventPayload>['event']): boolean {return (!!event &&(event.type === 'tool_use' ||@@ -3563,6 +5452,13 @@ function flushPendingTextDelta(sessionId: string, deferNotification = false): vopendingTextDeltaBatches.delete(sessionId);if (pendingTextDeltaBatches.size === 0) clearTextDeltaFlushTimer();+ if (+ !isDataOwnerGenerationCurrent(pending.dataOwner) ||+ !isCurrentLiveIngress(pending.ingress)+ ) {+ return;+ }+dispatchStreamEventPayload(sessionId,{@@ -3597,11 +5493,21 @@ function enqueueTextDeltaPayload(sessionId: string,event: NonNullable<MakerEventPayload>['event'],persistId?: string,+ ingress: LiveIngressContext = {},): void {if (!event) return;const data = event.data as { text?: unknown };const text = typeof data.text === 'string' ? data.text : '';- const existing = pendingTextDeltaBatches.get(sessionId);+ const dataOwner = getDataOwnerGeneration();+ let existing = pendingTextDeltaBatches.get(sessionId);+ if (+ existing &&+ (!isDataOwnerGenerationCurrent(existing.dataOwner) ||+ !sameLiveIngressScope(existing.ingress, ingress))+ ) {+ discardPendingTextDelta(sessionId);+ existing = undefined;+ }if (existing) {existing.text += text;if (!existing.persistId && persistId) existing.persistId = persistId;@@ -3610,6 +5516,8 @@ function enqueueTextDeltaPayload(} else {pendingTextDeltaBatches.set(sessionId, {text,+ dataOwner,+ ingress,source: event.source,persistId,...(event.agentMeta ? { agentMeta: event.agentMeta } : {}),@@ -3849,7 +5757,9 @@ function initGlobalListeners(): void {// handleStreamEvent / handleStatusUpdate 不需改动。// device-link:同一个 handler 既接本机 maker:event,也接被控端经 onRemotePush// 转发回来的远程 maker:event(按 sessionId 命中同一 reducer,与来源无关)。- const handleMakerEventRaw = (raw: unknown) => {+ const handleMakerEventRaw = (raw: unknown, ingress: LiveIngressContext = {}) => {+ if (!isCurrentLiveIngress(ingress)) return;+ const dataOwnerAtIngress = getDataOwnerGeneration();const payload = raw as MakerEventPayload;if (!payload?.sessionId || !payload.event) return;const { sessionId, event } = payload;@@ -3857,7 +5767,7 @@ function initGlobalListeners(): void {const resolvedContent = payload.resolvedContent;if (isTextDeltaEvent(event)) {- enqueueTextDeltaPayload(sessionId, event, persistId);+ enqueueTextDeltaPayload(sessionId, event, persistId, ingress);return;}const deferNotification = isHighFrequencyStreamEvent(event);@@ -3870,6 +5780,7 @@ function initGlobalListeners(): void {const current = getOrCreateState(sessionId);if (current.sdkSessionId === sdkSessionId) return;setState(sessionId, (s) => ({ ...s, sdkSessionId }));+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;sessionService.update(sessionId, { sdkSessionId }).catch((err) => log.warn('Failed to persist sdkSessionId:', err));@@ -3945,20 +5856,24 @@ function initGlobalListeners(): void {);void (async () => {try {+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;// 本地 only:网关 key 不再有服务器副本可拉。改为校验本机 safeStorage 是否// 有 key —— 有则关闭并重发会话(重连时把本机 key 重新下发给 remote host);// 没有则中止重试,让 error banner 浮现,提示用户在本机重填 key。const localKey = await window.electronAPI.safeStorageRead(providerSecretStorageKey('xd'),);+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;if (!localKey) {throw new Error('no local api key available');}// preserveWorkspace: 鉴权重连是瞬态 close+resend,会话继续,工作区必须保留。await makerApiFor(sessionId).closeSession(sessionId, { preserveWorkspace: true });await new Promise((r) => setTimeout(r, 1500));+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;if (hasRetryPayload) {const row = await sessionService.get(sessionId);+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;if (row.workingDir && row.model) {const retryAccepted = await sendMessage(sessionId,@@ -3989,6 +5904,7 @@ function initGlobalListeners(): void {throw new Error('no retry payload');}} catch {+ if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;// 重试失败——main 侧已跳过持久化(isRemoteAuthRetry),在此补落。// device-link 控制端经 makerApiFor 路由到被控端 main(不直调本地 IPC);// 同时透传 agentMeta 供 flushAssistantBlock 边界 meta 兜底与 dedup key。@@ -4005,7 +5921,9 @@ function initGlobalListeners(): void {supersedeInputProjectionOnTerminalEvent(sessionId, terminalErrorEvent);setState(sessionId, (s) => handleStreamEvent(s, terminalErrorEvent));} finally {- setState(sessionId, (s) => ({ ...s, _authRetryInFlight: false }));+ if (isDataOwnerGenerationCurrent(dataOwnerAtIngress)) {+ setState(sessionId, (s) => ({ ...s, _authRetryInFlight: false }));+ }}})();return;@@ -4036,16 +5954,18 @@ function initGlobalListeners(): void {}}- dispatchStreamEventPayload(- sessionId,- event,- persistId,- resolvedContent,- deferNotification,- );+ dispatchStreamEventPayload(sessionId, event, persistId, resolvedContent, deferNotification);// done / error 副作用 (从老 stream listener 搬过来)if (event.type === 'done') {+ if (+ event.source === 'codex' &&+ (event.data as { silentStop?: boolean } | null | undefined)?.silentStop !== true+ ) {+ // Codex 的 plan_review 跨 done 存活。done 会先作废旧快照,因此立即另起一代+ // Host 权威快照,补回 live push 丢失时的审批卡;fire-and-forget 不阻塞流 reducer。+ void reconcilePendingInteractions(sessionId).catch(() => undefined);+ }titleUpdateCallbacks.get(sessionId)?.();// A successful turn means auth recovered — reset the consecutive auth-retry// counter so a future 401 can auto-retry again.@@ -4092,7 +6012,15 @@ function initGlobalListeners(): void {// 本地会话则直接让 error banner 浮现,提示用户在设置里重填 key。}};- bindIpc(window.electronAPI.maker.onEvent, handleMakerEventRaw, 'maker-event');+ bindIpc(+ window.electronAPI.maker.onEvent,+ (raw, ownerStamp) =>+ handleMakerEventRaw(raw, {+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ }),+ 'maker-event',+ );// ── Maker session status: 兜底护栏, 防 "Generating..." 永久卡死 ────────────// main 端 session.close() 跑完会 broadcast status_changed: closed; renderer@@ -4103,16 +6031,31 @@ function initGlobalListeners(): void {// 触发 close 的路径很多(rehydrate / disableOrca / shutdown / 隐藏的 IPC 调用),// 真正的"凶手"还在用 [DEBUG-TEMP] 日志追。这条护栏不依赖修好 close 路径,// 只要 main 端把 closed 状态广播出来, 就保证 UI 一定能解锁。- const handleMakerStatusRaw = (raw: unknown) => {+ const handleMakerStatusRaw = (raw: unknown, ingress: LiveIngressContext = {}) => {+ if (!isCurrentLiveIngress(ingress)) return;const payload = raw as { sessionId?: string; status?: string } | null;if (!payload?.sessionId || payload.status !== 'closed') return;+ bumpInteractionReconcileEpoch(payload.sessionId);supersedeInputProjectionRequests(payload.sessionId, { supersedeOperations: true });flushPendingTextDelta(payload.sessionId);setState(payload.sessionId, forceFinalizeOnSessionClosed);};- bindIpc(window.electronAPI.maker.onStatusChanged, handleMakerStatusRaw, 'maker-status-changed');+ bindIpc(+ window.electronAPI.maker.onStatusChanged,+ (raw, ownerStamp) =>+ handleMakerStatusRaw(raw, {+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ }),+ 'maker-status-changed',+ );- const handleInputProjectionRaw = (raw: unknown, sourceDeviceId?: string) => {+ const handleInputProjectionRaw = (+ raw: unknown,+ sourceDeviceId?: string,+ ingress: LiveIngressContext = {},+ ) => {+ if (!isCurrentLiveIngress(ingress)) return;const projection = raw as AgentInputProjection | null;if (!projection?.sessionId) return;if (@@ -4125,12 +6068,20 @@ function initGlobalListeners(): void {};bindIpc(window.electronAPI.maker.onInputProjection,- handleInputProjectionRaw,+ (raw, ownerStamp) =>+ handleInputProjectionRaw(raw, undefined, {+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ }),'maker-input-projection',);// ── Maker interaction request: permission/ask/plan 三合一,按 kind 分发 ──- const handleInteractionRequestRaw = (raw: unknown) => {+ const handleInteractionRequestRaw = (+ raw: unknown,+ ingress: LiveIngressContext = {},+ ) => {+ if (!isCurrentLiveIngress(ingress)) return;const payload = raw as {sessionId?: string;request?: { kind: string; requestId: string; [k: string]: unknown };@@ -4250,8 +6201,7 @@ function initGlobalListeners(): void {// (`CindyRegion & unknown` 仍是 `CindyRegion`),那样写会让 TS 以为 IPC 传来的// region 已经是合法值,下面的白名单校验看着像在校验、实际没有类型层面的约束。const rawEnv = request.env as- | (Omit<PendingIssueConfirm['env'], 'region'> & { region?: unknown })- | undefined;+ (Omit<PendingIssueConfirm['env'], 'region'> & { region?: unknown }) | undefined;const submissionIdentity = parseIssueSubmissionIdentity(request.submissionIdentity);if (!draft || !rawEnv || !submissionIdentity) return;const suggestedPublicName =@@ -4296,9 +6246,25 @@ function initGlobalListeners(): void {return;}};++ const handleLiveInteractionRequestRaw = (+ raw: unknown,+ ingress: LiveIngressContext = {},+ ) => {+ if (!isCurrentLiveIngress(ingress)) return;+ const sessionId = (raw as { sessionId?: unknown } | null)?.sessionId;+ if (typeof sessionId === 'string' && sessionId.length > 0) {+ bumpInteractionReconcileEpoch(sessionId);+ }+ handleInteractionRequestRaw(raw, ingress);+ };bindIpc(window.electronAPI.maker.onInteractionRequest,- handleInteractionRequestRaw,+ (raw, ownerStamp) =>+ handleLiveInteractionRequestRaw(raw, {+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ }),'maker-interaction-request',);// 模块级桥接:供 reconcilePendingInteractions(打开/重连会话时的快照重建)复用同一套@@ -4306,7 +6272,11 @@ function initGlobalListeners(): void {applyInteractionRequestRef = handleInteractionRequestRaw;// ── Maker interaction dismissed: setPermissionMode 切换 / close 时关掉对话框 ──- const handleInteractionDismissedRaw = (raw: unknown) => {+ const handleInteractionDismissedRaw = (+ raw: unknown,+ ingress: LiveIngressContext = {},+ ) => {+ if (!isCurrentLiveIngress(ingress)) return;const payload = raw as { sessionId?: string; requestId?: string; reason?: string } | null;if (!payload?.sessionId || !payload.requestId) return;// 老 CCAgentPermissionDismissedPayload 要 reason / resolvedAs union 字面值。@@ -4333,21 +6303,41 @@ function initGlobalListeners(): void {handleStreamEvent(s, { sessionId, type: 'permission_dismissed', data }),);};+ const handleLiveInteractionDismissedRaw = (+ raw: unknown,+ ingress: LiveIngressContext = {},+ ) => {+ if (!isCurrentLiveIngress(ingress)) return;+ const sessionId = (raw as { sessionId?: unknown } | null)?.sessionId;+ if (typeof sessionId === 'string' && sessionId.length > 0) {+ bumpInteractionReconcileEpoch(sessionId);+ }+ handleInteractionDismissedRaw(raw, ingress);+ };bindIpc(window.electronAPI.maker.onInteractionDismissed,- handleInteractionDismissedRaw,+ (raw, ownerStamp) =>+ handleLiveInteractionDismissedRaw(raw, {+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ }),'maker-interaction-dismissed',);// Main 端写库的消息推送(接管路径 persistUserMessage / persistAssistantMessage),也复用给// device-link 远程会话(被控端 messages:created 经 onRemotePush 转发,注入同一套 in-memory state)。- function handleMessageCreatedRaw(raw: unknown): void {+ function handleMessageCreatedRaw(+ raw: unknown,+ ingress: LiveIngressContext = {},+ ): void {+ if (!isCurrentLiveIngress(ingress)) return;const payload = raw as { sessionId?: string; message?: Message } | null;if (!payload?.sessionId || !payload.message) return;const { sessionId, message } = payload;if (isBeforeOrAtRendererClearBoundary(sessionId, message.createdAt)) return;const [mapped] = mapServerMessages([message]);if (!mapped) return;+ clearRemoteOptimisticSend(sessionId, mapped.clientId);const current = getOrCreateState(sessionId);const existing = current.messages.find((candidate) => candidate.clientId === mapped.clientId);const isLiveToolEcho =@@ -4376,11 +6366,7 @@ function initGlobalListeners(): void {// 回声都对不断增长的整段消息重新遍历并排序,1,500+ 行时拖死 Renderer。// 仅限 tool 行:thinking 的 persisted createdAt 会回填块开始时间,必须让// mergeMessages 重排;assistant 等其它角色也保留原有权威时间线语义。- const hydrated = hydratePersistedMessage(- existing,- mapped,- hydrateOptions,- );+ const hydrated = hydratePersistedMessage(existing, mapped, hydrateOptions);if (hydrated === existing) return s;const nextMessages = s.messages.slice();nextMessages[existingIdx] = hydrated;@@ -4391,10 +6377,12 @@ function initGlobalListeners(): void {};}const nextMessages = mergeMessages([mapped], s.messages, hydrateOptions);- if (nextMessages === s.messages) return s;+ const pendingQueue = s.pendingQueue.filter((item) => item.clientId !== mapped.clientId);+ if (nextMessages === s.messages && pendingQueue.length === s.pendingQueue.length) return s;return {...s,messages: nextMessages,+ pendingQueue,isFirstMessage: mapped.role === 'user' ? false : s.isFirstMessage,};},@@ -4408,7 +6396,11 @@ function initGlobalListeners(): void {// 消息本地删除推送:本机多窗口与 device-link 控制端共用同一 reducer。// 新 payload 一次带齐整轮 clientIds;旧 host 仍回退到单个 clientId。- function handleMessageDeletedRaw(raw: unknown): void {+ function handleMessageDeletedRaw(+ raw: unknown,+ ingress: LiveIngressContext = {},+ ): void {+ if (!isCurrentLiveIngress(ingress)) return;const payload = raw as {sessionId?: string;clientId?: string;@@ -4425,7 +6417,11 @@ function initGlobalListeners(): void {removeMessagesByClientIds(payload.sessionId, clientIds);}- function handleUsageMessageTurnCostRaw(raw: unknown): void {+ function handleUsageMessageTurnCostRaw(+ raw: unknown,+ ingress: LiveIngressContext = {},+ ): void {+ if (!isCurrentLiveIngress(ingress)) return;const p = raw as {sessionId?: string;clientId?: string;@@ -4443,17 +6439,11 @@ function initGlobalListeners(): void {const normalizedTurnMoney = normalizeRegionalMoney(p.turnMoney);const legacyTurnCostUsd =typeof p.turnCostUsd === 'number' && p.turnCostUsd > 0- ? resolveEstimatedTurnCostUsd(- p.turnCostUsd,- turnCostIsEstimate,- turnUsageDetails,- )+ ? resolveEstimatedTurnCostUsd(p.turnCostUsd, turnCostIsEstimate, turnUsageDetails): undefined;const turnMoney =normalizedTurnMoney ??- (legacyTurnCostUsd !== undefined- ? legacyUsdMoney(legacyTurnCostUsd)- : undefined);+ (legacyTurnCostUsd !== undefined ? legacyUsdMoney(legacyTurnCostUsd) : undefined);const { sessionId, clientId } = p;// 用户轮累计与当前 segment 金额是**两个独立事实**,必须各自判定 —— 一次用户请求// 含多个 SDK segment 时,前面的 segment 有真实费用、收尾 segment 缺报价,payload@@ -4493,10 +6483,7 @@ function initGlobalListeners(): void {});return;}- const resolvedTurnCostUsd =- turnMoney.currency === 'USD'- ? turnMoney.amount- : undefined;+ const resolvedTurnCostUsd = turnMoney.currency === 'USD' ? turnMoney.amount : undefined;setState(sessionId, (s) => {const idx = s.messages.findIndex((m) => m.clientId === clientId);if (idx < 0) return s;@@ -4504,9 +6491,7 @@ function initGlobalListeners(): void {msgs[idx] = {...msgs[idx],turnMoney,- ...(resolvedTurnCostUsd !== undefined- ? { turnCostUsd: resolvedTurnCostUsd }- : {}),+ ...(resolvedTurnCostUsd !== undefined ? { turnCostUsd: resolvedTurnCostUsd } : {}),turnCostIsEstimate,...userTurnCostPatch,...(turnUsageDetails ? { turnUsageDetails } : {}),@@ -4517,7 +6502,11 @@ function initGlobalListeners(): void {// 模型降级标记实时推送(main 的 modelMismatchBroadcaster,与 turn-cost 同款// 「落库 agent_meta + 广播」两路;历史加载路径由 buildChatMessages 兜底)。- function handleUsageMessageModelMismatchRaw(raw: unknown): void {+ function handleUsageMessageModelMismatchRaw(+ raw: unknown,+ ingress: LiveIngressContext = {},+ ): void {+ if (!isCurrentLiveIngress(ingress)) return;const p = raw as {sessionId?: string;clientId?: string;@@ -4552,43 +6541,90 @@ function initGlobalListeners(): void {bindIpc(// 可选调用兜底:测试 / HMR 先于 main 重启时 window.electronAPI.deviceLink 可能尚未注入,// 直接取 .onRemotePush 会让 initGlobalListeners 整体崩掉(与下方 onUsageMessageTurnCost 同款防御)。- (cb) => window.electronAPI.deviceLink?.onRemotePush?.(cb),- (raw) => {- const push = raw as { deviceId?: string; channel?: string; payload?: unknown } | null;+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.deviceLink?.onRemotePush?.(cb),+ (raw, localOwnerStamp) => {+ if (!isCurrentLocalLiveIngress(localOwnerStamp)) return;+ const push = raw as {+ deviceId?: string;+ channel?: string;+ payload?: unknown;+ ownerStamp?: unknown;+ } | null;if (!push?.channel) return;+ const remoteIngress: LiveIngressContext = push.deviceId+ ? {+ remoteDeviceId: push.deviceId,+ ownerStamp: push.ownerStamp,+ ownerStampPresent: Object.prototype.hasOwnProperty.call(push, 'ownerStamp'),+ }+ : {};+ if (!isCurrentLiveIngress(remoteIngress)) return;+ const inboundPayload = push.payload as {+ sessionId?: string;+ patch?: Record<string, unknown>;+ } | null;+ const inboundSid = inboundPayload?.sessionId;+ const terminalPatch =+ push.channel === 'local-db:sessions:patched' &&+ push.deviceId !== undefined &&+ typeof inboundSid === 'string' &&+ (inboundPayload?.patch?.status === 'deleted' ||+ inboundPayload?.patch?.status === 'archived');+ // A terminal patch itself establishes the tombstone. Every later frame+ // for that device/session is ignored until an authoritative active+ // snapshot proves an archived task was explicitly restored.+ if (terminalPatch) {+ markRemoteTerminalSessionTombstone(+ push.deviceId!,+ inboundSid!,+ inboundPayload?.patch?.status as 'deleted' | 'archived',+ );+ } else if (+ push.deviceId &&+ inboundSid &&+ isRemoteTerminalSessionTombstoned(inboundSid, push.deviceId)+ ) {+ if (+ push.channel === 'local-db:sessions:patched' &&+ inboundPayload?.patch?.status === 'active'+ ) {+ requestRemoteReseed(push.deviceId);+ }+ return;+ }// stall 看门狗信号:只用重会话流刷新 lastInboundEventAt。列表级轻量 activity/patch// 可能仍在持续抵达,但 maker:event 重 topic 已经断流;若这里也刷新会掩盖卡死。- const inboundSid = (push.payload as { sessionId?: string } | null)?.sessionId;if (inboundSid && isRemoteHeavyInboundChannel(push.channel)) _markInboundEvent(inboundSid);switch (push.channel) {case 'maker:event':- handleMakerEventRaw(push.payload);+ handleMakerEventRaw(push.payload, remoteIngress);break;case 'maker:status-changed':- handleMakerStatusRaw(push.payload);+ handleMakerStatusRaw(push.payload, remoteIngress);break;case 'maker:input:projection':if (!push.deviceId) break;- handleInputProjectionRaw(push.payload, push.deviceId);+ handleInputProjectionRaw(push.payload, push.deviceId, remoteIngress);break;case 'maker:interaction-request':- handleInteractionRequestRaw(push.payload);+ handleLiveInteractionRequestRaw(push.payload, remoteIngress);break;case 'maker:interaction-dismissed':- handleInteractionDismissedRaw(push.payload);+ handleLiveInteractionDismissedRaw(push.payload, remoteIngress);break;case 'local-db:messages:created':// 远程会话的持久化消息(接管路径)→ 注入 in-memory state(同本机)。- handleMessageCreatedRaw(push.payload);+ handleMessageCreatedRaw(push.payload, remoteIngress);break;case 'local-db:messages:deleted':- handleMessageDeletedRaw(push.payload);+ handleMessageDeletedRaw(push.payload, remoteIngress);break;case 'usage:message-turn-cost':- handleUsageMessageTurnCostRaw(push.payload);+ handleUsageMessageTurnCostRaw(push.payload, remoteIngress);break;case 'usage:message-model-mismatch':- handleUsageMessageModelMismatchRaw(push.payload);+ handleUsageMessageModelMismatchRaw(push.payload, remoteIngress);break;case 'usage:session-spend-changed': {// 被控端 session 终身累计 cost 落库推送(sessionSpendBroadcaster 走裸 UPDATE、@@ -4609,9 +6645,7 @@ function initGlobalListeners(): void {if (push.deviceId && p?.sessionId && totalMoney) {remoteProjectsStore.applyPatch(push.deviceId, p.sessionId, {totalMoney,- ...(typeof p.totalCostUsd === 'number'- ? { totalCostUsd: p.totalCostUsd }- : {}),+ ...(typeof p.totalCostUsd === 'number' ? { totalCostUsd: p.totalCostUsd } : {}),});}break;@@ -4636,11 +6670,29 @@ function initGlobalListeners(): void {// 被控端会话元数据 / 设置变更 → 就地镜像到远程项目分片(取代乐观覆盖)。const p = push.payload as { sessionId?: string; patch?: Record<string, unknown> } | null;if (push.deviceId && p?.sessionId && p.patch) {+ const terminal = p.patch.status === 'deleted' || p.patch.status === 'archived';+ if (!terminal && isRemoteTerminalSessionTombstoned(p.sessionId, push.deviceId)) {+ if (p.patch.status === 'active') requestRemoteReseed(push.deviceId);+ break;+ }+ const ownsSession = getStickySessionDeviceId(p.sessionId) === push.deviceId;+ if (Object.prototype.hasOwnProperty.call(p.patch, 'clearedAt')) {+ observeRemoteInputClearBoundary(p.sessionId, p.patch.clearedAt);+ }remoteProjectsStore.applyPatch(push.deviceId, p.sessionId, p.patch);+ if (terminal && ownsSession) {+ // A background task can be deleted or archived from another+ // controller while this renderer still owns an offline outbox.+ // Retire it at the authoritative push boundary so reconnect+ // cannot dispatch into a task that no longer exists.+ removeRemoteSessionActivityEntry(p.sessionId);+ _purgeSession(p.sessionId);+ break;+ }// fast 开关读 chat in-memory,分片更新不灌它 → 这里把 fastMode 同步进来(以被控端为准)。mirrorSessionFields(p.sessionId, p.patch);// 会话在被控端被删除 / 归档 → 同步清掉活动镜像,避免孤儿状态点。- if (p.patch.status === 'deleted' || p.patch.status === 'archived') {+ if (terminal) {removeRemoteSessionActivityEntry(p.sessionId);}}@@ -4717,10 +6769,92 @@ function initGlobalListeners(): void {// 把启动竞速里以 origin=undefined 误命中本机空库的已打开远程会话重载一次(经隧道拉真历史)。// 纯来源漂移驱动,正常 patched 推送(current===loaded)不误重载。teardown 时随其它监听一并清。{- const unsub = remoteProjectsStore.subscribe(reconcileOpenSessionOrigins);+ const unsub = remoteProjectsStore.subscribe(() => {+ // Snapshot/reseed can be the first clear signal (the projection or patch+ // may have been dropped). Reconcile boundaries before any subscriber or+ // outbox pump can observe the new shard.+ observeRemoteInputClearBoundariesFromSnapshot();+ releaseArchivedRemoteTerminalTombstones();+ reconcileOpenSessionOrigins();+ // A remote shard can be reseeded before the relay presence event reaches+ // this renderer. Treat that as a reconnect edge for the in-memory outbox.+ const remoteOutboxSessionIds = new Set([+ ...remoteOptimisticSends.keys(),+ ...remoteClearFences.keys(),+ ]);+ for (const sessionId of remoteOutboxSessionIds) {+ clearRemoteInputProjectionProbeFailure(sessionId);+ void retryRemoteClearFence(sessionId);+ void pumpRemoteOptimisticSends(sessionId);+ }+ });ipcUnsubscribers.push(typeof unsub === 'function' ? unsub : () => {});}+ // device-link exposes both the relay status and per-device presence. They+ // are optional in older test bridges / older preload snapshots, so a missing+ // callback must not prevent the rest of the maker listeners from installing.+ bindIpc(+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.deviceLink?.onStatusChanged?.(cb as never),+ (raw, ownerStamp) => {+ if (+ !isCurrentLiveIngress({+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ })+ ) {+ return;+ }+ const status = (raw as { status?: string } | null)?.status;+ if (status !== 'online') return;+ const remoteOutboxSessionIds = new Set([+ ...remoteOptimisticSends.keys(),+ ...remoteClearFences.keys(),+ ]);+ for (const sessionId of remoteOutboxSessionIds) {+ clearRemoteInputProjectionProbeFailure(sessionId);+ void retryRemoteClearFence(sessionId);+ pumpRemoteOptimisticSendsAfterCurrent(sessionId);+ }+ },+ 'device-link-status-changed-for-outbox',+ );+ bindIpc(+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.deviceLink?.onPresenceChanged?.(cb as never),+ (raw, ownerStamp) => {+ if (+ !isCurrentLiveIngress({+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ })+ ) {+ return;+ }+ const presence = raw as { deviceId?: string; online?: boolean } | null;+ if (!presence?.deviceId) return;+ const wasOnline = remotePresenceOnlineByDevice.get(presence.deviceId);+ remotePresenceOnlineByDevice.set(presence.deviceId, presence.online === true);+ if (presence.online !== true) return;+ // Only a real offline -> online edge may indicate that the controlled+ // process restarted and reset its local owner generation. Busy/name/+ // settings presence updates also carry online=true; those must retain+ // the monotonic fence so a late older frame stays rejected.+ if (wasOnline !== true) resetRemoteDataOwnerPushFence(presence.deviceId);+ for (const [sessionId, records] of remoteOptimisticSends) {+ if ([...records.values()].some((record) => record.deviceId === presence.deviceId)) {+ clearRemoteInputProjectionProbeFailure(sessionId, presence.deviceId);+ pumpRemoteOptimisticSendsAfterCurrent(sessionId);+ }+ }+ for (const [sessionId, fence] of remoteClearFences) {+ if (fence.deviceId === presence.deviceId) void retryRemoteClearFence(sessionId);+ }+ },+ 'device-link-presence-changed-for-outbox',+ );+// ── Main 端写库的消息推送 (e.g. feishu /ctr 接管路径下 persistUserMessage /// persistAssistantMessage) ──// renderer 自己发出的 user 消息已经乐观 push 过, 落库后这条 broadcast 也会到,@@ -4729,12 +6863,21 @@ function initGlobalListeners(): void {// 这里直接补进 messages 数组让 UI 立刻看到。bindIpc(window.electronAPI.localDb.messages.onCreated,- handleMessageCreatedRaw,+ (raw, ownerStamp) =>+ handleMessageCreatedRaw(raw, {+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ }),'local-db-messages-created',);bindIpc(- (cb) => window.electronAPI.localDb.messages.onDeleted?.(cb),- handleMessageDeletedRaw,+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.localDb.messages.onDeleted?.(cb),+ (raw, ownerStamp) =>+ handleMessageDeletedRaw(raw, {+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ }),'local-db-messages-deleted',);@@ -4746,8 +6889,17 @@ function initGlobalListeners(): void {// 2. store.error 存在(live ErrorBanner) → 清掉,让重拉后 ErrorMessageCard 独自出现。// 正在被查看的会话跳过:它们有 live ErrorBanner(含 Retry/Cancel),不应被脏信号干扰。bindIpc(- (cb) => window.electronAPI.localDb.messages.onErrorPersisted?.(cb),- (raw: unknown) => {+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.localDb.messages.onErrorPersisted?.(cb),+ (raw: unknown, ownerStamp?: unknown) => {+ if (+ !isCurrentLiveIngress({+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ })+ ) {+ return;+ }const p = raw as { sessionId?: string } | null;if (!p?.sessionId) return;const state = sessions.get(p.sessionId);@@ -4766,9 +6918,7 @@ function initGlobalListeners(): void {setState(p.sessionId, (s) => ({...s,...(s.historyLoaded ? { historyLoaded: false } : {}),- ...(s.error- ? { error: null, usageLimitRecovery: null, errorRetryText: null }- : {}),+ ...(s.error ? { error: null, usageLimitRecovery: null, errorRetryText: null } : {}),}));},'local-db-session-error-persisted',@@ -4781,13 +6931,23 @@ function initGlobalListeners(): void {// 可选调用兜底:renderer HMR 先于 main 重启时老 preload 没有这个 fanOut,// 直接取值会让 initGlobalListeners 整体崩掉(费用推送丢了无妨,历史加载兜底)。bindIpc(- (cb) => window.electronAPI.onUsageMessageTurnCost?.(cb),- handleUsageMessageTurnCostRaw,+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.onUsageMessageTurnCost?.(cb),+ (raw, ownerStamp) =>+ handleUsageMessageTurnCostRaw(raw, {+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ }),'usage-message-turn-cost',);bindIpc(- (cb) => window.electronAPI.onUsageMessageModelMismatch?.(cb),- handleUsageMessageModelMismatchRaw,+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.onUsageMessageModelMismatch?.(cb),+ (raw, ownerStamp) =>+ handleUsageMessageModelMismatchRaw(raw, {+ ownerStamp,+ ownerStampPresent: ownerStamp !== undefined,+ }),'usage-message-model-mismatch',);@@ -4797,8 +6957,10 @@ function initGlobalListeners(): void {// 两条路都保证用户看得见"这条被谁拦了",绝不无声蒸发。被拦消息本就没// 入库,离开会话即消失(UI 瞬态,预期语义)。bindIpc(- (cb) => window.electronAPI.ghosts?.onUserMessageBlocked?.(cb),- (raw: unknown) => {+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.ghosts?.onUserMessageBlocked?.(cb),+ (raw: unknown, ownerStamp?: unknown) => {+ if (!isCurrentLocalLiveIngress(ownerStamp)) return;const p = raw as {sessionId?: string;clientId?: string;@@ -4844,8 +7006,10 @@ function initGlobalListeners(): void {// 必在;会话忙时排队消息无乐观气泡,找不到就忽略——落库后 messages:created// 会用改写版 content 显示。bindIpc(- (cb) => window.electronAPI.ghosts?.onUserMessageRewritten?.(cb),- (raw: unknown) => {+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.ghosts?.onUserMessageRewritten?.(cb),+ (raw: unknown, ownerStamp?: unknown) => {+ if (!isCurrentLocalLiveIngress(ownerStamp)) return;const p = raw as { sessionId?: string; clientId?: string; text?: string } | null;if (!p?.sessionId || !p.clientId || typeof p.text !== 'string') return;setState(p.sessionId, (s) => ({@@ -4863,8 +7027,10 @@ function initGlobalListeners(): void {// content 静默换成改写版(与落库一致)。找不到该 clientId(极少:消息还没// hydrate)则忽略——messages:created/更新会带最终内容。bindIpc(- (cb) => window.electronAPI.ghosts?.onAssistantMessageRewritten?.(cb),- (raw: unknown) => {+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.ghosts?.onAssistantMessageRewritten?.(cb),+ (raw: unknown, ownerStamp?: unknown) => {+ if (!isCurrentLocalLiveIngress(ownerStamp)) return;const p = raw as { sessionId?: string; clientId?: string; text?: string } | null;if (!p?.sessionId || !p.clientId || typeof p.text !== 'string') return;setState(p.sessionId, (s) => ({@@ -4882,8 +7048,10 @@ function initGlobalListeners(): void {// 或超时清掉。render(自绘卡)的呈现切换由 ghostCardStore 驱动(byCallId 命中// 本条 clientId),此处只管指示位。bindIpc(- (cb) => window.electronAPI.ghosts?.onAssistantMessagePending?.(cb),- (raw: unknown) => {+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.ghosts?.onAssistantMessagePending?.(cb),+ (raw: unknown, ownerStamp?: unknown) => {+ if (!isCurrentLocalLiveIngress(ownerStamp)) return;const p = raw as { sessionId?: string; clientId?: string; pending?: boolean } | null;if (!p?.sessionId || !p.clientId || typeof p.pending !== 'boolean') return;setState(p.sessionId, (s) => ({@@ -4898,8 +7066,10 @@ function initGlobalListeners(): void {// ── 意识钩子熔断(订阅槽①):连续失败降级只旁听,提示用户 ──bindIpc(- (cb) => window.electronAPI.ghosts?.onHookFused?.(cb),- (raw: unknown) => {+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.ghosts?.onHookFused?.(cb),+ (raw: unknown, ownerStamp?: unknown) => {+ if (!isCurrentLocalLiveIngress(ownerStamp)) return;const p = raw as { name?: string } | null;if (!p) return;toast.error(i18n.t('chat.ghostHook.fused', { name: p.name ?? '' }));@@ -4913,8 +7083,10 @@ function initGlobalListeners(): void {// 主机权威事件)——文案跟用户语言走,按 GHOST_HOST_NOTICE_KEYS 白名单翻译,// 白名单外静默丢(防版本错配把生肉 key 摆上界面)。bindIpc(- (cb) => window.electronAPI.ghosts?.onNotify?.(cb),- (raw: unknown) => {+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.ghosts?.onNotify?.(cb),+ (raw: unknown, ownerStamp?: unknown) => {+ if (!isCurrentLocalLiveIngress(ownerStamp)) return;const p = raw as {name?: string;iconDataUrl?: string;@@ -4953,8 +7125,10 @@ function initGlobalListeners(): void {// routeSidebarCommand 会按"贴附/抽离"把命令送到正确归宿;抽离的侧栏子窗口// 若也处理,同一条广播会开出两个标签。bindIpc(- (cb) => window.electronAPI.ghosts?.onPreviewOpen?.(cb),- (raw: unknown) => {+ (cb: (data: unknown, ownerStamp?: unknown) => void) =>+ window.electronAPI.ghosts?.onPreviewOpen?.(cb),+ (raw: unknown, ownerStamp?: unknown) => {+ if (!isCurrentLocalLiveIngress(ownerStamp)) return;if (isSidebarWindow()) return;const p = raw as {name?: string;@@ -4991,6 +7165,32 @@ function __teardownGlobalListeners(): void {pendingDeferredStateNotifications.clear();pendingMessageCreatedPatches.clear();_pendingErrorClearOnLeave.clear();+ remotePresenceOnlineByDevice.clear();+ resetRemoteDataOwnerPushFence();+ const remoteOptimisticSessionIds = new Set([+ ...remoteOptimisticSends.keys(),+ ...remoteOptimisticRetryTimers.keys(),+ ...remoteOptimisticSettlingTimers.keys(),+ ]);+ for (const sessionId of remoteOptimisticSessionIds) {+ clearRemoteOptimisticSendsForSession(sessionId);+ }+ for (const sessionId of remoteClearFences.keys()) {+ clearRemoteClearFence(sessionId, { pump: false });+ }+ remoteOptimisticMaterializationRecoveries.clear();+ syncRemoteOptimisticAttachmentUrls();+ remoteOptimisticPumps.clear();+ remoteOptimisticLocallyRemoved.clear();+ remoteClearInFlight.clear();+ remoteInputProjectionRequests.clear();+ remoteInputProjectionProbeStateBySession.clear();+ // A test/HMR teardown starts a fresh renderer epoch. Session LRU/view+ // eviction intentionally does not clear these maps: a reconnect can rebuild+ // the mirror with an empty shard and still needs the last known clear token.+ remoteInputClearBoundaryBySession.clear();+ rendererClearBoundaryBySession.clear();+ rendererClearGenerationBySession.clear();// Stage 2 C1: 老的 cc-agent:* fan-out 已退役, __resetCCAgentFanOuts 也跟着删了。// 新链路 maker:* fan-out 当前不会泄漏 (initGlobalListeners 顶部 if guard +// dispose 时调对应 unsub()), 不需要 reset 兜底; 真发现 HMR fan-out 重复时@@ -5070,10 +7270,8 @@ function lightStateEquals(a: SessionChatLightState, b: SessionChatLightState): ba.credentialSwitchWait === b.credentialSwitchWait &&a.continuationInFlightClientId === b.continuationInFlightClientId &&a.continuationTurnClientId === b.continuationTurnClientId &&- a.continuationInFlightProjectionCapability ===- b.continuationInFlightProjectionCapability &&+ a.continuationInFlightProjectionCapability === b.continuationInFlightProjectionCapability &&a.isLoadingMore === b.isLoadingMore &&-a.hasMoreMessages === b.hasMoreMessages &&a.historyWindowHasIsland === b.historyWindowHasIsland &&a.isFirstMessage === b.isFirstMessage &&@@ -5436,8 +7634,37 @@ let applyInteractionRequestRef: ((raw: unknown) => void) | null = null;* 面板不显示。这里经 makerApiFor(按来源路由:本机本机 IPC / 远程隧道)主动拉快照,* 喂给同一套分发逻辑重建(ask/plan 按 requestId 去重,复用历史里那条消息,不产生重复)。*/-function reconcilePendingInteractions(sessionId: string): Promise<number> {+function reconcilePendingInteractions(+ sessionId: string,+ isCurrent?: () => boolean,+): Promise<number> {if (!sessionId) return Promise.resolve(0);+ // The interaction snapshot is an async read, so its lifecycle must be+ // independent from the optional history-load guard supplied by only some+ // callers. Purge/clear/reload advance messagesEpoch; an origin change+ // means the response came from a different authority. Keep the captured+ // values even when no session slice exists yet: an unmounted session may+ // legitimately be materialized by a fresh interaction snapshot, while a+ // purged session cannot be resurrected because its epoch/tombstone changes.+ const interactionEpochAtStart = _messagesEpoch.get(sessionId) ?? 0;+ const interactionAuthorityEpochAtStart = _inputProjectionAuthorityEpoch.get(sessionId) ?? 0;+ const interactionDataOwnerAtStart = getDataOwnerGeneration();+ // Only the newest interaction snapshot may mutate the pending-card slice.+ // This also covers a dismiss/answer/request event arriving while the host+ // query is in flight, and prevents an older concurrent reconcile from+ // subtractively deleting a newer plugin_setup card.+ const interactionReconcileEpochAtStart = beginInteractionReconcile(sessionId);+ const interactionOriginAtStart = remoteProjectsStore.getSessionDeviceId(sessionId);+ const stickyDeviceAtStart = getStickySessionDeviceId(sessionId);+ const isCurrentInteractionReconcile = () =>+ isDataOwnerGenerationCurrent(interactionDataOwnerAtStart) &&+ (_messagesEpoch.get(sessionId) ?? 0) === interactionEpochAtStart &&+ (_inputProjectionAuthorityEpoch.get(sessionId) ?? 0) === interactionAuthorityEpochAtStart &&+ (_interactionReconcileEpoch.get(sessionId) ?? 0) === interactionReconcileEpochAtStart &&+ remoteProjectsStore.getSessionDeviceId(sessionId) === interactionOriginAtStart &&+ (!stickyDeviceAtStart || !isRemoteTerminalSessionTombstoned(sessionId, stickyDeviceAtStart)) &&+ (!isCurrent || isCurrent());+ if (!isCurrentInteractionReconcile()) return Promise.resolve(0);// best-effort 面板重建:对既有调用方仍是 fire-and-forget。它被 ensureInitialMessages 的// listMessagesFor.then 内联调用,若 getPendingInteractions **同步**抛错(如某路由分支// API 缺失)而不只是 reject,异常会冒泡到外层 .catch 把 historyLoaded 误打回 false。@@ -5447,73 +7674,71 @@ function reconcilePendingInteractions(sessionId: string): Promise<number> {// 语义——needs-interaction 未读的 passive 远程回执必须等交互面板真实重建后才放行,// 且守卫早退路径只在真有提示(count>0)时才算一代完成。try {- const run = makerApiFor(sessionId)- .getPendingInteractions(sessionId)- .then((list) => {- if (!Array.isArray(list)) return 0;- // A successful list response is the Host-authoritative snapshot for Setup- // interactions. Reconcile it subtractively before replaying the snapshot so- // a Device Link reconnect cannot leave cards that the Host already closed.- // Other interaction kinds keep their existing replay semantics.- const authoritativePluginSetupIds = new Set<string>();- for (const item of list) {- const request = item?.request;- if (- request?.kind === 'plugin_setup' &&- typeof request.requestId === 'string' &&- request.requestId.length > 0- ) {- authoritativePluginSetupIds.add(request.requestId);- }+ const interactionApi = stickyDeviceAtStart+ ? makerApiForDevice(stickyDeviceAtStart)+ : makerApiFor(sessionId);+ const run = interactionApi.getPendingInteractions(sessionId).then((list) => {+ if (!isCurrentInteractionReconcile()) return 0;+ if (!Array.isArray(list)) return 0;+ // A successful list response is the Host-authoritative snapshot for Setup+ // interactions. Reconcile it subtractively before replaying the snapshot so+ // a Device Link reconnect cannot leave cards that the Host already closed.+ // Other interaction kinds keep their existing replay semantics.+ const authoritativePluginSetupIds = new Set<string>();+ for (const item of list) {+ const request = item?.request;+ if (+ request?.kind === 'plugin_setup' &&+ typeof request.requestId === 'string' &&+ request.requestId.length > 0+ ) {+ authoritativePluginSetupIds.add(request.requestId);}- setState(sessionId, (state) => {- const currentSurvives =- state.pendingPluginSetup !== null &&- authoritativePluginSetupIds.has(state.pendingPluginSetup.requestId);- const survivingQueue = state.pendingPluginSetupQueue.filter(- (setup) =>- authoritativePluginSetupIds.has(setup.requestId) &&- (!currentSurvives || setup.requestId !== state.pendingPluginSetup?.requestId),- );- const nextCurrent = currentSurvives- ? state.pendingPluginSetup- : (survivingQueue.shift() ?? null);- const currentChanged = nextCurrent !== state.pendingPluginSetup;- const queueChanged =- survivingQueue.length !== state.pendingPluginSetupQueue.length ||- survivingQueue.some(- (setup, index) => setup !== state.pendingPluginSetupQueue[index],- );- const nextCommand =- state.pluginSetupCommandInFlight &&- authoritativePluginSetupIds.has(state.pluginSetupCommandInFlight.requestId)- ? state.pluginSetupCommandInFlight- : null;-- if (- !currentChanged &&- !queueChanged &&- nextCommand === state.pluginSetupCommandInFlight- ) {- return state;- }- return {- ...state,- pendingPluginSetup: nextCurrent,- pendingPluginSetupQueue: survivingQueue,- pluginSetupViewerState: currentChanged ? 'expanded' : state.pluginSetupViewerState,- pluginSetupCommandInFlight: nextCommand,- };- });- for (const item of list) {- applyInteractionRequestRef?.({- sessionId,- request: item.request,- persistId: item.persistId,- });+ }+ if (!isCurrentInteractionReconcile()) return 0;+ setState(sessionId, (state) => {+ const currentSurvives =+ state.pendingPluginSetup !== null &&+ authoritativePluginSetupIds.has(state.pendingPluginSetup.requestId);+ const survivingQueue = state.pendingPluginSetupQueue.filter(+ (setup) =>+ authoritativePluginSetupIds.has(setup.requestId) &&+ (!currentSurvives || setup.requestId !== state.pendingPluginSetup?.requestId),+ );+ const nextCurrent = currentSurvives+ ? state.pendingPluginSetup+ : (survivingQueue.shift() ?? null);+ const currentChanged = nextCurrent !== state.pendingPluginSetup;+ const queueChanged =+ survivingQueue.length !== state.pendingPluginSetupQueue.length ||+ survivingQueue.some((setup, index) => setup !== state.pendingPluginSetupQueue[index]);+ const nextCommand =+ state.pluginSetupCommandInFlight &&+ authoritativePluginSetupIds.has(state.pluginSetupCommandInFlight.requestId)+ ? state.pluginSetupCommandInFlight+ : null;++ if (!currentChanged && !queueChanged && nextCommand === state.pluginSetupCommandInFlight) {+ return state;}- return list.length;+ return {+ ...state,+ pendingPluginSetup: nextCurrent,+ pendingPluginSetupQueue: survivingQueue,+ pluginSetupViewerState: currentChanged ? 'expanded' : state.pluginSetupViewerState,+ pluginSetupCommandInFlight: nextCommand,+ };});+ for (const item of list) {+ if (!isCurrentInteractionReconcile()) return 0;+ applyInteractionRequestRef?.({+ sessionId,+ request: item.request,+ persistId: item.persistId,+ });+ }+ return list.length;+ });run.catch((err) => log.warn('reconcilePendingInteractions failed', err));return run;} catch (err) {@@ -5566,6 +7791,24 @@ const _inputProjectionEpoch = new Map<string, number>();const _inputProjectionAuthorityEpoch = new Map<string, number>();let _nextInputProjectionEpoch = 0;+/**+ * Interaction snapshots have their own lifecycle epoch. A pending+ * permission/ask/plan card is not message history: dismissing or answering it+ * must invalidate an older `getPendingInteractions()` response without+ * cancelling unrelated message pagination.+ */+const _interactionReconcileEpoch = new Map<string, number>();++function bumpInteractionReconcileEpoch(sessionId: string): number {+ const next = (_interactionReconcileEpoch.get(sessionId) ?? 0) + 1;+ _interactionReconcileEpoch.set(sessionId, next);+ return next;+}++function beginInteractionReconcile(sessionId: string): number {+ return bumpInteractionReconcileEpoch(sessionId);+}+function nextInputProjectionEpoch(): number {_nextInputProjectionEpoch += 1;return _nextInputProjectionEpoch;@@ -5587,11 +7830,30 @@ function supersedeInputProjectionRequests(function invalidateInputProjectionRequests(sessionId: string): void {_inputProjectionOrigin.delete(sessionId);_inputProjectionEpoch.delete(sessionId);+ remoteInputProjectionRequests.delete(sessionId);+ remoteInputProjectionProbeStateBySession.delete(sessionId);// authority 代际不能 delete:pre-purge 操作可能捕获 0,delete 后回落 0 会误放行,// 并通过 setState 复活已 purge 的 session。保留单调墓碑,与 messagesEpoch 同理。_inputProjectionAuthorityEpoch.set(sessionId, nextInputProjectionEpoch());}+/**+ * An account/local-mode boundary invalidates standalone projection operations+ * too. They do not necessarily have a remote optimistic outbox record, so+ * clearing only the outbox would still let an old owner's late projection+ * mutate the new owner's session slice.+ */+function invalidateInputProjectionRequestsForDataOwnerBoundary(): void {+ const sessionIds = new Set<string>([+ ...sessions.keys(),+ ..._inputProjectionOrigin.keys(),+ ..._inputProjectionEpoch.keys(),+ ..._inputProjectionAuthorityEpoch.keys(),+ ...remoteInputProjectionRequests.keys(),+ ]);+ for (const sessionId of sessionIds) invalidateInputProjectionRequests(sessionId);+}+function beginInputProjectionRequest(sessionId: string, origin: string | undefined): number {_inputProjectionOrigin.set(sessionId, origin);const epoch = nextInputProjectionEpoch();@@ -5614,19 +7876,18 @@ function noteInputProjectionOrigin(return { epoch: _inputProjectionEpoch.get(sessionId)!, changed: false };}-function isCurrentInputProjectionOrigin(- sessionId: string,- origin: string | undefined,-): boolean {- return remoteProjectsStore.getSessionDeviceId(sessionId) === origin;+function isCurrentInputProjectionOrigin(sessionId: string, origin: string | undefined): boolean {+ return getStickySessionDeviceId(sessionId) === origin;}function isCurrentInputProjectionRequest(sessionId: string,origin: string | undefined,epoch: number,+ dataOwner: DataOwnerGeneration,): boolean {return (+ isDataOwnerGenerationCurrent(dataOwner) &&isCurrentInputProjectionOrigin(sessionId, origin) &&(_inputProjectionEpoch.get(sessionId) ?? 0) === epoch);@@ -5635,6 +7896,8 @@ function isCurrentInputProjectionRequest(interface InputProjectionOperation {api: RoutableMaker;origin: string | undefined;+ pinnedDeviceId?: string;+ dataOwner: DataOwnerGeneration;epoch: number;}@@ -5643,11 +7906,21 @@ interface InputProjectionOperation {* origin 漂移后重新调用 makerApiFor 会把同一业务意图错发到另一台设备。* authority epoch 只由终态 / 来源切换推进;普通 push 与同源并发操作仍按响应到达顺序落地。*/-function beginInputProjectionOperation(sessionId: string): InputProjectionOperation {- const origin = remoteProjectsStore.getSessionDeviceId(sessionId);+function beginInputProjectionOperation(+ sessionId: string,+ pinnedDeviceId?: string,+): InputProjectionOperation {+ // Queue controls are still writes to the session owner. The live mirror can+ // be empty for a short window while relay subscriptions are rebuilding, but+ // stickySessionOrigin retains the last authoritative device and prevents a+ // weak-link click from falling back to the controller's local maker.+ const routedDeviceId = pinnedDeviceId ?? getStickySessionDeviceId(sessionId);+ const origin = routedDeviceId;return {- api: makerApiFor(sessionId),+ api: routedDeviceId ? makerApiForDevice(routedDeviceId) : makerApiFor(sessionId),origin,+ ...(pinnedDeviceId ? { pinnedDeviceId } : {}),+ dataOwner: getDataOwnerGeneration(),epoch: _inputProjectionAuthorityEpoch.get(sessionId) ?? 0,};}@@ -5658,7 +7931,10 @@ function applyInputProjectionOperationResponse(projection: AgentInputProjection,): boolean {if (- !isCurrentInputProjectionOrigin(sessionId, operation.origin) ||+ !isDataOwnerGenerationCurrent(operation.dataOwner) ||+ (operation.pinnedDeviceId+ ? getStickySessionDeviceId(sessionId) !== operation.pinnedDeviceId+ : !isCurrentInputProjectionOrigin(sessionId, operation.origin)) ||(_inputProjectionAuthorityEpoch.get(sessionId) ?? 0) !== operation.epoch) {return false;@@ -5678,11 +7954,13 @@ function supersedeInputProjectionOnTerminalEvent(): void {if (event.type === 'done') {if ((event.data as { silentStop?: boolean } | null | undefined)?.silentStop !== true) {+ bumpInteractionReconcileEpoch(sessionId);supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });}return;}if (event.type === 'error' && isTerminalErrorData(event.data)) {+ bumpInteractionReconcileEpoch(sessionId);supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });}}@@ -5698,6 +7976,460 @@ function runInputProjectionOperation(}));}+type RemoteOptimisticDispatchResult =+ | { kind: 'accepted' }+ | { kind: 'retry' }+ | { kind: 'deferred' }+ | { kind: 'cancelled' }+ | { kind: 'failed'; error: unknown };++type RemoteOptimisticPreparationResult =+ | { kind: 'ready' }+ | { kind: 'deferred' }+ | { kind: 'cancelled' }+ | { kind: 'failed'; error?: unknown };++function isRemoteOptimisticSendRegistered(+ sessionId: string,+ record: RemoteOptimisticSendRecord,+): boolean {+ return (+ remoteOptimisticSendRecords(sessionId)?.get(record.queued.clientId) === record &&+ isDataOwnerGenerationCurrent(record.dataOwner)+ );+}++async function prepareRemoteOptimisticSend(+ sessionId: string,+ record: RemoteOptimisticSendRecord,+): Promise<RemoteOptimisticPreparationResult> {+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ if (hasPendingRemoteClearFence(sessionId)) {+ record.phase = 'waiting-for-connection';+ scheduleRemoteClearRetry(sessionId);+ return { kind: 'deferred' };+ }+ if (record.materializationPending) {+ record.phase = 'preflight';+ return { kind: 'deferred' };+ }+ if (!record.preflightCompleted && record.beforeEnqueue) {+ record.phase = 'preflight';+ try {+ const proceed = await record.beforeEnqueue();+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ if (!proceed) return { kind: 'failed' };+ record.preflightCompleted = true;+ } catch (error) {+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ if (!isDeferredRemoteSendError(error)) return { kind: 'failed', error };+ markRemoteOptimisticSendWaiting(sessionId, record.queued.clientId);+ return { kind: 'deferred' };+ }+ } else {+ record.preflightCompleted = true;+ }++ // Any send without a known token probes the pinned host before dispatch. This+ // includes steer: a clear boundary is a content-ownership fence, not merely+ // an enqueue concern. Older hosts may reject the projection invoke; the+ // compatibility fallback below still permits the original steer attempt.+ const forceProbe = record.forceClearBoundaryProbe;+ if (+ !forceProbe &&+ record.expectedClearBoundaryMs === undefined &&+ !record.clearBoundaryProbeCompleted+ ) {+ const knownBoundary = getKnownRemoteInputClearBoundary(sessionId);+ if (knownBoundary !== undefined) {+ record.expectedClearBoundaryMs = knownBoundary;+ record.clearBoundaryProbeCompleted = true;+ }+ }+ if (+ !forceProbe &&+ record.expectedClearBoundaryMs === undefined &&+ !record.clearBoundaryProbeCompleted+ ) {+ const probeState = remoteInputProjectionProbeStateBySession.get(sessionId);+ if (+ probeState &&+ isRemoteInputProjectionProbeStateCurrent(sessionId, probeState, record.deviceId)+ ) {+ if (+ probeState.status === 'blocked' &&+ (isDeferredRemoteSendError(probeState.error) ||+ isRemoteInputClearBoundaryError(probeState.error))+ ) {+ markRemoteOptimisticSendWaiting(sessionId, record.queued.clientId);+ return { kind: 'deferred' };+ }+ record.expectedClearBoundaryMs = probeState.boundary;+ record.clearBoundaryProbeCompleted = true;+ }+ }+ if (+ record.expectedClearBoundaryMs === undefined &&+ (!record.clearBoundaryProbeCompleted || forceProbe)+ ) {+ record.clearBoundaryProbeInFlight = true;+ try {+ const projectionResult = await requestInputProjection(sessionId, record.deviceId);+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) {+ return { kind: 'cancelled' };+ }+ if (projectionResult && !projectionResult.current) {+ markRemoteOptimisticSendWaiting(sessionId, record.queued.clientId);+ return { kind: 'deferred' };+ }+ const projection = projectionResult?.projection;+ if (projection) {+ const hasBoundary = Object.prototype.hasOwnProperty.call(projection, 'clearBoundaryMs');+ if (hasBoundary) {+ const observedBoundary = normalizeAgentInputClearBoundaryMs(projection.clearBoundaryMs);+ if (observedBoundary === undefined) {+ return {+ kind: 'failed',+ error: new Error('Remote input projection carried an invalid clear boundary'),+ };+ }+ // A push/snapshot may have already advanced the local mirror while the+ // probe was in flight. Never regress to that probe's stale token.+ const currentBoundary = remoteInputClearBoundaryBySession.get(sessionId);+ record.expectedClearBoundaryMs =+ typeof currentBoundary === 'number' &&+ (observedBoundary === null || observedBoundary < currentBoundary)+ ? currentBoundary+ : observedBoundary;+ }+ }+ // `requestInputProjection` has already applied the response. Marking the+ // record complete here avoids a second apply/pump cycle and lets all later+ // FIFO items reuse the same modern/legacy capability result.+ record.clearBoundaryProbeCompleted = true;+ record.forceClearBoundaryProbe = false;+ record.clearGeneration = rendererClearGenerationBySession.get(sessionId) ?? 0;+ } catch (error) {+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ // A clear may be sealing while the relay is otherwise healthy. Keep the+ // local bubble and retry after the boundary settles instead of restoring+ // the composer as a permanent failure. Other projection failures retain+ // the pre-probe compatibility path: enqueue can still be attempted, and+ // main will enforce its own clear/state checks.+ if (isDeferredRemoteSendError(error) || isRemoteInputClearBoundaryError(error)) {+ markRemoteOptimisticSendWaiting(sessionId, record.queued.clientId);+ return { kind: 'deferred' };+ }+ record.forceClearBoundaryProbe = false;+ record.clearBoundaryProbeCompleted = true;+ } finally {+ record.clearBoundaryProbeInFlight = false;+ }+ }++ return { kind: 'ready' };+}++async function reconcileUncertainRemoteSteer(+ sessionId: string,+ record: RemoteOptimisticSendRecord,+ operation: InputProjectionOperation,+): Promise<RemoteOptimisticDispatchResult> {+ const [projectionResult, persistedResult] = await Promise.allSettled([+ operation.api.input.getProjection(sessionId),+ aroundMessagesByClientIdForDevice(record.deviceId, sessionId, record.queued.clientId, {+ radius: 0,+ }),+ ]);+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };++ let projectionConclusive = false;+ let persistedLookupConclusive = false;+ let hasAcceptanceEvidence = false;+ let freshProjection: AgentInputProjection | null = null;++ if (projectionResult.status === 'fulfilled') {+ projectionConclusive = true;+ freshProjection = projectionResult.value;+ hasAcceptanceEvidence =+ freshProjection.pendingQueue.some((item) => item.clientId === record.queued.clientId) ||+ freshProjection.steeringQueueClientIds?.includes(record.queued.clientId) === true;+ } else {+ log.warn('remote optimistic steer projection reconciliation failed:', projectionResult.reason);+ }++ if (persistedResult.status === 'fulfilled') {+ persistedLookupConclusive = true;+ hasAcceptanceEvidence ||= persistedResult.value.some(+ (message) => message.clientId === record.queued.clientId,+ );+ } else if (isRemoteAroundClientIdMiss(persistedResult.reason)) {+ // around-client-id 用 NOT_FOUND 表达“该 clientId 尚未落库”。这是一次成功的+ // 否定查询,不应被当成断线继续悬置。+ persistedLookupConclusive = true;+ } else {+ log.warn('remote optimistic steer DB reconciliation failed:', persistedResult.reason);+ }++ if (hasAcceptanceEvidence) {+ record.steerDispatchUncertain = false;+ markRemoteOptimisticSendAccepted(sessionId, record.queued.clientId);+ }+ if (freshProjection) {+ applyInputProjectionOperationResponse(sessionId, operation, freshProjection);+ }+ if (hasAcceptanceEvidence) {+ const current = remoteOptimisticSendRecords(sessionId)?.get(record.queued.clientId);+ if (!current?.currentlyQueued) {+ retainOrClearRemoteOptimisticSendAfterProjection(sessionId, record.queued.clientId);+ }+ markSessionHasUserMessage(sessionId);+ void reconcileRemoteMessages(sessionId);+ return { kind: 'accepted' };+ }++ if (projectionConclusive && persistedLookupConclusive) {+ // 两个权威面都确认没有这条 steer。改用同一 clientId enqueue:若 steer 恰好+ // 在查询后才被 main 接管,coordinator 的 queue/active/steering/recent 窗口+ // 会把这次补投幂等去重;否则消息获得一个可靠的排队落点。+ record.steerDispatchUncertain = false;+ record.deliveryMode = 'queue';+ record.phase = 'preflight';+ return { kind: 'retry' };+ }++ markRemoteOptimisticSendWaiting(sessionId, record.queued.clientId);+ return { kind: 'deferred' };+}++async function dispatchRemoteOptimisticSend(+ sessionId: string,+ record: RemoteOptimisticSendRecord,+): Promise<RemoteOptimisticDispatchResult> {+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ if (record.accepted) return { kind: 'accepted' };+ if (record.dispatching) return { kind: 'deferred' };+ record.dispatching = true;+ record.phase = 'dispatching';+ record.attempt += 1;+ clearRemoteOptimisticRetryTimer(sessionId);++ const operation = beginInputProjectionOperation(sessionId, record.deviceId);+ try {+ if (record.deliveryMode === 'steer') {+ if (record.steerDispatchUncertain) {+ return await reconcileUncertainRemoteSteer(sessionId, record, operation);+ }+ const accepted = await operation.api.input.steer(sessionId, record.queued, {+ touchUserSend: true,+ ...(record.expectedClearBoundaryMs !== undefined+ ? { expectedClearBoundaryMs: record.expectedClearBoundaryMs }+ : {}),+ });+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ if (!accepted) throw new Error('Remote steer was not accepted');+ markRemoteOptimisticSendAccepted(sessionId, record.queued.clientId);+ void requestInputProjection(sessionId);+ return { kind: 'accepted' };+ }+ const projection = await operation.api.input.enqueue(sessionId, record.queued, {+ sendAtMs: Date.now(),+ ...(record.expectedClearBoundaryMs !== undefined+ ? { expectedClearBoundaryMs: record.expectedClearBoundaryMs }+ : {}),+ });+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ markRemoteOptimisticSendAccepted(sessionId, record.queued.clientId);+ if (record.authRetryPersistOnProjectionError) {+ setState(sessionId, (s) => ({+ ...s,+ _authRetryPersistOnProjectionError: {+ clientId: record.queued.clientId,+ ...record.authRetryPersistOnProjectionError!,+ },+ }));+ }+ const applied = applyInputProjectionOperationResponse(sessionId, operation, projection);+ if (applied) markSessionHasUserMessage(sessionId);+ if (!projection.pendingQueue.some((item) => item.clientId === record.queued.clientId)) {+ retainOrClearRemoteOptimisticSendAfterProjection(sessionId, record.queued.clientId);+ }+ return { kind: 'accepted' };+ } catch (error) {+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ if (isRemoteInputPreparationSupersededError(error)) {+ // The host invalidated the input while it was being prepared (for+ // example, a remote clear advanced the coordinator generation). This+ // message is no longer safe to re-probe or enqueue; restore the draft+ // immediately without surfacing a user-facing error.+ return { kind: 'failed', error: undefined };+ }+ if (isRemoteInputClearBoundaryError(error)) {+ // The clear token can advance between the click-time probe and dispatch.+ // Re-open the probe exactly once so a stale renderer token can recover;+ // if the host still rejects the refreshed token, settle normally instead+ // of spinning the outbox forever.+ if (record.clearBoundaryRecoveryAttempted) {+ return { kind: 'failed', error: undefined };+ }+ record.clearBoundaryRecoveryAttempted = true;+ record.expectedClearBoundaryMs = undefined;+ record.clearBoundaryProbeCompleted = false;+ record.clearBoundaryProbeInFlight = false;+ record.forceClearBoundaryProbe = true;+ remoteInputProjectionProbeStateBySession.delete(sessionId);+ remoteInputProjectionRequests.delete(sessionId);+ markRemoteOptimisticSendWaiting(sessionId, record.queued.clientId);+ return { kind: 'deferred' };+ }+ if (isTerminalRemoteInputError(error)) {+ return { kind: 'failed', error };+ }+ if (record.deliveryMode === 'steer' && isAmbiguousRemoteSteerError(error)) {+ record.steerDispatchUncertain = true;+ return await reconcileUncertainRemoteSteer(sessionId, record, operation);+ }+ let reconciliationError: unknown;+ let reconciled = false;+ try {+ // An invoke timeout is ambiguous. Ask the same pinned device before+ // deciding whether it is safe to send again with the same clientId.+ const fresh = await operation.api.input.getProjection(sessionId);+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ const freshHasQueue = fresh.pendingQueue.some(+ (item) => item.clientId === record.queued.clientId,+ );+ const freshHasSteeringMarker =+ fresh.steeringQueueClientIds?.includes(record.queued.clientId) === true;+ if (freshHasQueue || freshHasSteeringMarker) {+ markRemoteOptimisticSendAccepted(sessionId, record.queued.clientId);+ reconciled = true;+ } else {+ const current = remoteOptimisticSendRecords(sessionId)?.get(record.queued.clientId);+ if (current) current.currentlyQueued = false;+ }+ applyInputProjectionOperationResponse(sessionId, operation, fresh);+ } catch (projectionError) {+ if (!isRemoteOptimisticSendRegistered(sessionId, record)) return { kind: 'cancelled' };+ reconciliationError = projectionError;+ log.warn('remote optimistic send reconciliation failed:', projectionError);+ }++ if (reconciled) {+ const current = remoteOptimisticSendRecords(sessionId)?.get(record.queued.clientId);+ if (!current?.currentlyQueued) {+ retainOrClearRemoteOptimisticSendAfterProjection(sessionId, record.queued.clientId);+ }+ markSessionHasUserMessage(sessionId);+ return { kind: 'accepted' };+ }+ const shouldDefer =+ record.deliveryMode === 'steer'+ ? isDefinitelyUndeliveredRemoteSteerError(error)+ : isDeferredRemoteSendError(error) || isDeferredRemoteSendError(reconciliationError);+ if (shouldDefer) {+ markRemoteOptimisticSendWaiting(sessionId, record.queued.clientId);+ return { kind: 'deferred' };+ }+ return { kind: 'failed', error };+ } finally {+ record.dispatching = false;+ }+}++function settleRemoteOptimisticFailure(sessionId: string, clientId: string, error?: unknown): void {+ const record = remoteOptimisticSendRecords(sessionId)?.get(clientId);+ if (record?.composerResolvedOptimistically && isDataOwnerGenerationCurrent(record.dataOwner)) {+ try {+ record.onRemoteOptimisticFailure?.(clientId, error);+ } catch (restoreError) {+ log.warn('remote optimistic composer restore failed:', restoreError);+ }+ }+ // The callback republishes restored draft attachment URLs synchronously.+ // Retire the outbox ref afterwards so media protection transfers without a+ // cleanup-eligible gap in main's renderer registry.+ clearRemoteOptimisticSend(sessionId, clientId);+ setState(sessionId, (s) => ({+ ...s,+ pendingQueue: s.pendingQueue.filter((item) => item.clientId !== clientId),+ messages: s.messages.filter(+ (message) => !(message.clientId === clientId && message.isPendingPersist),+ ),+ ...(error !== undefined+ ? {+ error: decodeRemoteErrorMessage(error instanceof Error ? error.message : String(error)),+ usageLimitRecovery: null,+ errorReason: null,+ recoverableError: null,+ errorRetryText: null,+ }+ : {}),+ }));+}++async function pumpRemoteOptimisticSends(sessionId: string): Promise<void> {+ const existing = remoteOptimisticPumps.get(sessionId);+ if (existing) return existing;+ // Self-reference is intentional: a detached clear/owner generation must not+ // keep draining after a newer pump replaces this Promise in the registry.+ // eslint-disable-next-line prefer-const+ let run!: Promise<void>;+ run = (async () => {+ while (true) {+ const record = firstUnacceptedRemoteOptimisticSend(sessionId);+ if (!record || record.dispatching) return;+ const prepared = await prepareRemoteOptimisticSend(sessionId, record);+ if (prepared.kind === 'deferred') return;+ if (prepared.kind === 'cancelled') {+ if (remoteOptimisticPumps.get(sessionId) !== run) return;+ continue;+ }+ if (prepared.kind === 'failed') {+ settleRemoteOptimisticFailure(sessionId, record.queued.clientId, prepared.error);+ continue;+ }+ const result = await dispatchRemoteOptimisticSend(sessionId, record);+ if (result.kind === 'deferred') return;+ if (result.kind === 'retry') continue;+ // A DB ACK may retire this record before its invoke response arrives. That+ // cancellation settles only the current item; later FIFO entries still need+ // the active pump to dispatch them deterministically. A clear/owner boundary,+ // however, detaches the old pump so it cannot race a newer generation.+ if (result.kind === 'cancelled') {+ if (remoteOptimisticPumps.get(sessionId) !== run) return;+ continue;+ }+ if (result.kind === 'failed') {+ settleRemoteOptimisticFailure(sessionId, record.queued.clientId, result.error);+ continue;+ }+ }+ })().finally(() => {+ if (remoteOptimisticPumps.get(sessionId) === run) remoteOptimisticPumps.delete(sessionId);+ });+ remoteOptimisticPumps.set(sessionId, run);+ return run;+}++function pumpRemoteOptimisticSendsAfterCurrent(sessionId: string): void {+ const existing = remoteOptimisticPumps.get(sessionId);+ if (!existing) {+ void pumpRemoteOptimisticSends(sessionId);+ return;+ }+ const clearGenerationAtSchedule = rendererClearGenerationBySession.get(sessionId) ?? 0;+ const dataOwnerAtSchedule = getDataOwnerGeneration();+ const rerunIfCurrent = () => {+ if (!isDataOwnerGenerationCurrent(dataOwnerAtSchedule)) return;+ if ((rendererClearGenerationBySession.get(sessionId) ?? 0) !== clearGenerationAtSchedule) {+ return;+ }+ void pumpRemoteOptimisticSends(sessionId);+ };+ void existing.then(rerunIfCurrent, rerunIfCurrent);+}+/*** 会直接触发 Agent 工作的 input 操作统一入口。与纯投影操作分开,避免 setExpanded / 清锁* 等内部收尾在切换期间被拒后残留状态;compact / retry / resume 这类用户派发则从 RPC@@ -5829,11 +8561,15 @@ const _cacheHydrateSuppressed = new Set<string>();function hydrateRemoteMessagesFromCache(sessionId: string): void {const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);if (!deviceId) return;+ const epochAtStart = _messagesEpoch.get(sessionId) ?? 0;+ const isCurrentHydration = () =>+ sessions.has(sessionId) && (_messagesEpoch.get(sessionId) ?? 0) === epochAtStart;// 作废式重载(rewind)之后盘上那份是过期窗口:权威数据没落地之前一律不借。if (_cacheHydrateSuppressed.has(sessionId)) return;if (_cacheHydrateStarted.has(sessionId)) return;_cacheHydrateStarted.add(sessionId);void readCachedMessages(deviceId, sessionId).then((rows) => {+ if (!isCurrentHydration()) return;if (rows.length === 0) return;// 缓存页整页都是"渲染后不留可见锚点"的行(orphan tool_result / 隐藏 thinking /// 合成指令行)时**不种入**:mapServerMessages 会产出非空数组,但 MessageStream 渲染 0 项,@@ -5844,10 +8580,7 @@ function hydrateRemoteMessagesFromCache(sessionId: string): void {...message,cacheHydrated: true as const,}));- if (- rows.every(isNonAnchorHistoryRow) &&- getLatestMessageTodoState(mapped).insertion === null- ) {+ if (rows.every(isNonAnchorHistoryRow) && getLatestMessageTodoState(mapped).insertion === null) {return;}if (mapped.length === 0) return;@@ -5860,6 +8593,7 @@ function hydrateRemoteMessagesFromCache(sessionId: string): void {// 切片被清空并置了抑制 —— 只在入口检查挡不住这笔在途的读,它会把 rewind 之前的行// 插进刚清空的切片,权威首拉再失败就一直留在屏上(review: codex P1)。if (_cacheHydrateSuppressed.has(sessionId)) return;+ if (!isCurrentHydration()) return;setState(sessionId, (s) => {// fresh 已经落地 / 期间已有实时消息进来 → 缓存没有价值了,原样返回不动切片。if (s.historyLoaded || s.messages.length > 0) return s;@@ -5883,8 +8617,11 @@ function hydrateRemoteMessagesFromCache(sessionId: string): void {* 2. 清盘 —— 进程内标记跨重启就没了,盘上那份必须一起消失。* 本机会话没有缓存,直接 no-op。*/-function invalidateRemoteMessageCache(sessionId: string): void {- const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);+function invalidateRemoteMessageCache(sessionId: string, pinnedDeviceId?: string): void {+ const deviceId =+ pinnedDeviceId ??+ getStickySessionDeviceId(sessionId) ??+ remoteProjectsStore.getSessionDeviceId(sessionId);if (!deviceId) return;_cacheHydrateStarted.add(sessionId);_cacheHydrateSuppressed.add(sessionId);@@ -5916,16 +8653,18 @@ function ensureInitialMessages(sessionId: string): void {}if (state.historyLoaded) return;if (_historyFetchInFlight.has(sessionId)) return;+ const historyEpochAtStart = _messagesEpoch.get(sessionId) ?? 0;+ const historyOriginAtStart = remoteProjectsStore.getSessionDeviceId(sessionId);+ const historyFetchToken = ++_nextHistoryFetchToken;+ _historyFetchToken.set(sessionId, historyFetchToken);+ const isCurrentHistoryLoad = () =>+ isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart);// 行水合并行异步读的陈旧性守卫: fetch 启动时定格 rev, 应用时比对(见 planModeRev)。const planModeRevAtFetchStart = state.planModeRev;// Mark in-flight to prevent concurrent callers from double-fetching.// historyLoaded stays false until data actually arrives._historyFetchInFlight.add(sessionId);- const historyFetchToken = ++_nextHistoryFetchToken;- _historyFetchToken.set(sessionId, historyFetchToken);- const historyEpochAtStart = _messagesEpoch.get(sessionId) ?? 0;- const historyOriginAtStart = remoteProjectsStore.getSessionDeviceId(sessionId);// 记录本次加载所依据的 origin(可能 undefined)。remote-projects 注入该会话来源后,// reconcileOpenSessionOrigins 比对此值发现漂移 → 重载(见上方说明)。_historyLoadOrigin.set(sessionId, historyOriginAtStart);@@ -6033,6 +8772,7 @@ function ensureInitialMessages(sessionId: string): void {// 冷缓存 hydrate 出来的行必须在这里一并抹掉,否则控制端会一直显示被清掉的正文。// 盘上那份不用在这里单独删:listMessagesFor 的写点收到空页时就把缓存清了。settleCacheHydration(sessionId);+ if (!isCurrentHistoryLoad()) return;setState(sessionId, (s) => ({...s,messages: s.messages.some((m) => m.cacheHydrated === true)@@ -6043,7 +8783,7 @@ function ensureInitialMessages(sessionId: string): void {}));_historyFetchInFlight.delete(sessionId);// 历史加载完 → 重建当前挂起交互(新窗口/重连/刷新打开时面板才会出现)。- reconcilePendingInteractions(sessionId);+ void reconcilePendingInteractions(sessionId, isCurrentHistoryLoad).catch(() => undefined);return;}@@ -6082,7 +8822,7 @@ function ensureInitialMessages(sessionId: string): void {hasMoreMessages: false,}));_historyFetchInFlight.delete(sessionId);- reconcilePendingInteractions(sessionId);+ void reconcilePendingInteractions(sessionId).catch(() => undefined);return;}let hasMore = serverMessagePageHasMore(existing);@@ -6142,6 +8882,7 @@ function ensureInitialMessages(sessionId: string): void {let pagesFetched = 0;let planResolutionPagesFetched = 0;while (hasMore) {+ if (!isCurrentHistoryLoad()) return;const needsAnchorBackfill =merged.every(isNonAnchorHistoryRow) && pagesFetched < MAX_NO_ANCHOR_BACKFILL_PAGES;const planState = historyRowsPlanBackfillState(merged, hasMore);@@ -6198,6 +8939,7 @@ function ensureInitialMessages(sessionId: string): void {const mapped = mapServerMessages(merged);const oldestId = oldestRow.id;settleCacheHydration(sessionId);+ if (!isCurrentHistoryLoad()) return;setState(sessionId, (s) => ({...s,historyLoaded: true,@@ -6249,7 +8991,7 @@ function ensureInitialMessages(sessionId: string): void {_historyFetchInFlight.delete(sessionId);// 历史加载完 → 重建当前挂起交互:历史里被转 expired 的 ask/plan 在此翻回 pending// (按 requestId 去重,不重复),permission 重新置 pendingPermission。- reconcilePendingInteractions(sessionId);+ void reconcilePendingInteractions(sessionId, isCurrentHistoryLoad).catch(() => undefined);}).catch(() => {if (!isCurrentHistoryFetch(sessionId, historyFetchToken, historyOriginAtStart, historyEpochAtStart)) {@@ -6263,6 +9005,7 @@ function ensureInitialMessages(sessionId: string): void {}// Allow retry on next mount_historyFetchInFlight.delete(sessionId);+ _historyFetchToken.delete(sessionId);// 首拉失败(典型:被控端离线)→ 放开「本轮已发起」的守卫以便下次重试,但**不解除**// rewind 之类的粘滞抑制(见 releaseCacheHydrationAfterFailure)。屏上已 hydrate 的// 缓存行**保持不动**:离线时它是用户唯一能看到的历史,清掉纯属倒退。@@ -6285,6 +9028,7 @@ function reloadMessages(sessionId: string, opts?: { allowCacheHydrate?: booleaninvalidateHistoryFetch(sessionId);// Drop the in-flight guard so ensureInitialMessages can run again._historyFetchInFlight.delete(sessionId);+ _historyFetchToken.delete(sessionId);// 默认**不借**冷缓存:rewind 截断这类重载的起因恰恰意味着盘上那份缓存已经过期,// hydrate 它只会先闪一下刚被截掉的消息。重载后的首拉照常刷新缓存。//@@ -6305,22 +9049,34 @@ function reloadMessages(sessionId: string, opts?: { allowCacheHydrate?: boolean// 成功时会重新写上。invalidateRemoteMessageCache(sessionId);}- setState(sessionId, (s) => ({- ...s,- messages: [],- taskUpdates: new Map(),- pendingTaskWake: false,- historyLoaded: false,- hasMoreMessages: false,- oldestMessageId: null,- isStreaming: false,- // 窗口从最新重新拉起 → 不再有孤岛。- historyWindowHasIsland: false,- // 分页锁归本次重置释放:窗口和游标都清了,in-flight 的翻页 / 跳转补齐也已被上面的- // bumpMessagesEpoch 作废,锁再留着只会让行首守卫卡住下一次翻页。由这里清而不是- // 让被作废的请求代清 —— 它们无法分辨锁是自己那一代的还是重置后新代际的(#676 review)。- isLoadingMore: false,- }));+ setState(sessionId, (s) => {+ const optimisticRecords = remoteOptimisticSendRecords(sessionId);+ const optimisticMessages = optimisticRecords+ ? s.messages.filter(+ (message) => message.isPendingPersist === true && optimisticRecords.has(message.clientId),+ )+ : [];+ return {+ ...s,+ // Origin reconciliation may reload history immediately after the local+ // outbox projects a bubble (for example when auto-title preview notifies+ // remoteProjectsStore). Preserve those unacknowledged local rows while+ // the authoritative history window resets.+ messages: optimisticMessages,+ taskUpdates: new Map(),+ pendingTaskWake: false,+ historyLoaded: false,+ hasMoreMessages: false,+ oldestMessageId: null,+ isStreaming: false,+ // 窗口从最新重新拉起 → 不再有孤岛。+ historyWindowHasIsland: false,+ // 分页锁归本次重置释放:窗口和游标都清了,in-flight 的翻页 / 跳转补齐也已被上面的+ // bumpMessagesEpoch 作废,锁再留着只会让行首守卫卡住下一次翻页。由这里清而不是+ // 让被作废的请求代清 —— 它们无法分辨锁是自己那一代的还是重置后新代际的(#676 review)。+ isLoadingMore: false,+ };+ });ensureInitialMessages(sessionId);}@@ -6453,6 +9209,7 @@ function reconcileOpenSessionOrigins(): void {// 最初按 A 发起的旧查询在来源恢复后重新通过检查,覆盖恢复后的权威投影。const originChange = noteInputProjectionOrigin(sessionId, current);if (originChange.changed) {+ bumpInteractionReconcileEpoch(sessionId);// 来源变更后旧设备的 owner / capability 都失效。在新来源 projection 回来前// fail closed,不能让 B 的历史沿用 A 的精确 owner 或 legacy 兜底。setState(sessionId, (state) => ({@@ -6790,6 +9547,7 @@ function finalizeStuckRemoteTurn(sessionId: string): void {if (!isRemoteSession(sessionId)) return;// 看门狗确认被控端已停止 = 权威终态;在清本地 owner 前先作废所有旧查询,// 防止 stall 期间悬挂的 getProjection 随后把已死 turn 重新点亮。+ bumpInteractionReconcileEpoch(sessionId);supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });flushPendingTextDelta(sessionId); // 收尾前把残留增量落定,避免丢最后一截文本setState(sessionId, forceFinalizeOnSessionClosed);@@ -7305,8 +10063,7 @@ function commitAroundWindow(// 既有回归「hands the cursor back to the latest page when initial history resolves after// a jump」与「keeps search result windows in chronological order across jumps」守着这条。oldestMessageId:- s.oldestMessageId ??- oldestServerMessageIdForWindow(rows, s.messages, null, 'oldest-first'),+ s.oldestMessageId ?? oldestServerMessageIdForWindow(rows, s.messages, null, 'oldest-first'),// hasMoreMessages:**merge 真的加进了行**时置 true,否则保持原值。//// 置 true 的理由:那些新行比旧游标更早(否则早就 covered 了),窗口最老边界因此前移,@@ -7349,7 +10106,6 @@ async function loadAroundMessage(? getOrCreateState(sessionId).messages.find((message) => message.clientId === targetClientId): undefined;-// 优先把窗口从最新连续补齐到目标,不留历史空洞(见 backfillHistoryUntil)。// 补不到(超上限 / 翻完 / 让位并发分页)则退回 around 窗口 merge:此时窗口仍不// 连续,由渲染层的 HISTORY_GAP_SPLIT_MS 守卫兜底,不至于把两段折成一个工作组。@@ -7378,11 +10134,7 @@ async function loadAroundMessage(// 干净,但会反转十几处既有测试的 mock 前提(它们用 around 播种窗口而 list 默认返回空页),// 故留作独立改动;陈旧行的生命周期止于会话重建(reload / clear / demote / trim),// 不持久化、不跨会话(#676 review)。- if (- outcome === 'cancelled' ||- (_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart- )- return null;+ if (outcome === 'cancelled' || (_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart) return null;commitAroundWindow(sessionId,@@ -7395,9 +10147,8 @@ async function loadAroundMessage(if (!targetClientId) return null;return (- getOrCreateState(sessionId).messages.find(- (message) => message.clientId === targetClientId,- ) ?? null+ getOrCreateState(sessionId).messages.find((message) => message.clientId === targetClientId) ??+ null);}@@ -7419,22 +10170,14 @@ async function loadAroundMessageClientId((message) => message.clientId === clientId,);- const { outcome, ownsPagingLock } = await backfillHistoryUntil(- sessionId,- clientId,- epochAtStart,- );+ const { outcome, ownsPagingLock } = await backfillHistoryUntil(sessionId, clientId, epochAtStart);// 切片被重置 → 跳转作废,不 merge 旧的 around 行。merge 前再校验一次 epoch:outcome// 只反映 backfill 返回那一刻的代际,它 return 之后到这里恢复之间还有一个 microtask// 间隙(见 loadAroundMessage 同款注释)。//// exhausted 不作废,取舍见 loadAroundMessage 的同款注释。- if (- outcome === 'cancelled' ||- (_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart- )- return null;+ if (outcome === 'cancelled' || (_messagesEpoch.get(sessionId) ?? 0) !== epochAtStart) return null;commitAroundWindow(sessionId,@@ -7473,8 +10216,9 @@ function buildQueuedMessage(/** 订阅槽①:透传一次性跳过意识拦截钩标记(预留;v1 无强制发送 UI,无调用点置位)。 */bypassGhostHooks?: boolean;},+ identity?: { clientId: string; createdAt: string },): QueuedMessage {- const clientId = crypto.randomUUID();+ const clientId = identity?.clientId ?? crypto.randomUUID();const attachmentPayload = buildUserMessageAttachmentPayload(files);const { serializedFiles, imageAttachments, fileAttachments, persistImageRefs, persistFileRefs } =attachmentPayload;@@ -7493,7 +10237,7 @@ function buildQueuedMessage(role: 'user',content: text,isStreaming: false,- createdAt: new Date().toISOString(),+ createdAt: identity?.createdAt ?? new Date().toISOString(),...(opts?.quotesEncoded === true && { quotesEncoded: true }),...(opts?.agentReferences?.length && { agentReferences: opts.agentReferences }),...(opts?.pastedTextRanges?.length && { pastedTextRanges: opts.pastedTextRanges }),@@ -7542,6 +10286,56 @@ function buildQueuedMessage(};}+function completeRemoteOptimisticMaterialization(+ sessionId: string,+ clientId: string,+ buildMaterializedQueued: () => QueuedMessage,+): void {+ const record = remoteOptimisticSendRecords(sessionId)?.get(clientId);+ if (+ !record ||+ !record.materializationPending ||+ !isRemoteOptimisticSendRegistered(sessionId, record)+ ) {+ return;+ }++ const previousQueued = record.queued;+ const queued = buildMaterializedQueued();+ // createOpts / userName 属于点击时快照。附件烧录期间设置或登录态可能变化,+ // 不能让迟到物化把这条消息悄悄改成新的发送配置。+ queued.createOpts = previousQueued.createOpts;+ if (previousQueued.userName === undefined) delete queued.userName;+ else queued.userName = previousQueued.userName;++ record.queued = queued;+ record.materializationPending = false;+ record.phase = 'preflight';+ record.attachmentUrls = [+ ...new Set([...record.attachmentUrls, ...collectRemoteOptimisticAttachmentUrls(queued.files)]),+ ];+ syncRemoteOptimisticAttachmentUrls();++ setState(sessionId, (state) => {+ let changed = false;+ const pendingQueue = state.pendingQueue.map((item) => {+ if (item.clientId !== clientId || item.isPendingEnqueue !== true) return item;+ changed = true;+ return { ...queued, isPendingEnqueue: true };+ });+ const messages = state.messages.map((message) => {+ if (message.clientId !== clientId || message.isPendingPersist !== true) return message;+ changed = true;+ return { ...queued.chatMessage, isPendingPersist: true };+ });+ return changed ? { ...state, pendingQueue, messages } : state;+ });+ const onMaterializationReady = record.onMaterializationReady;+ delete record.onMaterializationReady;+ onMaterializationReady?.(queued);+ pumpRemoteOptimisticSendsAfterCurrent(sessionId);+}+function extractSessionRefs(text: string,previous?: readonly AgentInputSessionRef[],@@ -7561,7 +10355,7 @@ function buildCreateOptsForCurrentSession(opts?: { vendorOptions?: Record<string, unknown> },): AgentInputCreateOpts {const current = getOrCreateState(sessionId);- const deviceLinkRemote = isRemoteSession(sessionId);+ const deviceLinkRemote = isRemoteSessionSticky(sessionId);return {agentKind: current.agentKind,workingDir,@@ -7604,35 +10398,49 @@ function touchSessionUserSend(sessionId: string, workingDir: string, wasFirst: b*/function setQueueExpanded(sessionId: string, expanded: boolean): void {if (!sessionId) return;+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);runInputProjectionOperation(sessionId, (input) =>- input.setExpanded(sessionId, expanded),+ boundaryOpts+ ? input.setExpanded(sessionId, expanded, boundaryOpts)+ : input.setExpanded(sessionId, expanded),).catch((err) => log.warn('setQueueExpanded failed:', err));}function resumeQueue(sessionId: string): void {if (!sessionId) return;- runAgentDispatchProjectionOperation(sessionId, (input) => input.resume(sessionId))- .catch((err) => log.warn('resumeQueue failed:', err));+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);+ runAgentDispatchProjectionOperation(sessionId, (input) =>+ boundaryOpts ? input.resume(sessionId, boundaryOpts) : input.resume(sessionId),+ ).catch((err) => log.warn('resumeQueue failed:', err));}function setQueueInteractionLock(sessionId: string, lockId: string, locked: boolean): void {if (!sessionId || !lockId) return;+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);runInputProjectionOperation(sessionId, (input) =>- input.setInteractionLock(sessionId, lockId, locked),+ boundaryOpts+ ? input.setInteractionLock(sessionId, lockId, locked, boundaryOpts)+ : input.setInteractionLock(sessionId, lockId, locked),).catch((err) => log.warn('setQueueInteractionLock failed:', err));}function setQueueEditLock(sessionId: string, clientId: string, locked: boolean): void {if (!sessionId || !clientId) return;+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);runInputProjectionOperation(sessionId, (input) =>- input.setEditLock(sessionId, clientId, locked),+ boundaryOpts+ ? input.setEditLock(sessionId, clientId, locked, boundaryOpts)+ : input.setEditLock(sessionId, clientId, locked),).catch((err) => log.warn('setQueueEditLock failed:', err));}function moveQueueItem(sessionId: string, clientId: string, targetIndex: number): void {if (!sessionId || !clientId) return;+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);runInputProjectionOperation(sessionId, (input) =>- input.move(sessionId, clientId, targetIndex),+ boundaryOpts+ ? input.move(sessionId, clientId, targetIndex, boundaryOpts)+ : input.move(sessionId, clientId, targetIndex),).catch((err) => log.warn('moveQueueItem failed:', err));}@@ -7645,8 +10453,18 @@ function moveQueueItem(sessionId: string, clientId: string, targetIndex: number)*/function removeFromQueue(sessionId: string, clientId: string): void {if (!sessionId || !clientId) return;- runInputProjectionOperation(sessionId, (input) => input.remove(sessionId, clientId))- .catch((err) => log.warn('removeFromQueue failed:', err));+ markRemoteOptimisticLocallyRemoved(sessionId, clientId);+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);+ runInputProjectionOperation(sessionId, (input) =>+ boundaryOpts+ ? input.remove(sessionId, clientId, boundaryOpts)+ : input.remove(sessionId, clientId),+ )+ .then(() => clearRemoteOptimisticSend(sessionId, clientId))+ .catch((err) => {+ unmarkRemoteOptimisticLocallyRemoved(sessionId, clientId);+ log.warn('removeFromQueue failed:', err);+ });}/**@@ -7661,13 +10479,23 @@ function updateQueueItem(sessionId: string, clientId: string, newText: string):const trimmed = newText.trim();if (!trimmed) return;const queued = getOrCreateState(sessionId).pendingQueue.find((q) => q.clientId === clientId);+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);runInputProjectionOperation(sessionId, (input) =>- input.updateText(- sessionId,- clientId,- newText,- extractSessionRefs(newText, queued?.sessionRefs),- ),+ boundaryOpts+ ? input.updateText(+ sessionId,+ clientId,+ newText,+ extractSessionRefs(newText, queued?.sessionRefs),+ undefined,+ boundaryOpts,+ )+ : input.updateText(+ sessionId,+ clientId,+ newText,+ extractSessionRefs(newText, queued?.sessionRefs),+ ),).catch((err) => log.warn('updateQueueItem failed:', err));}@@ -7722,7 +10550,10 @@ function scheduleAutoName(const fallbackTitle = normalizeAutoTitle(text);// 连描述都合成不出来(既无文字也无可命名附件):保留默认标题,留给下一条消息。if (!fallbackTitle) return;- if (isRemoteSession(sessionId)) {+ // mirror clear / relay reconnect can empty remoteProjectsStore after the+ // message was accepted. Keep the title preview on the last known device too;+ // otherwise this same remote message is treated as a local title update.+ if (getStickySessionDeviceId(sessionId)) {// 带上 isUserText:合成描述对应「被控端先写占位、之后还要换掉」,要登记成系统// 占位归属;用户文字对应的标题可能就此定稿,登记了会让后续预览一直盖着它。remoteProjectsStore.setPendingTitlePreview(sessionId, fallbackTitle, isUserText);@@ -7854,13 +10685,15 @@ type SendMessageOpts = {};/** 一次性跳过意识拦截钩(订阅槽①,预留;v1 无强制发送 UI):透传到排队项。 */bypassGhostHooks?: boolean;+ /** 远程预检在乐观投影建立后执行;false 时按 clientId 精确回滚。 */+ beforeEnqueue?: () => Promise<boolean>;+ /** 远程乐观发送在稍后确认永久失败时恢复 composer。 */+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;};/** remote(SSH / device-link)会话:标注编辑数据指向控制端本地缓存,发送时剥离。 */function isRemoteMediaSession(sessionId: string): boolean {- return Boolean(- getOrCreateState(sessionId).remoteHostId ?? remoteProjectsStore.getSessionDeviceId(sessionId),- );+ return Boolean(getOrCreateState(sessionId).remoteHostId ?? getStickySessionDeviceId(sessionId));}/**@@ -7898,6 +10731,20 @@ function sendMessage(// Allow send if there is text OR filesif ((!text.trim() && (!files || files.length === 0)) || !workingDir)return Promise.resolve(false);+ if (isRemoteDeletedSessionSendBlocked(sessionId)) return Promise.resolve(false);+ const remoteScopeAtStart = captureRemoteOptimisticSendScope(+ sessionId,+ opts?.onRemoteOptimisticFailure,+ );+ // A remote clear is allowed to seal in the background. Register the local+ // optimistic item and let its pump wait on the clear fence; local sessions+ // retain the historical synchronous guard.+ if (remoteClearInFlight.has(sessionId) && !remoteScopeAtStart) return Promise.resolve(false);+ if (remoteScopeAtStart && !isRemoteOptimisticSendScopeActive(sessionId, remoteScopeAtStart)) {+ return Promise.resolve(false);+ }+ const clearGenerationAtStart =+ remoteScopeAtStart?.clearGeneration ?? rendererClearGenerationBySession.get(sessionId) ?? 0;// 共享发送边界兜住 composer 之外的入口(编辑重发、恢复等)。ChatInput 会从引用// 水合阶段先持有一层 token;这里允许嵌套登记,确保未来新增调用方也不会绕过@@ -7921,22 +10768,88 @@ function sendMessage(files,mentions,opts,+ clearGenerationAtStart,+ remoteScopeAtStart,);}- return materializeAnnotatedAttachmentsForSend(files, sessionId, {- stripAnnotationMeta: isRemoteMediaSession(sessionId),- }).then((prepared) =>- sendMessageCore(+ if (remoteScopeAtStart) {+ const identity = {+ clientId: crypto.randomUUID(),+ createdAt: new Date().toISOString(),+ };+ const stripAnnotationMeta = isRemoteMediaSession(sessionId);+ // 先用原图建立稳定 clientId 的本地气泡/outbox,再后台烧录标注。这样+ // ChatInput 立即拿到 true、可继续输入;pump 会被 materializationPending+ // 挡住,绝不会把未烧录 payload 发到被控端。+ const accepted = sendMessageCore(sessionId,text,model,effort,permissionMode,workingDir,- prepared,+ files,mentions,opts,- ),+ clearGenerationAtStart,+ remoteScopeAtStart,+ files,+ identity,+ true,+ );+ void accepted.then(+ (optimisticallyAccepted) => {+ if (!optimisticallyAccepted) return;+ void materializeAnnotatedAttachmentsForSend(files, sessionId, {+ stripAnnotationMeta,+ })+ .then((prepared) => {+ completeRemoteOptimisticMaterialization(sessionId, identity.clientId, () =>+ buildQueuedMessage(+ sessionId,+ text,+ model,+ effort,+ permissionMode,+ workingDir,+ prepared,+ mentions,+ opts,+ identity,+ ),+ );+ })+ .catch((error) => {+ const record = remoteOptimisticSendRecords(sessionId)?.get(identity.clientId);+ if (record?.materializationPending) {+ settleRemoteOptimisticFailure(sessionId, identity.clientId, error);+ }+ });+ },+ () => undefined,+ );+ return accepted;+ }+ return runRemoteOptimisticMaterialization(+ null,+ materializeAnnotatedAttachmentsForSend(files, sessionId, {+ stripAnnotationMeta: isRemoteMediaSession(sessionId),+ }),+ (prepared) =>+ sendMessageCore(+ sessionId,+ text,+ model,+ effort,+ permissionMode,+ workingDir,+ prepared,+ mentions,+ opts,+ clearGenerationAtStart,+ remoteScopeAtStart,+ files,+ ),);},);@@ -7953,7 +10866,20 @@ async function sendMessageCore(files?: AttachedFile[],mentions?: MentionedResource[],opts?: SendMessageOpts,+ clearGenerationAtStart = 0,+ remoteScopeAtStart: RemoteOptimisticSendScope | null = null,+ recoveryFiles?: readonly AttachedFile[],+ identity?: { clientId: string; createdAt: string },+ materializationPending = false,): Promise<boolean> {+ if (+ (remoteClearInFlight.has(sessionId) && !remoteScopeAtStart) ||+ (remoteScopeAtStart+ ? !isRemoteOptimisticSendScopeActive(sessionId, remoteScopeAtStart)+ : (rendererClearGenerationBySession.get(sessionId) ?? 0) !== clearGenerationAtStart)+ ) {+ return false;+ }const current = getOrCreateState(sessionId);const wasFirst = current.isFirstMessage;@@ -7967,8 +10893,67 @@ async function sendMessageCore(files,mentions,opts,+ identity,);+ const deviceLinkRemote = remoteScopeAtStart !== null;+ const remoteRecord = remoteScopeAtStart+ ? registerRemoteOptimisticSend(+ sessionId,+ queued,+ remoteScopeAtStart.deviceId,+ 'queue',+ remoteScopeAtStart.dataOwner,+ remoteScopeAtStart.recoverySequence,+ remoteScopeAtStart.expectedClearBoundaryMs,+ opts,+ recoveryFiles ?? files,+ materializationPending,+ )+ : undefined;+ if (deviceLinkRemote && !remoteRecord) return false;++ // device-link 乐观第一拍:空闲沿用消息流气泡,忙时也立即显示 sending 队列行。+ if (deviceLinkRemote && isSendBusyForQueue(current)) {+ setState(sessionId, (s) =>+ s.pendingQueue.some((item) => item.clientId === queued.clientId)+ ? s+ : { ...s, pendingQueue: [...s.pendingQueue, { ...queued, isPendingEnqueue: true }] },+ );+ } else if (!isSendBusyForQueue(current)) {+ setState(sessionId, (s) =>+ s.messages.some((m) => m.clientId === queued.clientId)+ ? s+ : { ...s, messages: [...s.messages, { ...queued.chatMessage, isPendingPersist: true }] },+ );+ }++ if (!deviceLinkRemote && opts?.beforeEnqueue) {+ try {+ if (!(await opts.beforeEnqueue())) {+ clearRemoteOptimisticSend(sessionId, queued.clientId);+ setState(sessionId, (s) => ({+ ...s,+ pendingQueue: s.pendingQueue.filter((item) => item.clientId !== queued.clientId),+ messages: s.messages.filter(+ (message) => !(message.clientId === queued.clientId && message.isPendingPersist),+ ),+ }));+ return false;+ }+ } catch (err) {+ clearRemoteOptimisticSend(sessionId, queued.clientId);+ setState(sessionId, (s) => ({+ ...s,+ pendingQueue: s.pendingQueue.filter((item) => item.clientId !== queued.clientId),+ messages: s.messages.filter(+ (message) => !(message.clientId === queued.clientId && message.isPendingPersist),+ ),+ }));+ throw err;+ }+ }+// 一次性契约收口(bot review P2):计划勾选在**点击发送**时消耗——本条消息的计划// 意图已定格在行内快照(createOpts.planMode,派发时经 SendOptions.planMode 权威// 生效),这里立即熄灭 store/DB/runtime 的勾选,会话忙时连续排队的后续消息不再@@ -7989,34 +10974,40 @@ async function sendMessageCore(// previous turn). Safe to leave outside the isBusy branch.// 首条与补起名共用同一套素材推导:用户没打字时 seed.isUserText=false,// 只写合成占位、不调标题模型。- const autoTitleSeed = deriveAutoTitleSeed(queued, autoTitleFallbackLabels());- if (wasFirst) {- // 用会话真实 agentKind 起名 — 之前写死 'claude-code',导致 Codex 会话也- // 用 Claude haiku 起标题:纯 Codex 用户(无 Claude 鉴权)会 oneShot 失败 →- // fallback 原话,表现为"Codex 会话标题没有智能总结"。current.agentKind 已是- // maker 格式('claude-code' | 'codex' | 'pi'),直接透传。起名走立即占位 + 后台覆盖。- if (autoTitleSeed) {- scheduleAutoName(sessionId, autoTitleSeed.text, current.agentKind, autoTitleSeed.isUserText);+ const commitAutoTitle = (titleQueued = queued) => {+ const autoTitleSeed = deriveAutoTitleSeed(titleQueued, autoTitleFallbackLabels());+ if (wasFirst) {+ // 用会话真实 agentKind 起名 — 之前写死 'claude-code',导致 Codex 会话也+ // 用 Claude haiku 起标题:纯 Codex 用户(无 Claude 鉴权)会 oneShot 失败 →+ // fallback 原话,表现为"Codex 会话标题没有智能总结"。current.agentKind 已是+ // maker 格式('claude-code' | 'codex' | 'pi'),直接透传。起名走立即占位 + 后台覆盖。+ if (autoTitleSeed) {+ scheduleAutoName(+ sessionId,+ autoTitleSeed.text,+ current.agentKind,+ autoTitleSeed.isUserText,+ );+ }+ return;}- } else {// 补起名:首条是纯附件(只贴图没打字)、标题还是合成占位或默认名的会话,以及// fork 出来的占位标题会话,都在第一条带文字的消息上把标题换成用户写的内容。maybeAutoNameUnnamedSession(sessionId, autoTitleSeed, current.agentKind);+ };+ if (materializationPending && remoteRecord) {+ remoteRecord.onMaterializationReady = commitAutoTitle;+ } else {+ commitAutoTitle();}- // 视觉连续性: agent 空闲 + 队列为空时, main coordinator 会立即派发这条(见- // agent-input-coordinator.enqueue 的 immediate 分支)。提前乐观把 user 气泡 push- // 进消息流, 让"按 Enter → 气泡出现"既无队列灰字闪烁、也没有等 DB 广播回投的空窗。- // busy 判定取镜像于 main getDrainableHead(isSendBusyForQueue = boundary busy ||- // 队列非空)。派发落库后 localDb.messages.onCreated 广播按 clientId dedupe 不会重复;- // 若 race 导致 main 实际排了队 / 派发失败回退, applyInputProjection 会按 pendingQueue- // 的 clientId 撤回这条乐观气泡, 回落到队列态。- if (!isSendBusyForQueue(current)) {- setState(sessionId, (s) =>- s.messages.some((m) => m.clientId === queued.clientId)- ? s- : { ...s, messages: [...s.messages, { ...queued.chatMessage, isPendingPersist: true }] },- );+ if (deviceLinkRemote && remoteRecord) {+ // Device-link sends are locally accepted as soon as their immutable outbox+ // record and optimistic projection exist. The pump owns even the first+ // preflight/invoke so a weak link never holds the composer dispatch lock.+ remoteRecord.composerResolvedOptimistically = true;+ void pumpRemoteOptimisticSends(sessionId);+ return true;}const operation = beginInputProjectionOperation(sessionId);@@ -8034,22 +11025,14 @@ async function sendMessageCore(}const applied = applyInputProjectionOperationResponse(sessionId, operation, projection);if (applied) markSessionHasUserMessage(sessionId);- // RPC 已在发起时的设备上成功受理;origin 期间漂移只意味着旧 projection- // 不能写进当前镜像,不应向 composer 谎报发送失败并诱导用户重复发送。return true;}).catch((err) => {// 远端 lazy-create/startSession 抛的 [REMOTE_*] 不可恢复错误走 IPC reject 落这里// (不经 stream error event reducer),同样要解码成 i18n 文案,别裸显 bracket code。const message = decodeRemoteErrorMessage(err instanceof Error ? err.message : String(err));- // 远程会话:enqueue reject(NOT_CONNECTED / ACCESS_REVOKED / DEVICE_LINK_MEDIA_TRANSFER_FAILED 等)- // 后不会有 input projection 回来撤回乐观气泡,这里按 clientId 主动移除,避免一条没真正发出的- // 消息残留在 transcript。本地会话走 projection 撤回(busy 排队/派发失败回落),不动。setState(sessionId, (s) => ({...s,- messages: isRemoteSession(sessionId)- ? s.messages.filter((m) => !(m.clientId === queued.clientId && m.isPendingPersist))- : s.messages,error: message,usageLimitRecovery: null,errorReason: null,@@ -8082,22 +11065,28 @@ function compactSession(// /compact 是控制 turn(上下文压缩), 与 sendUiTrigger 同口径: 显式普通执行,// 不进计划模式、不消耗用户的一次性勾选(false 语义见 SendOptions.planMode)。createOpts.planMode = false;- return runAgentDispatchProjectionOperation(sessionId, (input) =>- input.compact(sessionId, createOpts, { userName: currentUserName }),- )- // RPC 已执行成功时保留既有返回语义;origin 漂移只丢控制端镜像回写。- .then(({ projection }) => projection.error === null)- .catch((err) => {- const message = decodeRemoteErrorMessage(err instanceof Error ? err.message : String(err));- setState(sessionId, (s) => ({- ...s,- error: message,- usageLimitRecovery: null,- recoverableError: null,- errorRetryText: null,- }));- return false;- });+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);+ return (+ runAgentDispatchProjectionOperation(sessionId, (input) =>+ input.compact(sessionId, createOpts, {+ userName: currentUserName,+ ...(boundaryOpts ?? {}),+ }),+ )+ // RPC 已执行成功时保留既有返回语义;origin 漂移只丢控制端镜像回写。+ .then(({ projection }) => projection.error === null)+ .catch((err) => {+ const message = decodeRemoteErrorMessage(err instanceof Error ? err.message : String(err));+ setState(sessionId, (s) => ({+ ...s,+ error: message,+ usageLimitRecovery: null,+ recoverableError: null,+ errorRetryText: null,+ }));+ return false;+ })+ );}function steerMessage(@@ -8115,11 +11104,24 @@ function steerMessage(agentReferences?: AgentInputReference[];pastedTextRanges?: PastedTextRange[];slashCommandRanges?: SlashCommandRange[];+ beforeEnqueue?: () => Promise<boolean>;+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;},): Promise<boolean> {if (!sessionId || (!text.trim() && (!files || files.length === 0)) || !workingDir) {return Promise.resolve(false);}+ if (isRemoteDeletedSessionSendBlocked(sessionId)) return Promise.resolve(false);+ const remoteScopeAtStart = captureRemoteOptimisticSendScope(+ sessionId,+ opts?.onRemoteOptimisticFailure,+ );+ if (remoteClearInFlight.has(sessionId) && !remoteScopeAtStart) return Promise.resolve(false);+ if (remoteScopeAtStart && !isRemoteOptimisticSendScopeActive(sessionId, remoteScopeAtStart)) {+ return Promise.resolve(false);+ }+ const clearGenerationAtStart =+ remoteScopeAtStart?.clearGeneration ?? rendererClearGenerationBySession.get(sessionId) ?? 0;const current = getOrCreateState(sessionId);if (!canStartComposerSteer(current)) {// 镜像里有在飞 steer 事务 → 静默拒绝对用户就是"没反应", 留痕 + 主动向@@ -8148,29 +11150,92 @@ function steerMessage(files,mentions,opts,+ clearGenerationAtStart,+ remoteScopeAtStart,);}- return materializeAnnotatedAttachmentsForSend(files, sessionId, {- stripAnnotationMeta: isRemoteMediaSession(sessionId),- }).then((prepared) =>- steerMessageCore(+ if (remoteScopeAtStart) {+ const identity = {+ clientId: crypto.randomUUID(),+ createdAt: new Date().toISOString(),+ };+ const stripAnnotationMeta = isRemoteMediaSession(sessionId);+ const accepted = steerMessageCore(sessionId,text,model,effort,permissionMode,workingDir,- prepared,+ files,mentions,opts,- ),+ clearGenerationAtStart,+ remoteScopeAtStart,+ files,+ identity,+ true,+ );+ void accepted.then(+ (optimisticallyAccepted) => {+ if (!optimisticallyAccepted) return;+ void materializeAnnotatedAttachmentsForSend(files, sessionId, {+ stripAnnotationMeta,+ })+ .then((prepared) => {+ completeRemoteOptimisticMaterialization(sessionId, identity.clientId, () =>+ buildQueuedMessage(+ sessionId,+ text,+ model,+ effort,+ permissionMode,+ workingDir,+ prepared,+ mentions,+ opts,+ identity,+ ),+ );+ })+ .catch((error) => {+ const record = remoteOptimisticSendRecords(sessionId)?.get(identity.clientId);+ if (record?.materializationPending) {+ settleRemoteOptimisticFailure(sessionId, identity.clientId, error);+ }+ });+ },+ () => undefined,+ );+ return accepted;+ }+ return runRemoteOptimisticMaterialization(+ null,+ materializeAnnotatedAttachmentsForSend(files, sessionId, {+ stripAnnotationMeta: isRemoteMediaSession(sessionId),+ }),+ (prepared) =>+ steerMessageCore(+ sessionId,+ text,+ model,+ effort,+ permissionMode,+ workingDir,+ prepared,+ mentions,+ opts,+ clearGenerationAtStart,+ remoteScopeAtStart,+ files,+ ),);},);}-/** steerMessage 的主体(附件已完成标注物化),同步构建并入队。 */-function steerMessageCore(+/** steerMessage 的主体(附件已完成标注物化)。 */+async function steerMessageCore(sessionId: string,text: string,model: string,@@ -8185,8 +11250,23 @@ function steerMessageCore(agentReferences?: AgentInputReference[];pastedTextRanges?: PastedTextRange[];slashCommandRanges?: SlashCommandRange[];+ beforeEnqueue?: () => Promise<boolean>;+ onRemoteOptimisticFailure?: (clientId: string, error?: unknown) => void;},+ clearGenerationAtStart = 0,+ remoteScopeAtStart: RemoteOptimisticSendScope | null = null,+ recoveryFiles?: readonly AttachedFile[],+ identity?: { clientId: string; createdAt: string },+ materializationPending = false,): Promise<boolean> {+ if (+ (remoteClearInFlight.has(sessionId) && !remoteScopeAtStart) ||+ (remoteScopeAtStart+ ? !isRemoteOptimisticSendScopeActive(sessionId, remoteScopeAtStart)+ : (rendererClearGenerationBySession.get(sessionId) ?? 0) !== clearGenerationAtStart)+ ) {+ return false;+ }const queued = buildQueuedMessage(sessionId,text,@@ -8197,18 +11277,80 @@ function steerMessageCore(files,mentions,opts,+ identity,);+ const deviceLinkRemote = remoteScopeAtStart !== null;+ const remoteDeviceId = remoteScopeAtStart?.deviceId;+ const remoteRecord = remoteScopeAtStart+ ? registerRemoteOptimisticSend(+ sessionId,+ queued,+ remoteScopeAtStart.deviceId,+ 'steer',+ remoteScopeAtStart.dataOwner,+ remoteScopeAtStart.recoverySequence,+ remoteScopeAtStart.expectedClearBoundaryMs,+ opts,+ recoveryFiles ?? files,+ materializationPending,+ )+ : undefined;+ if (deviceLinkRemote && !remoteRecord) return false;+ if (deviceLinkRemote) {+ setState(sessionId, (s) =>+ s.messages.some((message) => message.clientId === queued.clientId)+ ? s+ : { ...s, messages: [...s.messages, { ...queued.chatMessage, isPendingPersist: true }] },+ );+ }+ const rollbackOptimisticSteer = () => {+ if (!deviceLinkRemote) return;+ clearRemoteOptimisticSend(sessionId, queued.clientId);+ setState(sessionId, (s) => ({+ ...s,+ messages: s.messages.filter(+ (message) => !(message.clientId === queued.clientId && message.isPendingPersist),+ ),+ }));+ };+ if (!deviceLinkRemote && opts?.beforeEnqueue) {+ try {+ if (!(await opts.beforeEnqueue())) {+ rollbackOptimisticSteer();+ return false;+ }+ } catch (err) {+ rollbackOptimisticSteer();+ throw err;+ }+ }touchSessionUserSend(sessionId, workingDir, false);// 补起名同样要覆盖 steer:首条是纯附件的会话标题此时是合成占位,而用户完全// 可能趁这一轮还在跑就用「插话」写下第一句话。只走普通发送的话,这句话不会// 改名,标题会一直停在附件名直到他再排队发一条(PR #510 review P1)。// 素材在入队前推导(此刻 queued 还在手里),但**只有输入被受理才改名**:同会话// 已有在飞 steer / Stop 边界 / 输入锁都会让它被拒,拒掉的文本不该改名。- const autoTitleSeed = deriveAutoTitleSeed(queued, autoTitleFallbackLabels());const agentKind = getOrCreateState(sessionId).agentKind;- const commitAutoTitle = () => maybeAutoNameUnnamedSession(sessionId, autoTitleSeed, agentKind);- return makerApiFor(sessionId)- .input.steer(sessionId, queued, { touchUserSend: true })+ const commitAutoTitle = (titleQueued = queued) =>+ maybeAutoNameUnnamedSession(+ sessionId,+ deriveAutoTitleSeed(titleQueued, autoTitleFallbackLabels()),+ agentKind,+ );+ if (deviceLinkRemote && remoteRecord) {+ // Match ordinary remote sends: the first steer attempt also belongs to the+ // outbox pump, so an invoke timeout cannot keep Send disabled. Auto-title+ // follows the local acceptance point and permanent failure restores text.+ if (materializationPending) remoteRecord.onMaterializationReady = commitAutoTitle;+ else commitAutoTitle();+ remoteRecord.composerResolvedOptimistically = true;+ void pumpRemoteOptimisticSends(sessionId);+ return true;+ }++ const steerApi = remoteDeviceId ? makerApiForDevice(remoteDeviceId) : makerApiFor(sessionId);+ return steerApi.input+ .steer(sessionId, queued, { touchUserSend: true }).then(async (ok) => {if (ok) {commitAutoTitle();@@ -8220,12 +11362,14 @@ function steerMessageCore(// 由队列行接管显示,这里必须返回 true 让 composer 清空草稿,否则用户面前// 同时存在暂停行 + 草稿,再次发送会双份消费(review #939 第五轮)。try {- const operation = beginInputProjectionOperation(sessionId);+ const operation = beginInputProjectionOperation(sessionId, remoteDeviceId);const latest = await operation.api.input.getProjection(sessionId);+ const latestHasQueuedItem = latest.pendingQueue.some((q) => q.clientId === queued.clientId);if (!applyInputProjectionOperationResponse(sessionId, operation, latest)) {+ rollbackOptimisticSteer();return false;}- if (latest.pendingQueue.some((q) => q.clientId === queued.clientId)) {+ if (latestHasQueuedItem) {// 物化进队列 = 这条输入已被主端接管、日后会派发,与受理同等 —— 起名也要// 跟上,否则纯附件/fork 之后的第一句话恰好在这条不确定路径上不改名// (review P1)。是否真该改名仍由 main 权威判定。@@ -8235,12 +11379,14 @@ function steerMessageCore(} catch (err) {log.warn('steer materialization check failed:', err);}+ rollbackOptimisticSteer();return false;}).catch((err) => {// 远端 lazy-create/startSession 抛的 [REMOTE_*] 不可恢复错误走 IPC reject 落这里// (不经 stream error event reducer),同样要解码成 i18n 文案,别裸显 bracket code。const message = decodeRemoteErrorMessage(err instanceof Error ? err.message : String(err));+ rollbackOptimisticSteer();setState(sessionId, (s) => ({...s,error: message,@@ -8338,6 +11484,12 @@ async function resendBlockedMessage(function steerQueuedMessage(sessionId: string, clientId: string): Promise<boolean> {if (!sessionId || !clientId) return Promise.resolve(false);+ // Capture the target before entering the dispatch coordinator. A relay+ // reconnect may clear remoteProjectsStore while the coordinator is waiting;+ // retrying through makerApiFor(sessionId) in that window would address the+ // controller's local maker instead of the queued message's host.+ const remoteDeviceId = getStickySessionDeviceId(sessionId);+ const steerApi = remoteDeviceId ? makerApiForDevice(remoteDeviceId) : makerApiFor(sessionId);const current = getOrCreateState(sessionId);const queued = current.pendingQueue.find((q) => q.clientId === clientId);if (!queued) {@@ -8363,25 +11515,31 @@ function steerQueuedMessage(sessionId: string, clientId: string): Promise<booleareturn withAgentSendDispatch(sessionId,() => Promise.resolve(false),- () => makerApiFor(sessionId)- .input.steer(sessionId, queued, { removeFromQueue: true })- .then((ok) => {- requestInputProjection(sessionId);- return ok;- })- .catch((err) => {- // 远端 lazy-create/startSession 抛的 [REMOTE_*] 不可恢复错误走 IPC reject 落这里- // (不经 stream error event reducer),同样要解码成 i18n 文案,别裸显 bracket code。- const message = decodeRemoteErrorMessage(err instanceof Error ? err.message : String(err));- setState(sessionId, (s) => ({- ...s,- error: message,- usageLimitRecovery: null,- recoverableError: null,- errorRetryText: null,- }));- return false;- }),+ () =>+ steerApi.input+ .steer(sessionId, queued, {+ removeFromQueue: true,+ ...getRemoteInputClearBoundaryOpts(sessionId),+ })+ .then((ok) => {+ requestInputProjection(sessionId);+ return ok;+ })+ .catch((err) => {+ // 远端 lazy-create/startSession 抛的 [REMOTE_*] 不可恢复错误走 IPC reject 落这里+ // (不经 stream error event reducer),同样要解码成 i18n 文案,别裸显 bracket code。+ const message = decodeRemoteErrorMessage(+ err instanceof Error ? err.message : String(err),+ );+ setState(sessionId, (s) => ({+ ...s,+ error: message,+ usageLimitRecovery: null,+ recoverableError: null,+ errorRetryText: null,+ }));+ return false;+ }),);}@@ -8398,21 +11556,30 @@ function steerQueuedMessage(sessionId: string, clientId: string): Promise<boolea*/function stopSession(sessionId: string,- opts?: { keepQueue?: boolean; pauseQueue?: boolean },+ opts?: {+ keepQueue?: boolean;+ pauseQueue?: boolean;+ expectedClearBoundaryMs?: number | null;+ },): void {if (!sessionId) return;- const api = makerApiFor(sessionId);+ const remoteDeviceId = getStickySessionDeviceId(sessionId);// Stop 的乐观终态必须立即作废此前同源查询与旧操作;不能等响应回来,// 否则旧结果会在 abort 往返期间把刚清掉的 owner 重新写回。先推进再捕获,// 让 Stop 自己的权威响应仍属于新代际。+ bumpInteractionReconcileEpoch(sessionId);supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });- const operation: InputProjectionOperation = {- api,- origin: remoteProjectsStore.getSessionDeviceId(sessionId),- epoch: _inputProjectionAuthorityEpoch.get(sessionId) ?? 0,- };+ const operation = beginInputProjectionOperation(sessionId, remoteDeviceId);+ const clearBoundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);+ const stopOpts =+ opts || clearBoundaryOpts+ ? {+ ...(opts ?? {}),+ ...(clearBoundaryOpts ?? {}),+ }+ : undefined;operation.api.input- .stop(sessionId, opts)+ .stop(sessionId, stopOpts).then((projection) => {applyInputProjectionOperationResponse(sessionId, operation, projection);})@@ -8521,8 +11688,10 @@ function popQueueTail(sessionId: string): boolean {*/function clearError(sessionId: string): void {if (!sessionId) return;- runInputProjectionOperation(sessionId, (input) => input.clearError(sessionId))- .catch((err) => log.warn('clearError failed:', err));+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);+ runInputProjectionOperation(sessionId, (input) =>+ boundaryOpts ? input.clearError(sessionId, boundaryOpts) : input.clearError(sessionId),+ ).catch((err) => log.warn('clearError failed:', err));setState(sessionId, (s) => {if (s.error == null &&@@ -8550,9 +11719,9 @@ function retryLastError(sessionId: string): Promise<void> {// renderer 不传文案、不做判定。// retryLastError 在 main 内会先 await 历史查询再入队,必须从点击时刻起占住与// Agent 切换共享的发送 token;否则后点的切换能越过这段查询,让重试改由新 Agent 执行。- return runAgentDispatchProjectionOperation(- sessionId,- (input) => input.retryLastError(sessionId),+ const boundaryOpts = getRemoteInputClearBoundaryOpts(sessionId);+ return runAgentDispatchProjectionOperation(sessionId, (input) =>+ boundaryOpts ? input.retryLastError(sessionId, boundaryOpts) : input.retryLastError(sessionId),).then(() => undefined);}@@ -8630,33 +11799,63 @@ function dismissErrorTailMessage(sessionId: string, clientId: string): Promise<b* are permanently hidden and the next query starts a fresh conversation* - Stays on the same session (no navigation, no new session created)*/-function clearSession(sessionId: string): void {- if (!sessionId) return;+function clearSession(sessionId: string): Promise<void> {+ if (!sessionId) return Promise.resolve();const clearedAt = new Date().toISOString();- void clearSessionAfterGuard(sessionId, clearedAt);+ return clearSessionAfterGuard(sessionId, clearedAt);}async function clearSessionAfterGuard(sessionId: string, clearedAt: string): Promise<void> {+ if (remoteClearInFlight.has(sessionId)) return;+ remoteClearInFlight.add(sessionId);+ try {+ await clearSessionAfterGuardImpl(sessionId, clearedAt);+ } finally {+ remoteClearInFlight.delete(sessionId);+ }+}++async function clearSessionAfterGuardImpl(sessionId: string, clearedAt: string): Promise<void> {+ // Pin the clear lifecycle to the last known device before any await. The+ // mirror is intentionally cleared below, so live origin lookup is no longer+ // reliable for either clearSession or closeSession.+ const remoteDeviceId = getStickySessionDeviceId(sessionId);noteRendererClearBoundary(sessionId, clearedAt);+ // Invalidate old history/projection operations before the first network await.+ // The clear guard itself must be the new authority generation, otherwise an+ // older projection can win the race and reinsert pre-clear queue state.+ bumpMessagesEpoch(sessionId);+ bumpInteractionReconcileEpoch(sessionId);+ supersedeInputProjectionRequests(sessionId, { supersedeOperations: true });+ if (remoteDeviceId) {+ // Arm before the first remote await. New sends made while the invoke is+ // pending are accepted into the local optimistic ledger but cannot cross+ // the host's clear boundary.+ armRemoteClearFence(sessionId, remoteDeviceId, clearedAt);+ }+ clearRemoteOptimisticMaterializationRecoveriesForSession(sessionId, {+ preserveComposerTransitions: true,+ markComposerTransitionsPurged: true,+ });+ clearRemoteOptimisticSendsForSession(sessionId);// 远程会话:/clear 之后**不会**再有一次"最新页"拉取(唯一写缓存的那条路径),盘上那份// 仍是清空前的正文 —— 此刻退出 app,下次离线冷启动就把已经被清掉的对话 hydrate 回来// (review: codex P1)。放在守卫之前:无论守卫成功、失败还是超时,缓存都必须消失。- invalidateRemoteMessageCache(sessionId);+ invalidateRemoteMessageCache(sessionId, remoteDeviceId);// Arm main-side clear guards before closing the CLI and clearing renderer state.let guardTimeoutId: ReturnType<typeof setTimeout> | undefined;let guardResult:| { kind: 'projection'; projection: AgentInputProjection }| { kind: 'error'; err: unknown }| { kind: 'timeout' };- const clearOperation = beginInputProjectionOperation(sessionId);+ const clearOperation = beginInputProjectionOperation(sessionId, remoteDeviceId);try {guardResult = await Promise.race([- clearOperation.api.input.clearSession(sessionId, clearedAt)- .then(- (projection) => ({ kind: 'projection' as const, projection }),- (err) => ({ kind: 'error' as const, err }),- ),+ clearOperation.api.input.clearSession(sessionId, clearedAt).then(+ (projection) => ({ kind: 'projection' as const, projection }),+ (err) => ({ kind: 'error' as const, err }),+ ),new Promise<{ kind: 'timeout' }>((resolve) => {guardTimeoutId = setTimeout(() => resolve({ kind: 'timeout' }),@@ -8670,12 +11869,31 @@ async function clearSessionAfterGuard(sessionId: string, clearedAt: string): Proif (guardTimeoutId) clearTimeout(guardTimeoutId);}if (guardResult.kind === 'projection') {+ let remoteClearResolved = true;+ if (remoteDeviceId) {+ remoteClearResolved = resolveRemoteClearFenceFromProjection(+ sessionId,+ remoteDeviceId,+ clearedAt,+ guardResult.projection,+ { pump: false },+ );+ }applyInputProjectionOperationResponse(sessionId, clearOperation, guardResult.projection);+ if (remoteDeviceId) {+ if (remoteClearResolved) pumpRemoteOptimisticSendsAfterCurrent(sessionId);+ else scheduleRemoteClearRetry(sessionId);+ }} else if (guardResult.kind === 'error') {const err = guardResult.err;log.warn('maker.input.clearSession failed:', err);+ if (remoteDeviceId) {+ noteRemoteClearDispatchError(sessionId, remoteDeviceId, clearedAt, err);+ scheduleRemoteClearRetry(sessionId);+ }} else {log.warn('maker.input.clearSession timed out; continuing local clear', { sessionId });+ if (remoteDeviceId) scheduleRemoteClearRetry(sessionId);}_lastViewedAt.delete(sessionId);@@ -8683,20 +11901,34 @@ async function clearSessionAfterGuard(sessionId: string, clearedAt: string): Pro// Close the CLI subprocess entirely (not just interrupt — we want a fresh context).// preserveWorkspace: /clear 后停留在同一会话,worktree / cwd 必须原样保留,// 否则 onClose 副作用会把活会话的工作区静默 stash+删除(2026-07 实报)。- makerApiFor(sessionId)+ const closePromise = clearOperation.api.closeSession(sessionId, { preserveWorkspace: true }).catch((err) => log.warn('maker.closeSession failed:', err));+ // The remote guard may have been waiting while the user composed another+ // message. Those records belong to the post-clear generation: clear the old+ // transcript, but keep their local optimistic rows until the host accepts+ // them. Pre-clear records were already removed before the guard invoke.+ const postClearOptimisticClientIds = new Set(+ [...(remoteOptimisticSendRecords(sessionId)?.values() ?? [])]+ .filter(+ (record) =>+ isDataOwnerGenerationCurrent(record.dataOwner) &&+ record.clearGeneration === (rendererClearGenerationBySession.get(sessionId) ?? 0),+ )+ .map((record) => record.queued.clientId),+ );+// Clear in-memory state; preserve isFirstMessage so the view stays in ChatView- // with an empty message list (matches /clear semantics).- // 代际递增:/clear 与 reloadMessages / purge 同属"整体重置切片",作废 in-flight- // 的 loadOlderMessages 追页窗口——否则晚到的翻页提交会把清空前的行 merge 回来,- // 已 clear 的对话在界面上复活(subagent review P1;bump 点清单见 _messagesEpoch 注释)。- bumpMessagesEpoch(sessionId);+ // with an empty message list (matches /clear semantics). The epoch was bumped+ // before the guard await above, so old history responses are already invalid.setState(sessionId, (s) => {return {...s,- messages: [],+ messages: s.messages.filter(+ (message) =>+ message.isPendingPersist && postClearOptimisticClientIds.has(message.clientId),+ ),taskUpdates: new Map(),pendingTaskWake: false,streamingClientId: null,@@ -8731,7 +11963,9 @@ async function clearSessionAfterGuard(sessionId: string, clearedAt: string): ProaskUserDraft: null,pendingPlanReview: null,pendingIssueConfirm: null,- pendingQueue: [],+ pendingQueue: s.pendingQueue.filter((item) =>+ postClearOptimisticClientIds.has(item.clientId),+ ),steeringQueueClientIds: [],queuePaused: false,queueAbortPending: false,@@ -8758,7 +11992,10 @@ async function clearSessionAfterGuard(sessionId: string, clearedAt: string): Pro// Persist: null out sdkSessionId (fresh conversation) + set clearedAt// device-link 远程会话由被控端 maker:input:clear-session handler 权威落库并广播// sessions:patched;控制端本地 DB 没有该 row,不能在这里写。- if (isRemoteSession(sessionId)) return;+ if (remoteDeviceId) {+ await closePromise;+ return;+ }sessionService.update(sessionId, { sdkSessionId: null, clearedAt }).then(() => {@@ -8767,6 +12004,7 @@ async function clearSessionAfterGuard(sessionId: string, clearedAt: string): ProemitPatch(sessionId, { sdkSessionId: null, clearedAt, updatedAt: clearedAt });}).catch((err) => log.error('clearSession failed:', err));+ await closePromise;}/**@@ -8885,6 +12123,7 @@ function answerUserQuestion(const state = getOrCreateState(sessionId);if (!state.pendingAskUser) return;if (state.pendingAskUser.requestId !== requestId) return;+ bumpInteractionReconcileEpoch(sessionId);// Build a human-readable reply summaryconst replySummary = formatAskUserReply(answers);@@ -8965,6 +12204,7 @@ function respondToPluginSetup(const field = selectedAction.form.fields[0];if (value.length === 0 || value.length > field.maxLength) return;+ bumpInteractionReconcileEpoch(sessionId);const command: PluginSetupCommandInFlight = {requestId,action,@@ -8988,6 +12228,7 @@ function respondToPluginSetup(return;}+ bumpInteractionReconcileEpoch(sessionId);const command: PluginSetupCommandInFlight = {requestId,action,@@ -9019,6 +12260,7 @@ function respondToPermission(sessionId: string, result: CCAgentPermissionResult)if (!state.pendingPermission) return;const { requestId } = state.pendingPermission;+ bumpInteractionReconcileEpoch(sessionId);// Clear the pending permission immediately so the UI updatessetState(sessionId, (s) => ({ ...s, pendingPermission: null }));@@ -9060,6 +12302,7 @@ function respondToIssueConfirm(if (!state.pendingIssueConfirm) return;const { requestId } = state.pendingIssueConfirm;+ bumpInteractionReconcileEpoch(sessionId);// 先清 UI,再回包(同 respondToPermission 的时序)。setState(sessionId, (s) => ({ ...s, pendingIssueConfirm: null }));@@ -9104,6 +12347,7 @@ function respondToRenameSessionsConfirm(if (!state.pendingRenameSessionsConfirm) return;const { requestId } = state.pendingRenameSessionsConfirm;+ bumpInteractionReconcileEpoch(sessionId);setState(sessionId, (s) => ({ ...s, pendingRenameSessionsConfirm: null }));@@ -9173,6 +12417,7 @@ function respondToGhostGrantConfirm(if (!state.pendingGhostGrantConfirm) return;const { requestId } = state.pendingGhostGrantConfirm;+ bumpInteractionReconcileEpoch(sessionId);setState(sessionId, (s) => ({ ...s, pendingGhostGrantConfirm: null }));@@ -9199,6 +12444,7 @@ function respondToPlanReview(const nextStatus = approved ? 'approved' : 'revised';const trimmedFeedback = feedback?.trim() ?? '';+ bumpInteractionReconcileEpoch(sessionId);// Find the clientId for persistence updateconst planMsg = state.messages.find(@@ -9266,6 +12512,7 @@ function cancelPlanReview(sessionId: string, requestId: string): void {const state = getOrCreateState(sessionId);if (!state.pendingPlanReview) return;if (state.pendingPlanReview.requestId !== requestId) return;+ bumpInteractionReconcileEpoch(sessionId);const planMsg = state.messages.find((m) =>@@ -9364,13 +12611,12 @@ async function setFastMode(// setState 是当前打开会话的 in-memory 即时反馈;sidebar 分片由回流更新。隧道失败必须 reject,// 让上层不要把 New Maker draft default 误同步到一个未实际保存的 Fast 值。显式 device ID// 来自操作开始时的稳定 scope,relay origin 短暂缺失时仍必须走同一被控端。- if (sourceRemoteDeviceId || isRemoteSession(sessionId)) {+ const remoteDeviceId = sourceRemoteDeviceId ?? getStickySessionDeviceId(sessionId);+ if (remoteDeviceId) {const previousFastMode = getOrCreateState(sessionId).fastMode;setState(sessionId, (s) => (s.fastMode === enabled ? s : { ...s, fastMode: enabled }));try {- const remoteMaker = sourceRemoteDeviceId- ? makerApiForDevice(sourceRemoteDeviceId)- : makerApiFor(sessionId);+ const remoteMaker = makerApiForDevice(remoteDeviceId);await remoteMaker.setFastMode(sessionId, enabled);} catch (err) {setState(sessionId, (s) =>@@ -9409,7 +12655,8 @@ async function setFastMode(*/async function setPlanMode(sessionId: string, enabled: boolean): Promise<void> {if (!sessionId) return;- if (isRemoteSession(sessionId)) {+ const remoteDeviceId = getStickySessionDeviceId(sessionId);+ if (remoteDeviceId) {const previous = getOrCreateState(sessionId).planModeEnabled;setState(sessionId, (s) =>s.planModeEnabled === enabled@@ -9417,7 +12664,7 @@ async function setPlanMode(sessionId: string, enabled: boolean): Promise<void> {: { ...s, planModeEnabled: enabled, planModeRev: s.planModeRev + 1 },);try {- await makerApiFor(sessionId).setPlanMode(sessionId, enabled);+ await makerApiForDevice(remoteDeviceId).setPlanMode(sessionId, enabled);} catch (err) {setState(sessionId, (s) =>s.planModeEnabled === enabled@@ -9467,9 +12714,10 @@ async function setPlanMode(sessionId: string, enabled: boolean): Promise<void> {*/async function resetFastMode(sessionId: string): Promise<void> {if (!sessionId) return;- if (isRemoteSession(sessionId)) {+ const remoteDeviceId = getStickySessionDeviceId(sessionId);+ if (remoteDeviceId) {setState(sessionId, (s) => (!s.fastMode ? s : { ...s, fastMode: false }));- await makerApiFor(sessionId)+ await makerApiForDevice(remoteDeviceId).setFastMode(sessionId, false).catch((err: unknown) => {log.warn('resetFastMode IPC failed (remote):', err);@@ -9623,6 +12871,11 @@ export { UI_ACTION_TRIGGER_PREFIX };function sendUiTriggerCore(sessionId: string, prompt: string): Promise<void> {const state = getOrCreateState(sessionId);+ // UI triggers can be invoked from an error card while the mirror is being+ // reseeded. Pin every mutation in this attempt to the device that owned the+ // session when the action started.+ const remoteDeviceId = getStickySessionDeviceId(sessionId);+ const triggerApi = remoteDeviceId ? makerApiForDevice(remoteDeviceId) : makerApiFor(sessionId);const originalTail = state.messages[state.messages.length - 1];// Freeze the row the user acted on before session lookup / dispatch. A fast// continuation failure may append a new error before send resolves; that new@@ -9646,7 +12899,7 @@ function sendUiTriggerCore(sessionId: string, prompt: string): Promise<void> {// 无 pendingQueue 可取消,continue 在直发 accepted 后 durable ack;成功后再 dismiss// 尾部 error(主路径 enqueue 不能在排队阶段 dismiss,否则取消后续跑后入口丢失)。const sendDirect = (ackInterruptedTurnOnDispatch = false) =>- makerApiFor(sessionId)+ triggerApi.send(sessionId, { type: 'user', content: prompt }, undefined, {userName: currentUserName ?? undefined,...(ackInterruptedTurnOnDispatch ? { ackInterruptedTurnOnDispatch: true } : {}),@@ -9674,7 +12927,6 @@ function sendUiTriggerCore(sessionId: string, prompt: string): Promise<void> {session.permissionMode,session.workingDir,);- const deviceLinkRemote = isRemoteSession(sessionId);queued.createOpts = {...queued.createOpts,agentKind: dbAgentKindToMakerKind(session.agentKind, state.agentKind),@@ -9690,7 +12942,7 @@ function sendUiTriggerCore(sessionId: string, prompt: string): Promise<void> {// 远端 SSH 会话:重启后 lazy-create 缺它会把远端 workingDir 当本地路径。...(session.remoteHostId ? { remoteHostId: session.remoteHostId } : {}),};- const operation = beginInputProjectionOperation(sessionId);+ const operation = beginInputProjectionOperation(sessionId, remoteDeviceId);return operation.api.input.enqueue(sessionId, queued, { sendAtMs: Date.now() }).then((projection) => {@@ -9846,7 +13098,11 @@ function mirrorAgentSwitchIntent(sessionId: string, value: unknown): void {function setSessionRuntime(sessionId: string,- opts: { agentKind?: 'claude-code' | 'codex' | 'pi'; fastMode?: boolean; planModeEnabled?: boolean },+ opts: {+ agentKind?: 'claude-code' | 'codex' | 'pi';+ fastMode?: boolean;+ planModeEnabled?: boolean;+ },): void {if (!sessionId) return;setState(sessionId, (s) => {@@ -9983,6 +13239,8 @@ export const makerChatStore = {loadAroundMessage,loadAroundMessageClientId,sendMessage,+ beginRemoteOptimisticComposerTransition,+ cancelRemoteOptimisticSendsForDataOwnerBoundary,// /goal 从首页新建的会话不经普通发送路径,自动起名漏触发 —— 暴露此动作让调用方用目标文案补起名。autoNameSession: scheduleAutoName,compactSession,@@ -10109,6 +13367,12 @@ export const makerChatStore = {},/** Exposed for tests only. */__teardownGlobalListeners,+ /** Exposed for tests only: unlike getSnapshot, this probe never creates a session slice. */+ __hasSessionForTest: (sessionId: string): boolean => sessions.has(sessionId),+ /** Exposed for tests only: isolate remote terminal lifecycle tombstones. */+ __resetRemoteTerminalTombstonesForTest: (): void => {+ remoteTerminalSessionTombstones.clear();+ },/** Exposed for tests only: 非首条消息的补起名(纯附件首条 / fork 占位)。 */__autoNameUnnamedSessionForTest: maybeAutoNameUnnamedSession,/** Exposed for tests only: 清空「已确认无需起名」缓存,隔离用例间状态。 */@@ -10418,7 +13682,10 @@ function serverMessagePageHasMore(rows: Message[], pageSize = 50): boolean {return rows.length >= pageSize || rows.some((row) => row.agentMeta?.remoteRowsTrimmed === true);}-function historyRowsPlanBackfillState(rows: Message[], taskHistoryMayBeIncomplete: boolean): {+function historyRowsPlanBackfillState(+ rows: Message[],+ taskHistoryMayBeIncomplete: boolean,+): {hasPlanEvent: boolean;isResolved: boolean;} {@@ -10753,7 +14020,8 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {>;const message = typeof c.message === 'string' ? c.message : '';const reason = typeof c.reason === 'string' ? c.reason : undefined;- const errorProviderId = typeof c.providerId === 'string' && c.providerId ? c.providerId : undefined;+ const errorProviderId =+ typeof c.providerId === 'string' && c.providerId ? c.providerId : undefined;return {clientId: m.clientId,role: m.role,@@ -10837,9 +14105,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {// 「已自动继续」分隔条(见 hasInterruptionContext)。systemCardData: {...(m.agentMeta.autoResumeInfo ?? {}),- ...(m.agentMeta.autoResumeOutcome- ? { outcome: m.agentMeta.autoResumeOutcome }- : {}),+ ...(m.agentMeta.autoResumeOutcome ? { outcome: m.agentMeta.autoResumeOutcome } : {}),},};}@@ -10903,13 +14169,9 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {}const agentMeta = m.agentMeta;const turnUsageDetails =- m.role === 'assistant'- ? normalizeTurnUsageDetails(agentMeta?.turnUsageDetails)- : undefined;+ m.role === 'assistant' ? normalizeTurnUsageDetails(agentMeta?.turnUsageDetails) : undefined;const normalizedTurnMoney =- m.role === 'assistant'- ? normalizeRegionalMoney(agentMeta?.turnCost)- : undefined;+ m.role === 'assistant' ? normalizeRegionalMoney(agentMeta?.turnCost) : undefined;const legacyTurnCostUsd =m.role === 'assistant' &&typeof agentMeta?.turnCostUsd === 'number' &&@@ -10923,20 +14185,18 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {: undefined;const persistedTurnMoney =m.role === 'assistant'- ? normalizedTurnMoney ??- (legacyTurnCostUsd !== undefined- ? legacyUsdMoney(legacyTurnCostUsd)- : undefined)+ ? (normalizedTurnMoney ??+ (legacyTurnCostUsd !== undefined ? legacyUsdMoney(legacyTurnCostUsd) : undefined)): undefined;// 用户轮累计与当前 segment 费用各自独立读(不变量正本见 shared/turnCostPayload.ts):// 收尾 segment 缺报价的轮次只落了 userTurnCost + turnUsageDetails,若把它嵌在// persistedTurnMoney > 0 的分支里,重开会话后整轮已花的钱会被 token 顶掉。const persistedUserTurnMoney =m.role === 'assistant' && agentMeta- ? normalizeRegionalMoney(agentMeta.userTurnCost) ??+ ? (normalizeRegionalMoney(agentMeta.userTurnCost) ??(typeof agentMeta.userTurnCostUsd === 'number' && agentMeta.userTurnCostUsd > 0? legacyUsdMoney(agentMeta.userTurnCostUsd)- : undefined)+ : undefined)): undefined;const persistedUserTurnCostPatch =agentMeta && persistedUserTurnMoney@@ -10960,11 +14220,10 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {// assistant 等价可推导,直接补投影让本修复对历史复现会话立即生效。// turnUsageDetails 同样是 turn 结束才 patch 的字段(无报价轮只落它),因此// 也是等价的收尾信号 —— 少了它,无金额轮重开会话就挂不出 action bar。- ...(m.role === 'assistant' && (- agentMeta?.turnCompleted === true ||+ ...(m.role === 'assistant' &&+ (agentMeta?.turnCompleted === true ||(persistedTurnMoney?.amount ?? 0) > 0 ||- turnUsageDetails !== undefined- )+ turnUsageDetails !== undefined)? { turnCompleted: true }: {}),// 本轮 token 明细独立于金额挂载:Pi/新模型算不出报价的轮次只有它,@@ -10973,15 +14232,10 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {// 整轮累计费用同样独立挂载:无价收尾轮只有它,没有 turnCost。...persistedUserTurnCostPatch,// assistant 上挂的 per-turn 费用(main turn 结束时 patch 进 agent_meta)- ...(m.role === 'assistant' &&- agentMeta &&- persistedTurnMoney &&- persistedTurnMoney.amount > 0+ ...(m.role === 'assistant' && agentMeta && persistedTurnMoney && persistedTurnMoney.amount > 0? (() => {const turnCostUsd =- persistedTurnMoney.currency === 'USD'- ? persistedTurnMoney.amount- : undefined;+ persistedTurnMoney.currency === 'USD' ? persistedTurnMoney.amount : undefined;return {turnMoney: persistedTurnMoney,...(turnCostUsd !== undefined ? { turnCostUsd } : {}),@@ -11045,19 +14299,10 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {*/function projectLegacyUserTurnCosts(serverMsgs: Message[],-): Map<- string,- Pick<- ChatMessage,- 'userTurnMoney' | 'userTurnCostUsd' | 'userTurnCostIsEstimate'- >-> {+): Map<string, Pick<ChatMessage, 'userTurnMoney' | 'userTurnCostUsd' | 'userTurnCostIsEstimate'>> {const projected = new Map<string,- Pick<- ChatMessage,- 'userTurnMoney' | 'userTurnCostUsd' | 'userTurnCostIsEstimate'- >+ Pick<ChatMessage, 'userTurnMoney' | 'userTurnCostUsd' | 'userTurnCostIsEstimate'>>();let hasRealUserBoundary = false;let costUsd = 0;diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.tsindex 2d97db4071..8c3810c778 100644--- a/apps/desktop/src/renderer/lib/makerTransport.ts+++ b/apps/desktop/src/renderer/lib/makerTransport.ts@@ -18,6 +18,7 @@ import {getSessionDeviceId,remoteProjectsStore,} from '@/features/device-link/remoteProjectsStore';+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import {invalidationAtRequestStart,persistCachedMessages,@@ -245,7 +246,12 @@ export function regenerateSessionTitleFor(sessionId: string): Promise<{ title: s/** 读会话元数据:远程走隧道 local-db:sessions:get(本地 DB 没有该 row,直接调会 404)。 */export function getSessionFor(sessionId: string): Promise<Session> {- const deviceId = getSessionDeviceId(sessionId);+ // Session metadata is part of the same remote send attempt as the later+ // enqueue. Keep using the last known device while the mirror is being+ // rebuilt; reading the controller's local DB in that window returns either+ // an unrelated row or a misleading 404 and can make a UI trigger fall back+ // to the wrong maker instance.+ const deviceId = getStickySessionDeviceId(sessionId);if (!deviceId) return sessionService.get(sessionId);return invokeRemote(deviceId, 'local-db:sessions:get', [sessionId]) as Promise<Session>;}@@ -414,9 +420,7 @@ export function pluginEnableStateFor(: window.electronAPI.maker.plugins.getState(pluginId, workingDir, workspaceKind);}const args =- workspaceKind === undefined- ? [pluginId, workingDir]- : [pluginId, workingDir, workspaceKind];+ workspaceKind === undefined ? [pluginId, workingDir] : [pluginId, workingDir, workspaceKind];return invokeRemote(deviceId, 'maker:plugins:get-state', args) as ReturnType<typeof window.electronAPI.maker.plugins.getState>;@@ -496,6 +500,24 @@ export function aroundMessagesByClientIdFor(]) as Promise<Message[]>;}+/**+ * 已知稳定 deviceId 时直接查询 clientId 锚点。远程乐观发送用它核实一个+ * ACK 丢失的 steer 是否已经落库;这里不能重新读取易失的 session origin,+ * 否则恰好在重连清镜像的窗口会误查控制端本机 DB。+ */+export function aroundMessagesByClientIdForDevice(+ deviceId: string,+ sessionId: string,+ clientId: string,+ opts?: { radius?: number },+): Promise<Message[]> {+ return invokeRemote(deviceId, 'local-db:messages:around-client-id', [+ sessionId,+ clientId,+ opts,+ ]) as Promise<Message[]>;+}+// ─── /goal:device-link 远程路由 ────────────────────────────────────────────────// goal-host 在「会话归属设备」上跑(目标随会话在被控端自主续跑,控制端断链不中断)。// GoalIndicator / NewGoalDialog / useGoalStatus 经这里按会话来源路由;状态推送@@ -566,8 +588,9 @@ export function subscribeGoalStatusChanged(});}return (- window.electronAPI.deviceLink?.onRemotePush?.((push) => {+ window.electronAPI.deviceLink?.onRemotePush?.((push, localOwnerStamp) => {if (push.deviceId !== deviceId || push.channel !== 'maker:goal:status-changed') return;+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;const payload = push.payload as { sessionId?: string; goal?: GoalStatusPayload | null };if (payload?.sessionId !== sessionId) return;cb(payload as { sessionId: string; goal: GoalStatusPayload | null });@@ -701,11 +724,13 @@ export function subscribeOrcaWorkerChanged(leadSessionId: string, cb: () => void);}return (- window.electronAPI.deviceLink?.onRemotePush?.((push) => {+ window.electronAPI.deviceLink?.onRemotePush?.((push, localOwnerStamp) => {if (+ push.deviceId === deviceId &&push.channel === 'maker:orca:worker-changed' &&(push.payload as { leadSessionId?: string })?.leadSessionId === leadSessionId) {+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;cb();}}) ?? (() => {})diff --git a/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts b/apps/desktop/src/renderer/lib/recentWorkdirsStore.tsindex 424f855ac3..78c7807658 100644--- a/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts+++ b/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts@@ -17,6 +17,8 @@* recent_workdirs 表。*/+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';+export interface RecentWorkdirEntry {/** 绝对路径(写入时已 trim,跟 sessions.workingDir 形态一致)。 */path: string;@@ -121,7 +123,8 @@ if (typeof window !== 'undefined') {// 最便宜可靠 —— 表只有几行,IPC 开销可忽略。const sessionsPush = window.electronAPI?.localDb?.sessionsPush;if (sessionsPush) {- sessionsPush.onCreated(() => {+ sessionsPush.onCreated((_payload, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;void recentWorkdirsStore.forceRefresh().catch(() => {/* 静默:下次 ensure / 用户主动操作会再尝试 */});@@ -132,7 +135,8 @@ if (typeof window !== 'undefined') {// 重拉一次幂等无害。const recentApi = window.electronAPI?.localDb?.recentWorkdirs;if (recentApi?.onChanged) {- recentApi.onChanged(() => {+ recentApi.onChanged((_payload, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;void recentWorkdirsStore.forceRefresh().catch(() => {/* 静默:同上 */});diff --git a/apps/desktop/src/renderer/lib/remoteDataOwnerPushFence.ts b/apps/desktop/src/renderer/lib/remoteDataOwnerPushFence.tsnew file mode 100644index 0000000000..4dcf766423--- /dev/null+++ b/apps/desktop/src/renderer/lib/remoteDataOwnerPushFence.ts@@ -0,0 +1,71 @@+import {+ getDataOwnerGeneration,+ isDataOwnerPushCurrent,+} from '@/contexts/dataOwnerGeneration';++import { isDataOwnerPushStamp, type DataOwnerPushStamp } from '../../shared/dataOwnerPush';++/** Last stamped source boundary observed from each controlled device. */+const remoteOwnerStamps = new Map<string, DataOwnerPushStamp>();+/** Devices that have emitted at least one stamped frame in this connection. */+const remoteStampedDevices = new Set<string>();++/**+ * Validate a controlled-device push against the renderer's current account.+ *+ * Owner generations are local to each controlled process, so they must only+ * be compared with earlier generations from the same remote device. Legacy+ * unstamped frames remain compatible until that device proves stamp support.+ */+export function isRemoteDataOwnerPushCurrent(+ remoteDeviceId: string,+ ownerStamp: unknown,+ ownerStampPresent = ownerStamp !== undefined,+): boolean {+ const current = getDataOwnerGeneration();+ if (current.dataOwnerId === null) return false;+ if (!ownerStampPresent) return !remoteStampedDevices.has(remoteDeviceId);+ if (!isDataOwnerPushStamp(ownerStamp)) return false;++ remoteStampedDevices.add(remoteDeviceId);+ if (ownerStamp.dataOwnerId !== current.dataOwnerId) return false;++ const previous = remoteOwnerStamps.get(remoteDeviceId);+ if (+ previous &&+ previous.dataOwnerId === ownerStamp.dataOwnerId &&+ ownerStamp.ownerGeneration < previous.ownerGeneration+ ) {+ return false;+ }++ remoteOwnerStamps.set(remoteDeviceId, ownerStamp);+ return true;+}++/** Validate both the controller's local owner boundary and the controlled device's source owner. */+export function isDeviceLinkRemotePushCurrent(+ push: { deviceId: string; ownerStamp?: unknown },+ localOwnerStamp: unknown,+): boolean {+ if (!isDataOwnerPushCurrent(localOwnerStamp)) return false;+ return isRemoteDataOwnerPushCurrent(+ push.deviceId,+ push.ownerStamp,+ Object.prototype.hasOwnProperty.call(push, 'ownerStamp'),+ );+}++export function resetRemoteDataOwnerPushFence(remoteDeviceId?: string): void {+ if (remoteDeviceId !== undefined) {+ remoteOwnerStamps.delete(remoteDeviceId);+ remoteStampedDevices.delete(remoteDeviceId);+ return;+ }+ remoteOwnerStamps.clear();+ remoteStampedDevices.clear();+}++export const __testing = {+ reset: resetRemoteDataOwnerPushFence,+};diff --git a/apps/desktop/src/renderer/lib/sessionService.ts b/apps/desktop/src/renderer/lib/sessionService.tsindex 521a54ddc6..64f2fde0b3 100644--- a/apps/desktop/src/renderer/lib/sessionService.ts+++ b/apps/desktop/src/renderer/lib/sessionService.ts@@ -14,7 +14,7 @@ import { extractIpcError } from '@/utils/ipcError';// 与 makerTransport 互相 import 形成循环依赖,但双方都只在函数体内(运行时)调用对方导出,// 模块顶层不调用 → ESM 下安全(无 TDZ)。import { makerApiFor } from '@/lib/makerTransport';-import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';import type { SessionReference } from '../../shared/sessionReference';/**@@ -163,7 +163,10 @@ export async function patchMeta(sessionId: string,patch: { status?: SessionStatus; title?: string; pinnedAt?: string | null },): Promise<Session> {- const deviceId = getSessionDeviceId(sessionId);+ // Metadata writes must stay pinned to the last known device while the+ // relay's session mirror is being rebuilt. Otherwise an archived remote+ // task's auto-unarchive can fall through to the controller's local DB.+ const deviceId = getStickySessionDeviceId(sessionId);if (deviceId) {return wrap(window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:patch-meta', [diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.tsindex 232d898267..3f16e3a398 100644--- a/apps/desktop/src/renderer/lib/sessionsStore.ts+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts@@ -57,6 +57,7 @@ import {onPatch,onRefresh,} from '@/lib/sessionsBus';+import { isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';// V1.7:取消 16 条上限,全量拉取由 Sidebar 中部滚动条承载。// 后端硬上限 1000,覆盖几乎所有真实用户的 Session 总数。@@ -568,7 +569,8 @@ if (typeof window !== 'undefined') {});window.electronAPI?.onUsageSessionSpendChanged?.(- ({ sessionId, totalMoney, totalCostUsd }) => {+ ({ sessionId, totalMoney, totalCostUsd }, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;sessionsStore.patchLocal(sessionId, {...(totalMoney ? { totalMoney } : {}),...(typeof totalCostUsd === 'number' ? { totalCostUsd } : {}),@@ -578,10 +580,12 @@ if (typeof window !== 'undefined') {const sessionsPush = window.electronAPI?.localDb?.sessionsPush;if (sessionsPush) {- sessionsPush.onPatched(({ sessionId, patch }) =>- sessionsStore.patchLocal(sessionId, patch),- );- sessionsPush.onCreated(() => {+ sessionsPush.onPatched(({ sessionId, patch }, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;+ sessionsStore.patchLocal(sessionId, patch);+ });+ sessionsPush.onCreated((_payload, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;// payload 只有 sessionId 不带完整 Session row,prependCreated 用不上 ——// 直接重拉所有已加载桶让新 session 出现在 sidebar。void sessionsStore.forceRefreshAll();@@ -590,7 +594,8 @@ if (typeof window !== 'undefined') {const scheduleApi = window.electronAPI?.maker?.schedule;if (scheduleApi) {- scheduleApi.onEvent((event: unknown) => {+ scheduleApi.onEvent((event: unknown, ownerStamp) => {+ if (!isDataOwnerPushCurrent(ownerStamp)) return;if (event &&typeof event === 'object' &&diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 1c97a799a1..20cdf65bac 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -26,8 +26,7 @@ type DesktopLoginActionResult = import('../shared/authIpc').DesktopLoginActionRetype UtilityTextFailure = import('../shared/utilityTextResult').UtilityTextFailure;type MakerSessionTreeSnapshot = import('@cindy/maker-core').SessionTreeSnapshot;type BrowserBackendHealth = import('../shared/browserBackend').BrowserBackendHealth;-type BrowserBackendRecoveryResult =- import('../shared/browserBackend').BrowserBackendRecoveryResult;+type BrowserBackendRecoveryResult = import('../shared/browserBackend').BrowserBackendRecoveryResult;type DesktopAccountDeletionConfirmInput =import('../shared/authIpc').DesktopAccountDeletionConfirmInput;type DesktopAccountDeletionAvailabilityResult =@@ -182,23 +181,27 @@ interface RemoteAgentOneShotResult extends RemoteAgentExecResult {type VoiceInputState = import('@cindy/voice-input-core').VoiceInputState;type VoiceAudioTrace = import('@cindy/voice-input-core').AudioTrace;type VoiceSpeechSegment = import('@cindy/voice-input-core').SpeechSegment;-type VoiceInputGlobalErrorCode = 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' | 'superseded';+type VoiceInputGlobalErrorCode =+ 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' | 'superseded';type VoiceInputGlobalResult =- | { ok: true }- | { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode };+ { ok: true } | { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode };type VoiceEditableRange = import('@cindy/voice-input-core').EditableRange;type VoiceRefinementContext = import('@cindy/voice-input-core').DictationRefinementContext;type VoiceInputDraftSource = import('@cindy/voice-input-core').VoiceInputDraftSource;type VoiceInputRendererEvent = import('@cindy/voice-input-core').VoiceInputRendererEvent;-type VoiceInputDictionaryAdviceInput = import('@cindy/voice-input-core').DictationDictionaryAdviceInput;-type VoiceInputDictionaryLearningAction = import('@cindy/voice-input-core').DictationDictionaryLearningAction;+type VoiceInputDictionaryAdviceInput =+ import('@cindy/voice-input-core').DictationDictionaryAdviceInput;+type VoiceInputDictionaryLearningAction =+ import('@cindy/voice-input-core').DictationDictionaryLearningAction;type VoiceInputSettingsData = import('../shared/voiceInputData').VoiceInputSettings;type VoiceInputHistoryEntryData = import('../shared/voiceInputData').VoiceInputHistoryEntry;type VoiceInputDataSnapshot = import('../shared/voiceInputData').VoiceInputDataSnapshot;type VoiceInputProviderKindData = import('../shared/voiceInputAsrProfiles').VoiceInputProviderKind;type VoiceInputAsrModeData = import('../shared/voiceInputAsrProfiles').VoiceInputAsrMode;-type VoiceInputRefinerProviderKindData = import('../shared/voiceInputRefinerProfiles').VoiceInputRefinerProviderKind;-type VoiceInputRefinerTransportData = import('../shared/voiceInputRefinerProfiles').VoiceInputRefinerTransport;+type VoiceInputRefinerProviderKindData =+ import('../shared/voiceInputRefinerProfiles').VoiceInputRefinerProviderKind;+type VoiceInputRefinerTransportData =+ import('../shared/voiceInputRefinerProfiles').VoiceInputRefinerTransport;type VoiceInputServiceModeData = 'cindy' | 'byok';type VoiceInputModelSelectionResultData = {selection: {@@ -238,7 +241,8 @@ type VoiceInputModelSelectionResultData = {auth: 'api-key' | 'codex';settingsTab: 'api-keys' | 'connections' | 'providers';error?: string;- failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';+ failureReason?:+ 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';};customAsrApiKeyConfigured: boolean;};@@ -249,9 +253,12 @@ type LocalThemeWriteResult = import('../shared/local-themes').LocalThemeWriteRestype ImDefaultSettingsPatch = import('../shared/imDefaultSettings').ImDefaultSettingsPatch;type ImDefaultSettingsState = import('../shared/imDefaultSettings').ImDefaultSettingsState;type ImDefaultSettingsChannel = import('../shared/imDefaultSettings').ImDefaultSettingsChannel;-type SubagentModelSettingsPatch = import('../shared/subagentModelSettings').SubagentModelSettingsPatch;-type SubagentModelSettingsState = import('../shared/subagentModelSettings').SubagentModelSettingsState;-type SubagentModelSettingsWriteResult = import('../shared/subagentModelSettings').SubagentModelSettingsWriteResult;+type SubagentModelSettingsPatch =+ import('../shared/subagentModelSettings').SubagentModelSettingsPatch;+type SubagentModelSettingsState =+ import('../shared/subagentModelSettings').SubagentModelSettingsState;+type SubagentModelSettingsWriteResult =+ import('../shared/subagentModelSettings').SubagentModelSettingsWriteResult;/** Agent 资源占用设置的 IPC wire 形状(main 侧 agentResourceSettingsWire)。 */type AgentResourceProcessPriority = 'normal' | 'low' | 'lowest';@@ -346,9 +353,9 @@ interface ComputerDriverUpdateProgress {interface BinaryDownloadProgressPayload {progress: number;- speed?: string; // e.g. "2.5 MB/s"- downloaded?: string; // e.g. "15.3 MB"- total?: string; // e.g. "80.0 MB"+ speed?: string; // e.g. "2.5 MB/s"+ downloaded?: string; // e.g. "15.3 MB"+ total?: string; // e.g. "80.0 MB"/** Terminal failure flag from main; renderer should escape splash & show retry. */failed?: boolean;/** DownloadError code (e.g. 'NETWORK', 'CHECKSUM', 'HTTP_4XX', 'manifest_failed'). */@@ -494,6 +501,7 @@ interface AuthStateChangePayload {user: AuthUser | null;mode: 'signed-out' | 'local' | 'cloud';dataOwnerId: string | null;+ ownerGeneration: number;canEnterApp: boolean;isAuthenticated: boolean;/** 当前账号是否加入 Canary 发布通道;由 main 的 feature-flags 同步结果驱动。 */@@ -620,7 +628,21 @@ interface CodexUsageSnapshot {interface CCAgentStreamEvent {sessionId: string;- type: 'text' | 'tool_use' | 'tool_result' | 'tool_result_full' | 'agent_task_update' | 'status' | 'done' | 'error' | 'permission_request' | 'permission_dismissed' | 'ask_user_question' | 'plan_review' | 'thinking' | 'compact_boundary';+ type:+ | 'text'+ | 'tool_use'+ | 'tool_result'+ | 'tool_result_full'+ | 'agent_task_update'+ | 'status'+ | 'done'+ | 'error'+ | 'permission_request'+ | 'permission_dismissed'+ | 'ask_user_question'+ | 'plan_review'+ | 'thinking'+ | 'compact_boundary';data: unknown;source?: 'claude-code' | 'codex' | 'pi';/**@@ -694,7 +716,8 @@ interface CCAgentPermissionResult {interface CCAgentPermissionDismissedPayload {sessionId: string;requestId: string;- reason: 'mode_changed_to_bypassPermissions' | 'mode_changed_to_acceptEdits' | 'mode_changed_to_plan';+ reason:+ 'mode_changed_to_bypassPermissions' | 'mode_changed_to_acceptEdits' | 'mode_changed_to_plan';resolvedAs: 'allow' | 'deny';}@@ -774,8 +797,8 @@ interface CCAgentAnswerUserQuestionParams {interface CCAgentPlanReviewPayload {sessionId: string;requestId: string;- plan: string; // Markdown content- planFilePath: string; // Absolute path of the plan file on disk+ plan: string; // Markdown content+ planFilePath: string; // Absolute path of the plan file on disk}/**@@ -904,14 +927,7 @@ type AndroidMcpErrorCode =| 'INVALID_NODE'| 'ANDROID_DRIVER_ERROR';-type AndroidAdbPathSource =- | 'custom'- | 'env'- | 'prepared'- | 'bundled'- | 'sdk'- | 'path'- | 'fallback';+type AndroidAdbPathSource = 'custom' | 'env' | 'prepared' | 'bundled' | 'sdk' | 'path' | 'fallback';interface AndroidConnectedDevice {device_serial: string;@@ -1064,9 +1080,7 @@ interface ElectronAPI {write: (req: LocalThemeWriteRequest) => Promise<LocalThemeWriteResult>;openDir: () => Promise<LocalThemeOpenDirResult>;/** 导入 VSCode / Obsidian 主题文件;对话框与读文件都在 main 侧。 */- importExternal: () => Promise<- import('../shared/theme-import/types').LocalThemeImportResult- >;+ importExternal: () => Promise<import('../shared/theme-import/types').LocalThemeImportResult>;};/** RSB terminal tab —— PTY 后端 + xterm.js,详见 shared/terminal-bridge.ts 注释。 */@@ -1124,9 +1138,7 @@ interface ElectronAPI {/** 只列入口元数据,不运行插件工具;远程/device-link 不暴露。 *//** 用户选定一个入口后,按固定只读摘要契约搜索该插件。 *//** 最近使用顺序变化(发送 /卸载),多窗口同步。 */- onRecentUsageChanged: (- callback: (payload: { ids: string[] }) => void,- ) => () => void;+ onRecentUsageChanged: (callback: (payload: { ids: string[] }) => void) => () => void;install: (lizFilePath: string,/** enable:装入后立即开启(确认框勾选决定;缺省沉睡)。 */@@ -1146,10 +1158,19 @@ interface ElectronAPI {*/cindyPrefsSync: (id: string) => {overrides: Record<string, string>;- image: { options: Array<{ id: string; label: string }>; defaultModel: { id: string; label: string } | null };- video: { options: Array<{ id: string; label: string }>; defaultModel: { id: string; label: string } | null };+ image: {+ options: Array<{ id: string; label: string }>;+ defaultModel: { id: string; label: string } | null;+ };+ video: {+ options: Array<{ id: string; label: string }>;+ defaultModel: { id: string; label: string } | null;+ };/** 文本类(快问快答):选项是轻量任务模型链的档位(供应商×模型),不是媒体目录模型。 */- text: { options: Array<{ id: string; label: string }>; defaultModel: { id: string; label: string } | null };+ text: {+ options: Array<{ id: string; label: string }>;+ defaultModel: { id: string; label: string } | null;+ };};/** 写/清一项覆盖(model=null 即恢复跟随默认);返回该意识最新覆盖表。 */setCindyPref: (@@ -1167,9 +1188,7 @@ interface ElectronAPI {/** 系统文件选择框(.cindy 过滤),只选不装;取消返回 { canceled: true }。 */pickFile: () => Promise<{ canceled: true } | { filePath: string }>;/** 只验不装:读出清单、签名信任等级与 icon data URL,供确认弹窗展示。 */- inspect: (- lizFilePath: string,- ) => Promise<{+ inspect: (lizFilePath: string) => Promise<{manifest: import('../shared/ghost').GhostManifest;trust: import('../shared/ghost').GhostTrustInfo;/** 本次检查的整包指纹;安装/更新时回传,防止确认后文件被替换。 */@@ -1227,7 +1246,15 @@ interface ElectronAPI {purpose?: 'attach' | 'menu',) => Promise<| { url: string; kind?: 'image' }- | { url: string; kind: 'video'; absPath: string; size: number; name: string; ext: string; mimeType: string }+ | {+ url: string;+ kind: 'video';+ absPath: string;+ size: number;+ name: string;+ ext: string;+ mimeType: string;+ }>;/** 意识聊天卡片更新推送(卡槽③):card-update 过闸后带净化 html 全量推,* ghostCardStore 消费;toolUseId 仅 claude 路径有(codex 为 null,@@ -1263,7 +1290,11 @@ interface ElectronAPI {/** 交互卡(v2)按钮点击回传:宿主桥捕获 data-ghost-action 点击后调,主机* 验卡片归属→唤醒意识→管子下发 card-action。fire-and-forget。prompt 仅* data-ghost-prompt 类动作有(宿主输入框收集的用户文字)。 */- dispatchCardAction: (callId: string, actionId: string, prompt?: string) => Promise<{ ok: boolean }>;+ dispatchCardAction: (+ callId: string,+ actionId: string,+ prompt?: string,+ ) => Promise<{ ok: boolean }>;/** 订阅槽①:用户消息被意识钩子拦下(renderer 把乐观气泡原地降级为被拦态;* 没有既有气泡时用 text 补渲一条——排队消息被拦不无声蒸发)。 */onUserMessageBlocked: (@@ -1308,9 +1339,7 @@ interface ElectronAPI {/** 会话切换上报(did-session-switched 数据源;单向 send,main 去重+资格门)。 */noteSessionFocused: (sessionId: string | null) => void;/** 订阅槽①:意识钩子熔断(连续失败降级只旁听,renderer 弹提示)。 */- onHookFused: (- callback: (payload: { ghostId: string; name: string }) => void,- ) => () => void;+ onHookFused: (callback: (payload: { ghostId: string; name: string }) => void) => () => void;/** notify 槽 + 主机代言 notice:意识系统提示(宿主 Toast 渲染,带意识身份头)。* 意识自发的带 text(main 侧已净化+限速);主机代言的(凭证入库/授权成功)* 带 textKey/textArgs,renderer 按 GHOST_HOST_NOTICE_KEYS 白名单翻译。 */@@ -1378,8 +1407,12 @@ interface ElectronAPI {runtimeStates: () => Promise<{ states: Record<string, string> }>;/** 面板错误态「重载意识」:清熔断记账 + 重新拉起沙箱。 */reload: (id: string) => Promise<{ state: string }>;- legacyRecoveryStatus: () => Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus>;- retryLegacyRecovery: () => Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus>;+ legacyRecoveryStatus: () => Promise<+ import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus+ >;+ retryLegacyRecovery: () => Promise<+ import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus+ >;/** dev-only 运行时控制(packaged 版 main 侧不注册,调用会 reject)。 */devRuntime: (action: 'status' | 'spawn' | 'stop' | 'crash',@@ -1396,9 +1429,7 @@ interface ElectronAPI {/** Plugin Protocol v2 市场;网络、下载与安装全部在 main 进程完成。 */pluginMarket: {snapshot: () => Promise<import('../shared/pluginMarket').PluginMarketSnapshot>;- detail: (- pluginId: string,- ) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;+ detail: (pluginId: string) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;install: (pluginId: string,options: import('../shared/pluginMarket').PluginMarketInstallOptions,@@ -1417,17 +1448,19 @@ interface ElectronAPI {sparsePaths?: string[];}) => Promise<import('../shared/pluginMarket').MarketSourceSummary>;removeSource: (name: string) => Promise<{ ok: true }>;- refreshSource: (- name: string,- ) => Promise<import('../shared/pluginMarket').MarketSourceSummary>;+ refreshSource: (name: string) => Promise<import('../shared/pluginMarket').MarketSourceSummary>;gitPreflight: () => Promise<{ ok: boolean; version: string | null }>;};voiceInput: {- prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }) => Promise<{ ok: true }>;- getBenchmarkFixtureAudio: () => Promise<{ ok: true; path: string; wav: ArrayBuffer } | { ok: false }>;+ prewarm: (payload?: {+ sourceLanguage?: string;+ refinementEnabled?: boolean;+ }) => Promise<{ ok: true }>;+ getBenchmarkFixtureAudio: () => Promise<+ { ok: true; path: string; wav: ArrayBuffer } | { ok: false }+ >;getMicrophonePermissionCached: () =>- | { ok: true; status: string }- | { ok: false; status: string; error: string };+ { ok: true; status: string } | { ok: false; status: string; error: string };getSystemPermissionsCached: () => {microphone: { ok: true; status: string } | { ok: false; status: string; error: string };inputMonitoring: { ok: true; status: string } | { ok: false; status: string; error: string };@@ -1466,28 +1499,28 @@ interface ElectronAPI {settingsTab: 'api-keys' | 'connections' | 'providers';error?: string;authErrorReason?: string;- failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';+ failureReason?:+ 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';}>;- getReadinessCached: () =>- | {- ok: boolean;- serviceMode: VoiceInputServiceModeData;- provider:- | 'custom-realtime-asr'- | 'elevenlabs-scribe-realtime'- | 'openai-realtime-whisper'- | 'litellm-gpt-realtime-whisper'- | 'litellm-qwen3-asr-flash-realtime'- | 'litellm-volcengine-sauc-asr'- | 'litellm-batch';- providerModel: string;- auth: 'api-key' | 'codex';- settingsTab: 'api-keys' | 'connections' | 'providers';- error?: string;- authErrorReason?: string;- failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';- }- | null;+ getReadinessCached: () => {+ ok: boolean;+ serviceMode: VoiceInputServiceModeData;+ provider:+ | 'custom-realtime-asr'+ | 'elevenlabs-scribe-realtime'+ | 'openai-realtime-whisper'+ | 'litellm-gpt-realtime-whisper'+ | 'litellm-qwen3-asr-flash-realtime'+ | 'litellm-volcengine-sauc-asr'+ | 'litellm-batch';+ providerModel: string;+ auth: 'api-key' | 'codex';+ settingsTab: 'api-keys' | 'connections' | 'providers';+ error?: string;+ authErrorReason?: string;+ failureReason?:+ 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';+ } | null;getModelSelection: () => Promise<VoiceInputModelSelectionResultData>;setModelSelection: (patch: {serviceMode?: VoiceInputServiceModeData | null;@@ -1524,11 +1557,11 @@ interface ElectronAPI {updateSettings: (patch: Partial<VoiceInputSettingsData>) => Promise<VoiceInputSettingsData>;updateShortcutSetting: (shortcut: VoiceInputShortcut | null) => Promise<| {- ok: true;- settings: VoiceInputSettingsData;- /** 已存盘但 macOS 监听权限未授权,快捷键要等授权后才生效。 */- pendingInputMonitoring?: boolean;- }+ ok: true;+ settings: VoiceInputSettingsData;+ /** 已存盘但 macOS 监听权限未授权,快捷键要等授权后才生效。 */+ pendingInputMonitoring?: boolean;+ }| { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode }>;deleteDictionaryEntries: (entryIds: string[]) => Promise<VoiceInputSettingsData>;@@ -1560,19 +1593,39 @@ interface ElectronAPI {* 挂载时也要主动取一次:失败可能发生在常挂载 UI 之前,那时推送没有订阅者。*/consumeShortcutRecoveryFailure: () => Promise<{ failed: boolean }>;- onGlobalShortcutTrigger: (callback: (payload?: { id?: string; phase?: 'start' | 'tap' | 'end' }) => void) => () => void;+ onGlobalShortcutTrigger: (+ callback: (payload?: { id?: string; phase?: 'start' | 'tap' | 'end' }) => void,+ ) => () => void;claimGlobalShortcutTrigger: (id: string) => void;- onGlobalOverlayCommand: (callback: (command: { type: 'start' | 'submit' | 'cancel' }) => void) => () => void;+ onGlobalOverlayCommand: (+ callback: (command: { type: 'start' | 'submit' | 'cancel' }) => void,+ ) => () => void;adviseDictionaryLearning: (payload: VoiceInputDictionaryAdviceInput,- ) => Promise<{ ok: true; actions: VoiceInputDictionaryLearningAction[]; elapsedMs: number; ignoreReason?: string | null } | { ok: false; error: string }>;+ ) => Promise<+ | {+ ok: true;+ actions: VoiceInputDictionaryLearningAction[];+ elapsedMs: number;+ ignoreReason?: string | null;+ }+ | { ok: false; error: string }+ >;onDictionaryLearningEvidence: (- callback: (payload: { evidence: Pick<VoiceInputDictionaryAdviceInput, 'source' | 'rawTranscriptText' | 'beforeText' | 'afterText' | 'context'> }) => void,+ callback: (payload: {+ evidence: Pick<+ VoiceInputDictionaryAdviceInput,+ 'source' | 'rawTranscriptText' | 'beforeText' | 'afterText' | 'context'+ >;+ }) => void,) => () => void;/** 系统挂起/锁屏 → 释放 fast activation 的保活麦克风。 */onPowerStateChange: (callback: (payload: VoiceInputPowerStatePayload) => void) => () => void;notifyGlobalOverlayReady: () => void;- pasteIntoFocusedTarget: (text: string, rawTranscriptText?: string) => Promise<VoiceInputGlobalResult>;+ pasteIntoFocusedTarget: (+ text: string,+ rawTranscriptText?: string,+ ) => Promise<VoiceInputGlobalResult>;restoreGlobalPasteTargetFocus: () => Promise<VoiceInputGlobalResult>;closeGlobalOverlay: (options?: { preservePasteTarget?: boolean }) => Promise<{ ok: true }>;showGlobalOverlay: () => Promise<VoiceInputGlobalResult>;@@ -1581,13 +1634,11 @@ interface ElectronAPI {endGlobalOverlayDrag: () => void;resetGlobalOverlayPosition: () => Promise<{ ok: true }>;openAccessibilitySettings: () => Promise<VoiceInputGlobalResult>;- showDictionaryToast: (- payload: {- entryId?: string;- term?: string;- entries?: Array<{ entryId: string; term: string }>;- },- ) => Promise<{ ok: true } | { ok: false; error: string }>;+ showDictionaryToast: (payload: {+ entryId?: string;+ term?: string;+ entries?: Array<{ entryId: string; term: string }>;+ }) => Promise<{ ok: true } | { ok: false; error: string }>;closeDictionaryToast: () => Promise<{ ok: true }>;};@@ -1723,6 +1774,7 @@ interface ElectronAPI {user: AuthUser | null;mode: 'signed-out' | 'local' | 'cloud';dataOwnerId: string | null;+ ownerGeneration: number;canEnterApp: boolean;isAuthenticated: boolean;isCanary: boolean;@@ -1753,9 +1805,7 @@ interface ElectronAPI {setAnalyticsEnabled: (enabled: boolean) => Promise<AnalyticsSettingsPayload>;resetAnalyticsEnabled: () => Promise<AnalyticsSettingsPayload>;acceptPrivacyConsent: () => Promise<AnalyticsSettingsPayload>;- onAnalyticsSettingsChange: (- callback: (payload: AnalyticsSettingsPayload) => void,- ) => () => void;+ onAnalyticsSettingsChange: (callback: (payload: AnalyticsSettingsPayload) => void) => () => void;// ── Profile 编辑(设置 → 用户卡片编辑名字 / 头像;直写服务端,跨设备生效) ──profileGetState: () => Promise<{@@ -1828,9 +1878,7 @@ interface ElectronAPI {}>;checkSessionAuth: () => Promise<DiscordBotSessionAuthCheckResult>;onStatusChange: (- callback: (update: {- status: DiscordBotTransportStatus;- }) => void,+ callback: (update: { status: DiscordBotTransportStatus }) => void,) => () => void;};@@ -1860,7 +1908,10 @@ interface ElectronAPI {listGroups: () => Promise<{groups: Array<{ chatId: string; chatName: string | null; activation: 'mention' | 'always' }>;}>;- setGroupActivation: (payload: { chatId: string; mode: 'mention' | 'always' }) => Promise<unknown>;+ setGroupActivation: (payload: {+ chatId: string;+ mode: 'mention' | 'always';+ }) => Promise<unknown>;getPersona: () => Promise<{ botName: string; soul: string }>;setPersona: (payload: {botName?: string;@@ -1976,10 +2027,12 @@ interface ElectronAPI {}) => void;/** 被控端 renderer → 自身 main:providerModelMemory 全量快照镜像(草稿列表行真实读源)。 */- syncProviderModelMemory: (snapshot: Record<- string,- { effortByModel: Record<string, string>; fastByModel: Record<string, boolean> }- >) => void;+ syncProviderModelMemory: (+ snapshot: Record<+ string,+ { effortByModel: Record<string, string>; fastByModel: Record<string, boolean> }+ >,+ ) => void;/** 被控端 renderer → 自身 main:会话「非选中模型」effort/fast 变化镜像(转发给控制端)。 */syncSessionModelPref: (pref: {@@ -2005,9 +2058,7 @@ interface ElectronAPI {) => () => void;/** 被控端本地 main → 自身 renderer:控制端写穿的「新建会话默认启用 worktree」(patchDraft 写真实草稿)。 */- onMakerWorktreePrefApply: (- cb: (payload: { worktreeEnabled: boolean }) => void,- ) => () => void;+ onMakerWorktreePrefApply: (cb: (payload: { worktreeEnabled: boolean }) => void) => () => void;/** 被控端本地 main → 自身 renderer:控制端写穿的会话「模型 effort/fast」pref(调本地 setter)。 */onMakerSessionPrefApply: (@@ -2044,7 +2095,9 @@ interface ElectronAPI {};checkEnvironment: () => Promise<EnvCheckResult>;- onBinaryDownloadProgress: (callback: (payload: BinaryDownloadProgressPayload) => void) => () => void;+ onBinaryDownloadProgress: (+ callback: (payload: BinaryDownloadProgressPayload) => void,+ ) => () => void;checkAppUpdate: () => Promise<{hasUpdate: boolean;action?: 'relaunch' | 'none';@@ -2060,45 +2113,93 @@ interface ElectronAPI {relPath?: string;hideMetaFiles?: boolean;docMode?: boolean;- }) => Promise<Array<{- name: string;- relPath: string;- type: 'file' | 'directory';- size: number;- mtimeMs: number;- }>>;+ }) => Promise<+ Array<{+ name: string;+ relPath: string;+ type: 'file' | 'directory';+ size: number;+ mtimeMs: number;+ }>+ >;/** 项目级文件名扁平列表(ripgrep --files honor .gitignore);失败返回空数组* + error 字段,renderer 应做 fallback 渲染。 */- listAllFiles: (params: { remoteHostId?: string | null; workdir: string; cap?: number }) => Promise<{+ listAllFiles: (params: {+ remoteHostId?: string | null;+ workdir: string;+ cap?: number;+ }) => Promise<{files: string[];truncated: boolean;elapsedMs: number;error?: string;}>;- readFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<- | { ok: true; data: { relPath: string; content: string; size: number; mtimeMs: number; truncated: boolean } }+ readFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }) => Promise<+ | {+ ok: true;+ data: {+ relPath: string;+ content: string;+ size: number;+ mtimeMs: number;+ truncated: boolean;+ };+ }/** OVERSIZE = 远程文本超传输上限(device-link 帧限预判),stat 供"文件过大"占位卡。 */| { ok: false; code: 'BINARY_FILE' | 'READ_FAILED'; message?: string }- | { ok: false; code: 'OVERSIZE'; stat: { relPath: string; type: 'file'; size: number; mtimeMs: number } }- >;- writeFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string; content: string }) => Promise<- | { ok: true; size: number; mtimeMs: number }- | { ok: false; message: string }- >;- createFile: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }- | { ok: false; message: string }+ | {+ ok: false;+ code: 'OVERSIZE';+ stat: { relPath: string; type: 'file'; size: number; mtimeMs: number };+ }>;- createFolder: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ writeFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ content: string;+ }) => Promise<{ ok: true; size: number; mtimeMs: number } | { ok: false; message: string }>;+ createFile: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }) => Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }>;- deleteEntry: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<- | { ok: true }+ createFolder: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }) => Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }>;- renameEntry: (params: { remoteHostId?: string | null; workdir: string; fromRel: string; toRel: string }) => Promise<- | { ok: true; stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number } }+ deleteEntry: (params: {+ remoteHostId?: string | null;+ workdir: string;+ relPath: string;+ }) => Promise<{ ok: true } | { ok: false; message: string }>;+ renameEntry: (params: {+ remoteHostId?: string | null;+ workdir: string;+ fromRel: string;+ toRel: string;+ }) => Promise<+ | {+ ok: true;+ stat: { relPath: string; type: 'file' | 'directory'; size: number; mtimeMs: number };+ }| { ok: false; message: string }>;stat: (params: { remoteHostId?: string | null; workdir: string; relPath: string }) => Promise<{@@ -2107,8 +2208,15 @@ interface ElectronAPI {size: number;mtimeMs: number;}>;- startWatch: (params: { remoteHostId?: string | null; workdir: string; hideMetaFiles?: boolean }) => Promise<{ ok: boolean }>;- stopWatch: (params: { remoteHostId?: string | null; workdir: string }) => Promise<{ ok: boolean }>;+ startWatch: (params: {+ remoteHostId?: string | null;+ workdir: string;+ hideMetaFiles?: boolean;+ }) => Promise<{ ok: boolean }>;+ stopWatch: (params: {+ remoteHostId?: string | null;+ workdir: string;+ }) => Promise<{ ok: boolean }>;onEvent: (cb: (event: {workdir: string;@@ -2125,7 +2233,9 @@ interface ElectronAPI {remoteHostId?: string | null;deviceId?: string | null;}) => Promise<{ ok: true; cachePath: string; stale: boolean } | { ok: false; message: string }>;- readCached: (params: { cachePath: string }) => Promise<+ readCached: (params: {+ cachePath: string;+ }) => Promise<| { ok: true; kind: 'text'; content: string; truncated: boolean }| { ok: true; kind: 'binary' }| { ok: false; message: string }@@ -2140,7 +2250,13 @@ interface ElectronAPI {deviceId?: string | null;}) => Promise<{ ok: boolean }>;onTransferProgress: (- cb: (event: { workdir: string; relPath: string; received: number; total: number; phase?: 'upload' | 'download' }) => void,+ cb: (event: {+ workdir: string;+ relPath: string;+ received: number;+ total: number;+ phase?: 'upload' | 'download';+ }) => void,) => () => void;/** 聊天流文件取回:远端绝对路径 → 本地缓存副本(进度经 onTransferProgress,relPath 键 = absPath)。 */chatFetch: (params: {@@ -2149,7 +2265,11 @@ interface ElectronAPI {absPath: string;}) => Promise<| { ok: true; cachePath: string; stale: boolean; size: number }- | { ok: false; code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED'; message?: string }+ | {+ ok: false;+ code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED';+ message?: string;+ }>;/** 聊天流文件 chip 点亮预检:远端精确 stat。file=点亮;nonfile=保持纯文本;unknown=乐观点亮。 */chatStat: (params: {@@ -2182,7 +2302,13 @@ interface ElectronAPI {lineText: string;submatches: Array<{ start: number; end: number }>;}- | { type: 'end'; searchId: string; truncated: boolean; totalMatches: number; totalFiles: number }+ | {+ type: 'end';+ searchId: string;+ truncated: boolean;+ totalMatches: number;+ totalFiles: number;+ }| { type: 'error'; searchId: string; message: string }>;}@@ -2191,23 +2317,24 @@ interface ElectronAPI {>;cancel: (params: { searchId: string; remoteHostId?: string | null }) => Promise<{ ok: true }>;onEvent: (- cb: (event:- | {- type: 'match';- searchId: string;- relPath: string;- lineNumber: number;- lineText: string;- submatches: Array<{ start: number; end: number }>;- }- | {- type: 'end';- searchId: string;- truncated: boolean;- totalMatches: number;- totalFiles: number;- }- | { type: 'error'; searchId: string; message: string }+ cb: (+ event:+ | {+ type: 'match';+ searchId: string;+ relPath: string;+ lineNumber: number;+ lineText: string;+ submatches: Array<{ start: number; end: number }>;+ }+ | {+ type: 'end';+ searchId: string;+ truncated: boolean;+ totalMatches: number;+ totalFiles: number;+ }+ | { type: 'error'; searchId: string; message: string },) => void,) => () => void;};@@ -2256,7 +2383,10 @@ interface ElectronAPI {/** 将对应 session 标记为需要关注,显示 Dock/taskbar app badge。 */notificationMarkSessionAttention: (sessionId: string) => Promise<void>;/** 用户查看对应 session 后,清除系统级 Dock/taskbar attention badge。 */- notificationClearSessionAttention: (sessionId: string, intent?: 'explicit' | 'passive') => Promise<void>;+ notificationClearSessionAttention: (+ sessionId: string,+ intent?: 'explicit' | 'passive',+ ) => Promise<void>;/*** main → renderer 的会话已读广播(payload:{ sessionId, intent })。清除来源可能是* device-link 远程控制端(手机看完会话),sessionAttentionStore 订阅后把本机侧栏@@ -2318,7 +2448,8 @@ interface ElectronAPI {*/onRsbBrowserCommand: (callback: (payload: {- command: 'go-back' | 'go-forward' | 'reload' | 'close-tab' | 'right-tab-prev' | 'right-tab-next';+ command:+ 'go-back' | 'go-forward' | 'reload' | 'close-tab' | 'right-tab-prev' | 'right-tab-next';}) => void,) => () => void;@@ -2363,9 +2494,7 @@ interface ElectronAPI {* (single-sourced) so the renderer can render dynamic* "exceeding the {limitMb} MB preview limit" copy.*/- readTextFilePreview: (params: {- filePath: string;- }) => Promise<{+ readTextFilePreview: (params: { filePath: string }) => Promise<{success: boolean;error?: string;reason?: 'oversize' | 'not_found' | 'forbidden' | 'read_failed';@@ -2380,10 +2509,7 @@ interface ElectronAPI {openPath: (filePath: string) => Promise<{ success: boolean; error?: string }>;/** Copy a dangerous local attachment into the controlled inert cache. */- stageChatAttachment: (params: {- sourcePath: string;- suggestedName: string;- }) => Promise<+ stageChatAttachment: (params: { sourcePath: string; suggestedName: string }) => Promise<| { success: true; path: string }| {success: false;@@ -2404,10 +2530,7 @@ interface ElectronAPI {* Save a safely materialized chat attachment under its sanitized original* filename. The main process validates the source and never opens the target.*/- saveChatAttachmentAs: (params: {- sourcePath: string;- suggestedName: string;- }) => Promise<+ saveChatAttachmentAs: (params: { sourcePath: string; suggestedName: string }) => Promise<| { status: 'saved'; savedPath: string }| { status: 'canceled' }| {@@ -2458,9 +2581,7 @@ interface ElectronAPI {* 图片 lightbox:另存为。本地源直接复制,http(s)/data: 先取字节;用户取消* 保存对话框返回 `{ canceled: true }`,不算错误。*/- saveMediaAs: (params: {- url: string;- }) => Promise<{ canceled: boolean; savedPath?: string }>;+ saveMediaAs: (params: { url: string }) => Promise<{ canceled: boolean; savedPath?: string }>;/*** 图片 lightbox "发送到对话":把图片复制成目标会话的一份新 `xdt-image://`@@ -2472,9 +2593,7 @@ interface ElectronAPI {}) => Promise<{ url: string; name: string; ext: string; mimeType: string; size: number }>;/** 图片 lightbox 字节层:http / cindy-remote-media 源取字节(标注/位图复制)。 */- readImageBytes: (params: {- url: string;- }) => Promise<{ base64: string; mimeType: string }>;+ readImageBytes: (params: { url: string }) => Promise<{ base64: string; mimeType: string }>;/*** 附件卡缩略图:本机文件走系统缩略图服务(macOS QuickLook / Windows Shell)。@@ -2495,10 +2614,7 @@ interface ElectronAPI {* ends with `/<href>`. Returns 'none' on bad input or no matches so the* renderer can fall back to legacy resolveLocalPath.*/- resolvePath: (params: {- href: string;- workingDir: string;- }) => Promise<{+ resolvePath: (params: { href: string; workingDir: string }) => Promise<{status: 'unique' | 'multiple' | 'none';candidates: string[];/** unique 命中时的目标类型;缺省按 file 理解(老 main 兼容)。 */@@ -2515,7 +2631,10 @@ interface ElectronAPI {hrefs: string[];workingDir: string;}) => Promise<- Record<string, { status: 'unique' | 'multiple' | 'none'; candidates: string[]; kind?: 'file' | 'directory' }>+ Record<+ string,+ { status: 'unique' | 'multiple' | 'none'; candidates: string[]; kind?: 'file' | 'directory' }+ >>;// 本机文件系统目录浏览(项目选择器「添加远程项目」;device-link 经隧道在被控端执行)。@@ -2559,10 +2678,7 @@ interface ElectronAPI {* file. Used by the renderer to run magic-bytes + UTF-8 sniffing on files* whose extension didn't match any supported type.*/- peekFileHeader: (params: {- filePath: string;- bytes?: number;- }) => Promise<{+ peekFileHeader: (params: { filePath: string; bytes?: number }) => Promise<{success: boolean;error?: string;/** base64-encoded leading bytes; present when actualBytes > 0. */@@ -2594,12 +2710,17 @@ interface ElectronAPI {// ── Learn (/learn 蒸馏 —— 系统级"学成 skill"能力) ──learn: {- start: (- req: import('../shared/learnTypes').LearnStartRequest,- ) => Promise<{ runId: string }>;- listRuns: () => Promise<{ runs: import('../shared/learnTypes').LearnRunPublic[]; ready: boolean }>;- getProposalDiff: (params: { runId: string }) => Promise<import('../shared/learnTypes').LearnProposalDiff>;- apply: (params: { runId: string }) => Promise<{ name: string; absolutePath: string; replacedBackupPath?: string }>;+ start: (req: import('../shared/learnTypes').LearnStartRequest) => Promise<{ runId: string }>;+ listRuns: () => Promise<{+ runs: import('../shared/learnTypes').LearnRunPublic[];+ ready: boolean;+ }>;+ getProposalDiff: (params: {+ runId: string;+ }) => Promise<import('../shared/learnTypes').LearnProposalDiff>;+ apply: (params: {+ runId: string;+ }) => Promise<{ name: string; absolutePath: string; replacedBackupPath?: string }>;discard: (params: { runId: string }) => Promise<{ ok: boolean }>;cancel: (params: { runId: string }) => Promise<{ ok: boolean }>;onEvent: (@@ -2609,9 +2730,7 @@ interface ElectronAPI {// ── SkillHub (xdt-maker-技能中心 v0.2) ──skillhub: {- scan: (params: {- projects?: SkillhubProjectInput[];- }) => Promise<{+ scan: (params: { projects?: SkillhubProjectInput[] }) => Promise<{success: boolean;error?: string;skills?: SkillhubSkill[];@@ -2650,14 +2769,18 @@ interface ElectronAPI {| { success: false; error: string }>;/** 改名整个 skill (目录名 + SKILL.md frontmatter `name`),用于撞名发布流程。 */- renameLocal: (params: { absolutePath: string; newName: string }) => Promise<- | { success: true; newAbsolutePath: string }- | { success: false; error: string }- >;+ renameLocal: (params: {+ absolutePath: string;+ newName: string;+ }) => Promise<{ success: true; newAbsolutePath: string } | { success: false; error: string }>;// ── v0.2.1: publish pipeline ──- sync: (params: string[] | {- slugs?: string[];- }) => Promise<{+ sync: (+ params:+ | string[]+ | {+ slugs?: string[];+ },+ ) => Promise<{success: boolean;error?: string;results?: SkillhubSyncResult[];@@ -2748,8 +2871,12 @@ interface ElectronAPI {teamSlug?: string | null;};}) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;- deletePublished: (name: string) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;- unpublishPublished: (name: string) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;+ deletePublished: (+ name: string,+ ) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;+ unpublishPublished: (+ name: string,+ ) => Promise<{ success: boolean; result?: unknown; error?: string; errorCode?: string }>;setPublishedVisibility: (params: {name: string;visibility: 'private' | 'shared' | 'public';@@ -2775,10 +2902,7 @@ interface ElectronAPI {* - hasSnapshot=false:本地无快照(历史 publish 或换机器),UI 显示"无快照"提示* - changes:文件粒度 add/remove/modify,文本文件已带内容,二进制只带 size*/- getSnapshotDiff: (params: {- absolutePath: string;- name: string;- }) => Promise<{+ getSnapshotDiff: (params: { absolutePath: string; name: string }) => Promise<{success: boolean;hasSnapshot?: boolean;changes?: Array<{@@ -2792,14 +2916,19 @@ interface ElectronAPI {}>;error?: string;}>;- getUsageSummary: (params: { name: string; mdPath?: string }) => Promise<+ getUsageSummary: (params: {+ name: string;+ mdPath?: string;+ }) => Promise<| { success: true; summary: SkillUsageSummary; refreshing: boolean }| { success: false; error: string }>;onUsageAnalyticsRefreshed: (callback: () => void) => () => void;- getUsageDiagnosisContext: (params: { name: string; mdPath?: string }) => Promise<- | { success: true; context: SkillUsageDiagnosisContext }- | { success: false; error: string }+ getUsageDiagnosisContext: (params: {+ name: string;+ mdPath?: string;+ }) => Promise<+ { success: true; context: SkillUsageDiagnosisContext } | { success: false; error: string }>;getMyDepts: () => Promise<{success: boolean;@@ -2823,7 +2952,14 @@ interface ElectronAPI {}>;listUserTeams: () => Promise<{success: boolean;- teams: Array<{ slug: string; name: string; type: string; source?: string | null; isPersonal?: boolean; myRole?: 'admin' | 'publisher' | 'viewer' }>;+ teams: Array<{+ slug: string;+ name: string;+ type: string;+ source?: string | null;+ isPersonal?: boolean;+ myRole?: 'admin' | 'publisher' | 'viewer';+ }>;error?: string;}>;publish: (params: SkillhubPublishParams) => Promise<{@@ -2835,9 +2971,7 @@ interface ElectronAPI {cancelPublish: () => Promise<{ success: boolean }>;startScanPoll: (params: { slug: string; version: string }) => Promise<{ success: boolean }>;stopScanPoll: () => Promise<{ success: boolean }>;- onPublishProgress: (- callback: (event: SkillhubPublishProgressEvent) => void,- ) => () => void;+ onPublishProgress: (callback: (event: SkillhubPublishProgressEvent) => void) => () => void;// ── Market install / uninstall / cancel ──// 冲突手写技能 → errorCode='CONFLICT_USER_OWNED',UI 弹确认后重发 with force:true@@ -2867,7 +3001,13 @@ interface ElectronAPI {};/** 一次性补齐:把 server 权威 authorId 写回本地 registry。 */reconcileMineRegistry: (- items: Array<{ name: string; absolutePath: string; version: string; authorId: string; folderHash?: string }>,+ items: Array<{+ name: string;+ absolutePath: string;+ version: string;+ authorId: string;+ folderHash?: string;+ }>,) => Promise<{success: boolean;added: number;@@ -2875,10 +3015,9 @@ interface ElectronAPI {failures: Array<{ name: string; error: string }>;}>;cancelInstall: (name: string) => Promise<{ success: boolean }>;- uninstall: (absolutePath: string) => Promise<- | { success: true }- | { success: false; errorCode: string; message: string }- >;+ uninstall: (+ absolutePath: string,+ ) => Promise<{ success: true } | { success: false; errorCode: string; message: string }>;/** 在 main 内选择并检查本地包,成功时签发绑定当前 renderer 的短期导入授权。 */pickLocal: () => Promise<| { success: true; canceled: true }@@ -2893,11 +3032,7 @@ interface ElectronAPI {| { success: false; errorCode: string; message: string }>;/** 使用 main 签发的文件授权导入;registry origin=imported。 */- importLocal: (params: {- grantToken: string;- installPath?: string;- force?: boolean;- }) => Promise<+ importLocal: (params: { grantToken: string; installPath?: string; force?: boolean }) => Promise<| {success: true;name: string;@@ -3036,7 +3171,9 @@ interface ElectronAPI {getUpdateStatus: () => Promise<{ status: string; version?: string; errorCode?: string }>;/** Query and update auto-apply settings for downloaded app updates. */getAutoUpdateSettings: () => Promise<AutoUpdateSettingsPayload>;- setAutoUpdateSettings: (settings: { autoRelaunchOnIdle: boolean }) => Promise<AutoUpdateSettingsPayload>;+ setAutoUpdateSettings: (settings: {+ autoRelaunchOnIdle: boolean;+ }) => Promise<AutoUpdateSettingsPayload>;resetAutoUpdateSettings: () => Promise<AutoUpdateSettingsPayload>;setUpdateRelaunchTheme: (theme: 'light' | 'dark') => void;// E4D 毛玻璃:family 切换/启动通知 main 开关 vibrancy(仅 CINDY 透壁纸)@@ -3052,7 +3189,8 @@ interface ElectronAPI {* - 'manual_download' → Linux 首版仅支持手动下载安装包*/checkForUpdate: () => Promise<{- result: 'ready' | 'idle' | 'downloading' | 'manifest_failed' | 'download_failed' | 'manual_download';+ result:+ 'ready' | 'idle' | 'downloading' | 'manifest_failed' | 'download_failed' | 'manual_download';}>;/*** 现在重启会不会打断正在跑的活(逻辑 turn / Claude 后台活动 / Ghost card-action 后台活动@@ -3092,9 +3230,7 @@ interface ElectronAPI {* Returns null on 404 / network error / parse error — caller decides* whether to surface a toast or stay silent.*/- fetchReleaseNotes: (- version: string,- ) => Promise<RawReleaseNotesPayload | null>;+ fetchReleaseNotes: (version: string) => Promise<RawReleaseNotesPayload | null>;/*** Sorted ascending list of every version with a notice on the CDN. Used by@@ -3123,7 +3259,10 @@ interface ElectronAPI {enabled: boolean,) => Promise<{ deviceId: string; enabled: boolean; disabledControlDeviceIds: string[] }>;listDevices: () => Promise<{ devices: DeviceLinkDeviceView[] }>;- renameDevice: (deviceId: string, name: string | null) => Promise<{ deviceId: string; name: string; manualName?: string | null }>;+ renameDevice: (+ deviceId: string,+ name: string | null,+ ) => Promise<{ deviceId: string; name: string; manualName?: string | null }>;deleteDevice: (deviceId: string) => Promise<{ deviceId: string; deleted: boolean }>;// —— 控制端:远程会话视图 ——openLink: (deviceId: string) => Promise<{ appVersion: string; allowlistHash: string }>;@@ -3154,7 +3293,15 @@ interface ElectronAPI {onOwnershipChanged: (cb: (payload: { standby: boolean }) => void) => () => void;/** 控制端:被控端转发回来的 renderer 广播事件 */onRemotePush: (- cb: (payload: { deviceId: string; channel: string; payload: unknown }) => void,+ cb: (+ payload: {+ deviceId: string;+ channel: string;+ payload: unknown;+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp;+ },+ localOwnerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,+ ) => void,) => () => void;/** 被控端可见性:本机正在被哪些控制端控制 */onControlledState: (@@ -3241,23 +3388,46 @@ interface ElectronAPI {onStatusChanged: (cb: (snap: RemoteHostSnapshot) => void) => () => void;// Phase B: agent-on-remoteprobeAgent: (id: string, kind: RemoteAgentKind) => Promise<{ probe: RemoteAgentProbe }>;- installAgent: (id: string, kind: RemoteAgentKind) => Promise<{ result: RemoteAgentInstallResult }>;+ installAgent: (+ id: string,+ kind: RemoteAgentKind,+ ) => Promise<{ result: RemoteAgentInstallResult }>;uninstallAgent: (id: string, kind: RemoteAgentKind) => Promise<{ ok: true }>;- runAgentOneShot: (id: string, kind: RemoteAgentKind, prompt: string) => Promise<{ result: RemoteAgentOneShotResult }>;+ runAgentOneShot: (+ id: string,+ kind: RemoteAgentKind,+ prompt: string,+ ) => Promise<{ result: RemoteAgentOneShotResult }>;// Generic remote fs primitives (Phase C) — reusable by a future remote// file browser. Both accept '~' / '~/...' and let remote bash expand to $HOME.- statRemotePath: (id: string, path: string) => Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }>;+ statRemotePath: (+ id: string,+ path: string,+ ) => Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }>;mkdirPRemote: (id: string, path: string) => Promise<{ resolvedPath: string }>;- setAutoConnect: (id: string, autoConnect: boolean) => Promise<{ ok: true; autoConnect: boolean }>;+ setAutoConnect: (+ id: string,+ autoConnect: boolean,+ ) => Promise<{ ok: true; autoConnect: boolean }>;hasAnyAutoConnectHost: () => Promise<{ hasAny: boolean }>;- listRemoteDir: (id: string, path: string) => Promise<{+ listRemoteDir: (+ id: string,+ path: string,+ ) => Promise<{resolvedPath: string;entries: Array<{ name: string; kind: 'dir' | 'symlink' }>;}>;onInstallProgress: (cb: (payload: RemoteAgentInstallProgressPush) => void) => () => void;- onSilentInstallStatus: (cb: (payload: RemoteAgentSilentInstallStatusPush) => void) => () => void;- onCcMgrUpgradeAvailable: (cb: (payload: RemoteAgentCcMgrUpgradeAvailablePush) => void) => () => void;- ccMgrForceUpgrade: (hostId: string, sessionId?: string) => Promise<{ ok: true; daemonReady: boolean }>;+ onSilentInstallStatus: (+ cb: (payload: RemoteAgentSilentInstallStatusPush) => void,+ ) => () => void;+ onCcMgrUpgradeAvailable: (+ cb: (payload: RemoteAgentCcMgrUpgradeAvailablePush) => void,+ ) => () => void;+ ccMgrForceUpgrade: (+ hostId: string,+ sessionId?: string,+ ) => Promise<{ ok: true; daemonReady: boolean }>;ccMgrListPendingUpgrades: () => Promise<{pending: Array<{ hostId: string; currentVersion: string; availableVersion: string }>;}>;@@ -3294,7 +3464,10 @@ interface ElectronAPI {};}>;readPubkey: (pubkeyPath: string) => Promise<{ content: string }>;- buildInstallCmd: (id: string, pubkeyPath: string) => Promise<{+ buildInstallCmd: (+ id: string,+ pubkeyPath: string,+ ) => Promise<{command: string;platform: NodeJS.Platform;}>;@@ -3325,12 +3498,8 @@ interface ElectronAPI {worktreeGetForSession: (sessionId: string,) => Promise<import('@/lib/worktree.types').WorktreeMeta | null>;- worktreeListAll: () => Promise<- import('@/lib/worktree.types').WorktreeMeta[]- >;- worktreeReveal: (req: {- path: string;- }) => Promise<import('@/lib/worktree.types').RevealResp>;+ worktreeListAll: () => Promise<import('@/lib/worktree.types').WorktreeMeta[]>;+ worktreeReveal: (req: { path: string }) => Promise<import('@/lib/worktree.types').RevealResp>;worktreeSuggestName: (req: {baseRepo: string;}) => Promise<import('@/lib/worktree.types').SuggestNameResp>;@@ -3338,19 +3507,17 @@ interface ElectronAPI {baseRepo: string;}) => Promise<import('@/lib/worktree.types').ListBranchesResp>;// P1: 删除/归档确认预检- worktreeRemovalPreview: (- sessionId: string,- ) => Promise<{ hasWorktree: boolean; dirty: boolean }>;+ worktreeRemovalPreview: (sessionId: string) => Promise<{ hasWorktree: boolean; dirty: boolean }>;// P1: worktree 回收后的可恢复状态 + 一键恢复- worktreeRestoreStatus: (sessionId: string) => Promise<+ worktreeRestoreStatus: (+ sessionId: string,+ ) => Promise<| { state: 'present'; worktreePath: string; hasSnapshot?: boolean }| { state: 'no-worktree' }| { state: 'restorable'; worktreePath: string; hasSnapshot: boolean }| { state: 'gone'; worktreePath: string }>;- worktreeRestoreForSession: (- sessionId: string,- ) => Promise<{+ worktreeRestoreForSession: (sessionId: string) => Promise<{ok: boolean;snapshotApplied?: boolean;reason?: 'gone' | 'no-worktree' | 'git-error';@@ -3360,9 +3527,7 @@ interface ElectronAPI {* 「worktree 回收链已跑完」推送。归档/删除后 main 侧的回收是 fire-and-forget 的* 异步链,store 条目移除远晚于状态 IPC 返回,renderer 必须等这条才能拿到真实快照。*/- onWorktreeChanged: (- callback: (payload: { sessionId: string }) => void,- ) => () => void;+ onWorktreeChanged: (callback: (payload: { sessionId: string }) => void) => () => void;// ── Slack Hook(中心 slack-hook-server 接入) ── 类型正本在 shared/hookControlIpc.tshookControl: {@@ -3476,9 +3641,7 @@ interface ElectronAPI {// ── session-git-pr-context: 会话分支感知 + PR 关联状态 ──gitContext: {- get: (- workdir: string,- ) => Promise<import('@/lib/gitContext.types').GitContextSnapshot>;+ get: (workdir: string) => Promise<import('@/lib/gitContext.types').GitContextSnapshot>;getForSession: (input: {sessionId: string;workingDir: string | null;@@ -3486,9 +3649,7 @@ interface ElectronAPI {}) => Promise<import('@/lib/gitContext.types').SessionGitDirResult>;watch: (workdir: string) => Promise<void>;unwatch: (workdir: string) => Promise<void>;- listPrRefs: (- sessionId: string,- ) => Promise<import('@/lib/gitContext.types').SessionPrRef[]>;+ listPrRefs: (sessionId: string) => Promise<import('@/lib/gitContext.types').SessionPrRef[]>;/** null = main 侧 db 尚未就绪(登录前/启动期),调用方应稍后重试。 */listAllPrRefs: () => Promise<import('@/lib/gitContext.types').SessionPrRef[] | null>;getPrStatuses: (@@ -3501,26 +3662,83 @@ interface ElectronAPI {};gitReview: {- get: (params: { sessionId: string; ignoreWhitespace?: boolean }) => Promise<import('@/lib/gitReview.types').ReviewData>;- summary: (params: { sessionId: string }) => Promise<import('@/lib/gitReview.types').ReviewDirtySummary>;- commits: (params: { sessionId: string; baseRef?: string | null }) => Promise<import('@/lib/gitReview.types').ReviewCommitListData>;- commitDiff: (params: { sessionId: string; oid: string; ignoreWhitespace?: boolean }) => Promise<import('@/lib/gitReview.types').ReviewCommitDiffData>;- branchDiff: (params: { sessionId: string; baseRef?: string | null; ignoreWhitespace?: boolean }) => Promise<import('@/lib/gitReview.types').ReviewBranchDiffData>;- fileDiff: (params: { sessionId: string } & import('@/lib/gitReview.types').ReviewFileDiffRequest) => Promise<import('@/lib/gitReview.types').ReviewFileDiffData>;- imagePreview: (params: { sessionId: string; diff: import('@/lib/gitReview.types').FileDiff; commitOid?: string | null; branchBaseRef?: string | null }) => Promise<import('@/lib/gitReview.types').ReviewImagePreviewData>;- markdownPreview: (params: { sessionId: string; diff: import('@/lib/gitReview.types').FileDiff; commitOid?: string | null; branchBaseRef?: string | null }) => Promise<import('@/lib/gitReview.types').ReviewMarkdownPreviewData>;+ get: (params: {+ sessionId: string;+ ignoreWhitespace?: boolean;+ }) => Promise<import('@/lib/gitReview.types').ReviewData>;+ summary: (params: {+ sessionId: string;+ }) => Promise<import('@/lib/gitReview.types').ReviewDirtySummary>;+ commits: (params: {+ sessionId: string;+ baseRef?: string | null;+ }) => Promise<import('@/lib/gitReview.types').ReviewCommitListData>;+ commitDiff: (params: {+ sessionId: string;+ oid: string;+ ignoreWhitespace?: boolean;+ }) => Promise<import('@/lib/gitReview.types').ReviewCommitDiffData>;+ branchDiff: (params: {+ sessionId: string;+ baseRef?: string | null;+ ignoreWhitespace?: boolean;+ }) => Promise<import('@/lib/gitReview.types').ReviewBranchDiffData>;+ fileDiff: (+ params: { sessionId: string } & import('@/lib/gitReview.types').ReviewFileDiffRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewFileDiffData>;+ imagePreview: (params: {+ sessionId: string;+ diff: import('@/lib/gitReview.types').FileDiff;+ commitOid?: string | null;+ branchBaseRef?: string | null;+ }) => Promise<import('@/lib/gitReview.types').ReviewImagePreviewData>;+ markdownPreview: (params: {+ sessionId: string;+ diff: import('@/lib/gitReview.types').FileDiff;+ commitOid?: string | null;+ branchBaseRef?: string | null;+ }) => Promise<import('@/lib/gitReview.types').ReviewMarkdownPreviewData>;openFile: (params: { sessionId: string; path: string }) => Promise<void>;- stageFile: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- unstageFile: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- discardFile: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- stageHunk: (params: import('@/lib/gitReview.types').ReviewHunkOperationRequest) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- unstageHunk: (params: import('@/lib/gitReview.types').ReviewHunkOperationRequest) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- discardHunk: (params: import('@/lib/gitReview.types').ReviewHunkOperationRequest) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- stageAll: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- unstageAll: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- discardAll: (params: { sessionId: string; targets: import('@/lib/gitReview.types').ReviewFileTarget[] }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;- commit: (params: import('@/lib/gitReview.types').ReviewCommitRequest) => Promise<import('@/lib/gitReview.types').ReviewCommitResult>;- push: (params: { sessionId: string; confirmForce?: import('@/lib/gitReview.types').ReviewPushConfirmForce }) => Promise<import('@/lib/gitReview.types').ReviewPushResult>;+ stageFile: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ unstageFile: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ discardFile: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ stageHunk: (+ params: import('@/lib/gitReview.types').ReviewHunkOperationRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ unstageHunk: (+ params: import('@/lib/gitReview.types').ReviewHunkOperationRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ discardHunk: (+ params: import('@/lib/gitReview.types').ReviewHunkOperationRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ stageAll: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ unstageAll: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ discardAll: (params: {+ sessionId: string;+ targets: import('@/lib/gitReview.types').ReviewFileTarget[];+ }) => Promise<import('@/lib/gitReview.types').ReviewStageOperationResult>;+ commit: (+ params: import('@/lib/gitReview.types').ReviewCommitRequest,+ ) => Promise<import('@/lib/gitReview.types').ReviewCommitResult>;+ push: (params: {+ sessionId: string;+ confirmForce?: import('@/lib/gitReview.types').ReviewPushConfirmForce;+ }) => Promise<import('@/lib/gitReview.types').ReviewPushResult>;};// sidebar 偏好(置顶手动顺序)跨 dev / installed 共享;读 sendSync,写 invoke。@@ -3535,12 +3753,8 @@ interface ElectronAPI {remotePrecreatedWorktreeLedger: {list: () => Promise<RemotePrecreatedWorktreeLedgerSnapshot>;- register: (- record: PendingRemotePrecreatedWorktree,- ) => Promise<{ persisted: boolean }>;- forget: (- target: PendingRemotePrecreatedWorktreeTarget,- ) => Promise<{ persisted: boolean }>;+ register: (record: PendingRemotePrecreatedWorktree) => Promise<{ persisted: boolean }>;+ forget: (target: PendingRemotePrecreatedWorktreeTarget) => Promise<{ persisted: boolean }>;};// ── session 级"终身累计 cost"变化 (per-session, 不是 today-aggregate) ──@@ -3550,10 +3764,13 @@ interface ElectronAPI {sessionId: string;totalMoney: import('../shared/regionalMoney').RegionalMoney;totalCostUsd?: number;- }) => void,+ }, ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void,) => () => void;onUsageSessionTokensChanged: (- cb: (data: { sessionId: string; totalTokens: number }) => void,+ cb: (+ data: { sessionId: string; totalTokens: number },+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,+ ) => void,) => () => void;// per-message 维度: turn 结束后 main 推该轮费用(挂在最后一条 assistant 上)。@@ -3563,6 +3780,7 @@ interface ElectronAPI {onUsageMessageTurnCost: (cb: (data: import('../shared/turnCostPayload').MessageTurnCostPayload,+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,) => void,) => () => void;@@ -3573,7 +3791,7 @@ interface ElectronAPI {sessionId: string;clientId: string;modelMismatch: import('../shared/modelMismatch').ModelMismatchInfo;- }) => void,+ }, ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void,) => () => void;// ── 首登轻量数据迁移(mToc) — 老 userData → Cindy 一次性复制迁移弹窗 ──@@ -3591,9 +3809,7 @@ interface ElectronAPI {// ── chat-data-localization (M-FE2) — local SQLite IPC bridge ──localDb: {/** Open / migrate the per-user db file. Failure → fatal dialog + ready:false. */- ensureReady: (- userId: string,- ) => Promise<+ ensureReady: (userId: string) => Promise<| { ready: true }| {ready: false;@@ -3685,7 +3901,12 @@ interface ElectronAPI {/** 从最近列表移除一条(列表卫生,不动 sessions / 磁盘;再次使用会重新入列)。 */remove: (input: { path: string }) => Promise<{ deleted: boolean }>;/** Broadcast: 任一窗口/远程调用删除条目后通知;返回退订函数。 */- onChanged: (callback: (data: { path: string }) => void) => () => void;+ onChanged: (+ callback: (+ data: { path: string },+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,+ ) => void,+ ) => () => void;};rightSidebarTabs: {/** 按 sessionId 拉 tab 列表 + activeTabId(右侧栏多 Tab 容器)。 */@@ -3756,7 +3977,11 @@ interface ElectronAPI {) => Promise<{ matched: number; inserted: number; updated: number; scanned: number }>;};sessionShare: {- export: (request: { sessionId: string; password?: string; excludeMedia?: boolean }) => Promise<+ export: (request: {+ sessionId: string;+ password?: string;+ excludeMedia?: boolean;+ }) => Promise<| {status: 'ok';filePath: string;@@ -3767,7 +3992,9 @@ interface ElectronAPI {| { status: 'canceled' }| { status: 'oversize'; totalBytes: number; mediaBytes: number; limitBytes: number }>;- inspect: (request?: { filePath?: string }) => Promise<+ inspect: (request?: {+ filePath?: string;+ }) => Promise<| { status: 'canceled' }| { draftId: string; encrypted: true }| { draftId: string; encrypted: false; preview: SessionSharePreview }@@ -3795,7 +4022,9 @@ interface ElectronAPI {notes: string[];}>;cancel: (request: { draftId: string }) => Promise<{ ok: boolean }>;- classifyPath: (request: { path: string }) => Promise<{ kind: 'share' | 'directory' | 'other' }>;+ classifyPath: (request: {+ path: string;+ }) => Promise<{ kind: 'share' | 'directory' | 'other' }>;};orcaWorkflows: {getByLeadSession: (leadSessionId: string) => Promise<OrcaTeamRecord | null>;@@ -3809,7 +4038,11 @@ interface ElectronAPI {onOrcaWorkerChanged: (cb: (payload: unknown) => void) => () => void;createWorker: (input: Record<string, unknown>) => Promise<unknown>;switchFocus: (input: Record<string, unknown>) => Promise<unknown>;- idleWorker: (leadSessionId: string, workerId: string, expectedStatus?: 'done') => Promise<unknown>;+ idleWorker: (+ leadSessionId: string,+ workerId: string,+ expectedStatus?: 'done',+ ) => Promise<unknown>;archiveWorker: (leadSessionId: string, workerId: string) => Promise<unknown>;endTeam: (leadSessionId: string) => Promise<unknown>;getCollaborationSettings: () => Promise<unknown>;@@ -3821,9 +4054,7 @@ interface ElectronAPI {sessionId: string,opts?: { limit?: number; before?: string; beforeTs?: number },) => Promise<import('@/lib/ccAgent.types').Message[]>;- estimatedSessionValue: (- sessionId: string,- ) => Promise<{+ estimatedSessionValue: (sessionId: string) => Promise<{totalValueMoney?: import('../shared/regionalMoney').RegionalMoney | null;totalValueUsd?: number;entries: Array<{@@ -3869,34 +4100,39 @@ interface ElectronAPI {callback: (payload: {sessionId: string;message: import('@/lib/ccAgent.types').Message;- }) => void,+ }, ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void,) => () => void;onDeleted: (- callback: (payload: { sessionId: string; clientId: string }) => void,+ callback: (+ payload: { sessionId: string; clientId: string },+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,+ ) => void,) => () => void;onErrorPersisted: (- callback: (payload: { sessionId: string }) => void,+ callback: (+ payload: { sessionId: string },+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,+ ) => void,) => () => void;};sessionsPush: {onCreated: (- callback: (payload: { sessionId: string }) => void,+ callback: (+ payload: { sessionId: string },+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,+ ) => void,) => () => void;onPatched: (callback: (payload: {sessionId: string;patch: Partial<import('@/lib/ccAgent.types').Session>;- }) => void,+ }, ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void,) => () => void;};/** V0.4 (C10): one-shot toast trigger when ensureReady ran two-level fallback. */- onCorruptionRestored: (- cb: (info: CorruptionRestoredPayload) => void,- ) => () => void;+ onCorruptionRestored: (cb: (info: CorruptionRestoredPayload) => void) => () => void;/** #37: release 端检测到 schema drift 时的一次性 toast 事件。 */- onSchemaDriftWarning: (- cb: (info: SchemaDriftWarningPayload) => void,- ) => () => void;+ onSchemaDriftWarning: (cb: (info: SchemaDriftWarningPayload) => void) => () => void;};// ── RSB browser bridge (Phase 2) ───────────────────────────────────────────@@ -3927,9 +4163,7 @@ interface ElectronAPI {/** 工具栏截图按钮:main 端 capturePage 后写入系统剪贴板。失败抛 IPC error。 */captureScreenshot: (input: { tabId: string }) => Promise<{ ok: true }>;/** 页面评论:main 端 capturePage 后返回 PNG 字节(不写剪贴板)。失败抛 IPC error。 */- captureScreenshotData: (input: {- tabId: string;- }) => Promise<{ ok: true; data: Uint8Array }>;+ captureScreenshotData: (input: { tabId: string }) => Promise<{ ok: true; data: Uint8Array }>;/** main → renderer:把 tabId 标记为 automation pinned(LRU 跳过)。 */onPin: (cb: (payload: { tabId: string }) => void) => () => void;/** main → renderer:取消 automation pin。 */@@ -3940,9 +4174,7 @@ interface ElectronAPI {* 完后通过 `tabOpResult` 回报。*/onTabOpRequest: (- cb: (- req: import('../shared/rsbBrowserBridge').RsbBrowserBridgeTabOpRequest,- ) => void,+ cb: (req: import('../shared/rsbBrowserBridge').RsbBrowserBridgeTabOpRequest) => void,) => () => void;/** renderer → main:tab-op-request 的结果,按 reqId 关联。 */tabOpResult: (@@ -3957,9 +4189,7 @@ interface ElectronAPI {forceKill: (input: { tabId: string; webContentsId?: number }) => Promise<{ ok: true }>;/** main → renderer:资源看门狗事件(evict-request / kill-notice / cpu-alert)。 */onResourceEvent: (- cb: (- event: import('../shared/rsbBrowserBridge').RsbBrowserBridgeResourceEvent,- ) => void,+ cb: (event: import('../shared/rsbBrowserBridge').RsbBrowserBridgeResourceEvent) => void,) => () => void;};@@ -4050,7 +4280,9 @@ interface ElectronAPI {) => Promise<{ ok: true }>;deleteCustomProvider: (providerId: string) => Promise<{ ok: true }>;/** 自定义供应商创建模板(目录 presets 段,纯 UI 模板数据)。 */- listProviderPresets: () => Promise<{ presets: import('@cindy/model-providers').ProviderPreset[] }>;+ listProviderPresets: () => Promise<{+ presets: import('@cindy/model-providers').ProviderPreset[];+ }>;/** 供应商「测试连接」—— 与真实会话同路由口径的最小探测请求(结构化结果,code 走 providerError.* i18n)。 */testProviderConnection: (input:@@ -4232,9 +4464,7 @@ interface ElectronAPI {ctx: { sessionId?: string; workingDir?: string; args?: string; deviceId?: string },) => Promise<{ success: boolean; error?: string }>;- listAgentCommands: (- agentKind: 'claude-code' | 'codex' | 'pi',- ) => Promise<{+ listAgentCommands: (agentKind: 'claude-code' | 'codex' | 'pi') => Promise<{success: boolean;error?: string;commands?: Array<{ kind: 'agent-builtin'; name: string; description: string }>;@@ -4287,14 +4517,23 @@ interface ElectronAPI {setGoal: (input: {sessionId: string;objective: string;- limits?: { maxTurns: number | null; budgetTokens: number | null; noProgressLimit: number | null };+ limits?: {+ maxTurns: number | null;+ budgetTokens: number | null;+ noProgressLimit: number | null;+ };}) => Promise<{ ok: boolean }>;clearGoal: (sessionId: string) => Promise<{ ok: boolean }>;pauseGoal: (sessionId: string) => Promise<{ ok: boolean }>;resumeGoal: (sessionId: string) => Promise<{ ok: boolean }>;updateGoal: (sessionId: string,- patch: { objective?: string; maxTurns?: number | null; budgetTokens?: number | null; noProgressLimit?: number | null },+ patch: {+ objective?: string;+ maxTurns?: number | null;+ budgetTokens?: number | null;+ noProgressLimit?: number | null;+ },) => Promise<{ ok: boolean }>;getGoalStatus: (sessionId: string) => Promise<GoalStatusPayload | null>;onGoalStatusChanged: (@@ -4356,7 +4595,13 @@ interface ElectronAPI {/** 远端 host alias (Codex only) — codex agent 跑在远端机器上, workingDir 是远端路径。 */remoteHostId?: string;vendorOptions?: Record<string, unknown>;- }) => Promise<{ sessionId: string; agentKind: string; workDir: string; capabilities: unknown; usedProjectContext?: boolean }>;+ }) => Promise<{+ sessionId: string;+ agentKind: string;+ workDir: string;+ capabilities: unknown;+ usedProjectContext?: boolean;+ }>;markOrcaRole: (sessionId: string,@@ -4398,7 +4643,8 @@ interface ElectronAPI {*/send: (sessionId: string,- message: string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },+ message:+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },createOpts?: {agentKind: 'claude-code' | 'codex' | 'pi';workingDir: string;@@ -4433,7 +4679,8 @@ interface ElectronAPI {steer: (sessionId: string,- message: string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },+ message:+ string | { type: 'user'; content: string | Array<{ type: string; [k: string]: unknown }> },sendOpts?: {/** 这条 user 消息的 SDK uuid (renderer 与 messages.agent_meta.uuid 同源, rewind 锚点)。 */messageUuid?: string;@@ -4471,69 +4718,101 @@ interface ElectronAPI {sessionId: string,clientId: string,) => Promise<{ sessionId: string; clientId: string; clientIds: string[] }>;- listActive: () => Promise<Array<{- sessionId: string;- agentKind: 'claude-code' | 'codex' | 'pi';- workDir: string;- capabilities: unknown;- isTurnRunning: boolean;- }>>;+ listActive: () => Promise<+ Array<{+ sessionId: string;+ agentKind: 'claude-code' | 'codex' | 'pi';+ workDir: string;+ capabilities: unknown;+ isTurnRunning: boolean;+ }>+ >;onInputProjection: (cb: (payload: import('../shared/agentInputQueue').AgentInputProjection) => void,) => () => void;input: {- getProjection: (sessionId: string) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;+ getProjection: (+ sessionId: string,+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;enqueue: (sessionId: string,item: import('../shared/agentInputQueue').AgentInputQueuedMessage,- opts?: { sendAtMs?: number },+ opts?: { sendAtMs?: number; expectedClearBoundaryMs?: number | null },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;compact: (sessionId: string,createOpts: import('../shared/agentInputQueue').AgentInputCreateOpts,- opts?: { userName?: string },+ opts?: { userName?: string; expectedClearBoundaryMs?: number | null },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;steer: (sessionId: string,item: import('../shared/agentInputQueue').AgentInputQueuedMessage,- opts?: { removeFromQueue?: boolean; touchUserSend?: boolean },+ opts?: {+ removeFromQueue?: boolean;+ touchUserSend?: boolean;+ expectedClearBoundaryMs?: number | null;+ },) => Promise<boolean>;stop: (sessionId: string,- opts?: { keepQueue?: boolean; pauseQueue?: boolean },+ opts?: {+ keepQueue?: boolean;+ pauseQueue?: boolean;+ expectedClearBoundaryMs?: number | null;+ },+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;+ resume: (+ sessionId: string,+ opts?: { expectedClearBoundaryMs?: number | null },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;- resume: (sessionId: string) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;- retryLastError: (sessionId: string) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;- clearError: (sessionId: string) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;- persistTurnErrorDeferred: (sessionId: string, errData: Record<string, unknown> | null, agentMeta?: import('@/lib/ccAgent.types').AgentMeta | null) => Promise<void>;+ retryLastError: (+ sessionId: string,+ opts?: { expectedClearBoundaryMs?: number | null },+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;+ clearError: (+ sessionId: string,+ opts?: { expectedClearBoundaryMs?: number | null },+ ) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;+ persistTurnErrorDeferred: (+ sessionId: string,+ errData: Record<string, unknown> | null,+ agentMeta?: import('@/lib/ccAgent.types').AgentMeta | null,+ ) => Promise<void>;remove: (sessionId: string,clientId: string,+ opts?: { expectedClearBoundaryMs?: number | null },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;updateText: (sessionId: string,clientId: string,newText: string,sessionRefs?: import('../shared/agentInputQueue').AgentInputSessionRef[],+ trustedContexts?: import('../shared/agentInputQueue').AgentInputSessionReferenceContext[],+ opts?: { expectedClearBoundaryMs?: number | null },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;move: (sessionId: string,clientId: string,targetIndex: number,+ opts?: { expectedClearBoundaryMs?: number | null },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;setExpanded: (sessionId: string,expanded: boolean,+ opts?: { expectedClearBoundaryMs?: number | null },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;setInteractionLock: (sessionId: string,lockId: string,locked: boolean,+ opts?: { expectedClearBoundaryMs?: number | null },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;setEditLock: (sessionId: string,clientId: string,locked: boolean,+ opts?: { expectedClearBoundaryMs?: number | null },) => Promise<import('../shared/agentInputQueue').AgentInputProjection>;clearSession: (sessionId: string,@@ -4542,10 +4821,7 @@ interface ElectronAPI {};/** Resolve a pending interaction (permission / ask_user_question / plan_review). */- resolveInteraction: (- requestId: string,- decision: Record<string, unknown>,- ) => Promise<void>;+ resolveInteraction: (requestId: string, decision: Record<string, unknown>) => Promise<void>;/** Submit one inline plugin Secret through the local trusted-frame-only IPC. */submitPluginSetupInline: (request: {@@ -4558,7 +4834,12 @@ interface ElectronAPI {/** 快照:某会话当前挂起交互(permission/ask/plan),打开/重连/刷新会话时拉一次重建面板。 */getPendingInteractions: (sessionId: string,- ) => Promise<Array<{ request: { kind: string; requestId: string; [k: string]: unknown }; persistId?: string }>>;+ ) => Promise<+ Array<{+ request: { kind: string; requestId: string; [k: string]: unknown };+ persistId?: string;+ }>+ >;// ── 运行时切换 (Stage 2 B) ─────────────────────────────────────────────// session 不存在(没 send 过/已 close)时 main 侧 no-op,renderer 可乐观调用。@@ -4584,14 +4865,20 @@ interface ElectronAPI {providerId?: string | null,effort?: string,fastMode?: boolean,- ) => Promise<{ switched: boolean; agentKind: 'claude-code' | 'codex' | 'pi'; model: string; engineReady: boolean; deferred?: boolean; sameEngineRevision?: number; sameEngineSuperseded?: boolean }>;+ ) => Promise<{+ switched: boolean;+ agentKind: 'claude-code' | 'codex' | 'pi';+ model: string;+ engineReady: boolean;+ deferred?: boolean;+ sameEngineRevision?: number;+ sameEngineSuperseded?: boolean;+ }>;/*** 读 main 权威的 pending 切换意图(内存态,不落库;无意图 → null)。* 重开视图 / device-link 远程会话重连后恢复乐观显示用。*/- getSessionAgentSwitchIntent: (- sessionId: string,- ) => Promise<{+ getSessionAgentSwitchIntent: (sessionId: string) => Promise<{targetAgentKind: 'claude-code' | 'codex' | 'pi';model: string;providerId: string | null;@@ -4667,7 +4954,12 @@ interface ElectronAPI {makerMemoryReset: () => Promise<{ removedCount: number }>;/** 启动期拉 main 持久化的三个 memory 开关 — 见 preload memoryGetSettings 注释 */- memoryGetSettings: () => Promise<{ maker: boolean; claudeCode: boolean; codex: boolean; pi: boolean }>;+ memoryGetSettings: () => Promise<{+ maker: boolean;+ claudeCode: boolean;+ codex: boolean;+ pi: boolean;+ }>;memoryGetSettingsState: () => Promise<{maker: boolean;claudeCode: boolean;@@ -4706,7 +4998,9 @@ interface ElectronAPI {/** 子代理模型覆盖。null 表示不注入覆盖,仅对新建 agent 会话生效。 */subagentModelSettingsGet: () => Promise<SubagentModelSettingsState>;- subagentModelSettingsSet: (patch: SubagentModelSettingsPatch) => Promise<SubagentModelSettingsWriteResult>;+ subagentModelSettingsSet: (+ patch: SubagentModelSettingsPatch,+ ) => Promise<SubagentModelSettingsWriteResult>;subagentModelSettingsReset: () => Promise<SubagentModelSettingsWriteResult>;/** Agent 资源占用治理(命令并发上限/进程优先级/工具链限核)。 */@@ -4718,16 +5012,34 @@ interface ElectronAPI {agentResourceSettingsReset: () => Promise<AgentResourceSettingsWire>;/** Silent invalid_encrypted_content recovery setting. */- silentEncryptedRetryGet: () => Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }>;+ silentEncryptedRetryGet: () => Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }>;/** Takes effect immediately for proxy recovery. */- silentEncryptedRetrySet: (enabled: boolean) => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean; effective: 'immediate' }>;- silentEncryptedRetryReset: () => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean; effective: 'immediate' }>;+ silentEncryptedRetrySet: (+ enabled: boolean,+ ) => Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }>;+ silentEncryptedRetryReset: () => Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }>;/** Claude Code 自动上下文压缩触发百分比。仅对新建会话生效 */compactionGetPct: () => Promise<number>;compactionGetState: () => Promise<{ pct: number; isCustomized: boolean; defaultPct: number }>;/** 写入后返回 main 端 clamp 后的最终百分比 */- compactionSetPct: (pct: number) => Promise<{ pct: number; isCustomized: boolean; defaultPct: number }>;+ compactionSetPct: (+ pct: number,+ ) => Promise<{ pct: number; isCustomized: boolean; defaultPct: number }>;compactionResetPct: () => Promise<{ pct: number; isCustomized: boolean; defaultPct: number }>;/** LSP Beta 开关 — 控制 mcp providers 是否注入 lsp_* 工具 (默认 false) */@@ -4736,16 +5048,40 @@ interface ElectronAPI {lspModeSet: (enabled: boolean) => Promise<{ effective: 'next-session' }>;/** 聊天嵌入开关 — 控制 chat-history-embedder 是否对新消息入队嵌入到本地向量库 */- chatEmbeddingGet: () => Promise<{ enabled: boolean; isCustomized?: boolean; defaultEnabled?: boolean }>;+ chatEmbeddingGet: () => Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }>;/** 立即生效; 第一次开启时 main 会在 embedding_meta 表写入 cutoff 时间戳 */- chatEmbeddingSet: (enabled: boolean) => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }>;- chatEmbeddingReset: () => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }>;+ chatEmbeddingSet: (+ enabled: boolean,+ ) => Promise<{ enabled: boolean; isCustomized: boolean; defaultEnabled: boolean }>;+ chatEmbeddingReset: () => Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ }>;/** Git 安全保存点开关 — 控制 agent turn 后是否自动创建 XDT savepoint commit */- gitSafetyGet: () => Promise<{ autoSnapshotEnabled: boolean; isCustomized: boolean; defaultAutoSnapshotEnabled: boolean }>;+ gitSafetyGet: () => Promise<{+ autoSnapshotEnabled: boolean;+ isCustomized: boolean;+ defaultAutoSnapshotEnabled: boolean;+ }>;/** 立即生效; Codex rewind 入口跟随此开关显示 */- gitSafetySet: (enabled: boolean) => Promise<{ autoSnapshotEnabled: boolean; isCustomized: boolean; defaultAutoSnapshotEnabled: boolean }>;- gitSafetyReset: () => Promise<{ autoSnapshotEnabled: boolean; isCustomized: boolean; defaultAutoSnapshotEnabled: boolean }>;+ gitSafetySet: (+ enabled: boolean,+ ) => Promise<{+ autoSnapshotEnabled: boolean;+ isCustomized: boolean;+ defaultAutoSnapshotEnabled: boolean;+ }>;+ gitSafetyReset: () => Promise<{+ autoSnapshotEnabled: boolean;+ isCustomized: boolean;+ defaultAutoSnapshotEnabled: boolean;+ }>;/*** 智能通讯录(maker-contacts)— 设置页管理 UI 数据通道。@@ -4863,9 +5199,7 @@ interface ElectronAPI {* fresh 一到即整体接管。**非权威**:里面没有本次查询的健康状况,它的空列表也不构成* 「查证过的空」(详见 main/github-issue/myIssuesSnapshotStore.ts)。*/- getMyIssuesSnapshot: () => Promise<- import('../shared/myIssues').MyIssuesSnapshot | null- >;+ getMyIssuesSnapshot: () => Promise<import('../shared/myIssues').MyIssuesSnapshot | null>;listMyIssues: (options?: { force?: boolean }) => Promise<| ({ success: true } & import('../shared/myIssues').MyIssuesResult)| {@@ -4891,10 +5225,7 @@ interface ElectronAPI {* 错误码: SESSION_NOT_FOUND / MESSAGE_NOT_FOUND / NOT_USER_MESSAGE /* NO_PRIOR_ASSISTANT / SESSION_RUNNING / NO_LIVE_QUERY*/- rewindPreview: (- sessionId: string,- clientId: string,- ) => Promise<RewindFilesResultPayload>;+ rewindPreview: (sessionId: string, clientId: string) => Promise<RewindFilesResultPayload>;/*** 真执行 rewind: SDK 文件回滚 + 关 query + 设 pendingRewindTo + DB 软删 messages。* 三件套 (resume + resumeSessionAt + forkSession) 重启在用户下一次 send 时由@@ -4905,9 +5236,7 @@ interface ElectronAPI {clientId: string,opts?: { requireLatestUser?: boolean; stopIfRunning?: boolean },) => Promise<import('@/lib/ccAgent.types').Session>;- forkStripEncrypted: (- sourceSessionId: string,- ) => Promise<import('@/lib/ccAgent.types').Session>;+ forkStripEncrypted: (sourceSessionId: string) => Promise<import('@/lib/ccAgent.types').Session>;/*** fork: 把 source session 在 messageClientId 处 fork 成新 session。* fork 点支持 user 消息(复制提问之前内容)与 assistant 消息(复制含该回复@@ -4983,13 +5312,9 @@ interface ElectronAPI {import('@cindy/maker-shared/device-link-contract').MobileCodexRateLimitsResult>;/** Cindy AI /models 下发的 XD 原生报价。 */- getModelPricing: () => Promise<- import('../shared/regionalMoney').ModelPricingCatalog | null- >;+ getModelPricing: () => Promise<import('../shared/regionalMoney').ModelPricingCatalog | null>;onModelPricingChanged: (- cb: (- pricing: import('../shared/regionalMoney').ModelPricingCatalog | null,- ) => void,+ cb: (pricing: import('../shared/regionalMoney').ModelPricingCatalog | null) => void,) => () => void;/** 非 XD Provider 的 Catalog 参考价与用户覆盖。 */getReferenceModelPricing: () => Promise<@@ -4999,14 +5324,17 @@ interface ElectronAPI {cb: (pricing: import('../shared/regionalMoney').ModelPricingCatalog) => void,) => () => void;/** 用量历史聚合 (首页仪表盘)。wire 形态与 main/usage/usageHistory.ts 的 UsageHistoryPayload 同形。 */- getHistory: (- opts?: { days?: number; forceRefresh?: boolean },- ) => Promise<import('../main/usage/usageHistory').UsageHistoryPayload>;- onTodaySpendChanged: (cb: (p: {- day: string;- money: import('../shared/regionalMoney').RegionalMoney;- costUsd?: number;- }) => void) => () => void;+ getHistory: (opts?: {+ days?: number;+ forceRefresh?: boolean;+ }) => Promise<import('../main/usage/usageHistory').UsageHistoryPayload>;+ onTodaySpendChanged: (+ cb: (p: {+ day: string;+ money: import('../shared/regionalMoney').RegionalMoney;+ costUsd?: number;+ }) => void,+ ) => () => void;onTodayTokensChanged: (cb: (p: CodexUsageSnapshot) => void) => () => void;onClaudeAccountChanged: (cb: (p: {@@ -5047,13 +5375,15 @@ interface ElectronAPI {/** xAI(SuperGrok bridge)限流快照推送;字段与 main usageBroadcaster XaiRateLimitSnapshot 对齐。* null = main 主动清空(xAI 登出 / 换账号,clearXaiRateLimitSnapshot)。 */onXaiRateLimitChanged: (- cb: (p: {- limitRequests?: number;- remainingRequests?: number;- limitTokens?: number;- remainingTokens?: number;- updatedAt: number;- } | null) => void,+ cb: (+ p: {+ limitRequests?: number;+ remainingRequests?: number;+ limitTokens?: number;+ remainingTokens?: number;+ updatedAt: number;+ } | null,+ ) => void,) => () => void;};@@ -5065,7 +5395,12 @@ interface ElectronAPI {) => Promise<{ items: CrossAgentMigrationItem[] }>;convert: (items: CrossAgentMigrationItem[],- ) => Promise<{ total: number; successCount: number; skippedCount: number; failedCount: number }>;+ ) => Promise<{+ total: number;+ successCount: number;+ skippedCount: number;+ failedCount: number;+ }>;onStep: (cb: (ev: CrossAgentStepEvent) => void) => () => void;};@@ -5091,7 +5426,11 @@ interface ElectronAPI {runNow: (id: string) => Promise<{ runId: string }>;/** script 任务能力选择器:各能力的运行时可用性(依赖意识的装入/唤醒态)。 */scriptCapabilityStatus: () => Promise<{- statuses: Array<{ capability: string; state: 'ok' | 'ghost-missing' | 'ghost-asleep'; ghostName?: string }>;+ statuses: Array<{+ capability: string;+ state: 'ok' | 'ghost-missing' | 'ghost-asleep';+ ghostName?: string;+ }>;}>;/** 表单「测试运行」:立即执行一次前置检查脚本,返回判定 / exit code / 输出 / 耗时。 */testPreRunHook: (params: {@@ -5126,26 +5465,29 @@ interface ElectronAPI {/** 绑定会话任务:workingDir 空时 main 按会话 meta.workDir 解析落盘/自测目录。 */targetSessionId?: string;currentCommand?: string;- }) => Promise<{- ok: true;- command: string;- filePath: string;- content: string;- test: {- status: 'passed' | 'skipped' | 'failed' | 'timed_out' | 'aborted';- decision: 'run' | 'skip' | 'block';- exitCode: number | null;- durationMs: number;- stdout: string;- stderr: string;- stdoutTruncated: boolean;- stderrTruncated: boolean;- timedOut: boolean;- aborted: boolean;- spawnError?: string;- error?: string;- };- } | UtilityTextFailure>;+ }) => Promise<+ | {+ ok: true;+ command: string;+ filePath: string;+ content: string;+ test: {+ status: 'passed' | 'skipped' | 'failed' | 'timed_out' | 'aborted';+ decision: 'run' | 'skip' | 'block';+ exitCode: number | null;+ durationMs: number;+ stdout: string;+ stderr: string;+ stdoutTruncated: boolean;+ stderrTruncated: boolean;+ timedOut: boolean;+ aborted: boolean;+ spawnError?: string;+ error?: string;+ };+ }+ | UtilityTextFailure+ >;listRuns: (id: string, limit?: number) => Promise<unknown[]>;/** { runs, inflightRunIds } —— 形态见 features/scheduler/lib/scheduleSidebarIndexRuns。 */listSidebarIndexRuns: () => Promise<unknown>;@@ -5157,15 +5499,26 @@ interface ElectronAPI {markRunRead: (runId: string) => Promise<void>;markAllRunsRead: () => Promise<number>;markScheduleRunsRead: (scheduleId: string) => Promise<number>;- onEvent: (cb: (ev: unknown) => void) => () => void;+ onEvent: (+ cb: (+ ev: unknown,+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,+ ) => void,+ ) => () => void;};projectAutomation: {reconcile: (params: { workingDir: string }) => Promise<ProjectAutomationReconcileResult>;listConsents: () => Promise<ProjectAutomationConsent[]>;revokeConsent: (workingDir: string) => Promise<{ deleted: number }>;- upsertSchedule: (params: { workingDir: string; config: unknown }) => Promise<ProjectAutomationReconcileResult>;- removeSchedule: (params: { workingDir: string; id: string }) => Promise<ProjectAutomationReconcileResult>;+ upsertSchedule: (params: {+ workingDir: string;+ config: unknown;+ }) => Promise<ProjectAutomationReconcileResult>;+ removeSchedule: (params: {+ workingDir: string;+ id: string;+ }) => Promise<ProjectAutomationReconcileResult>;onEvent: (cb: (ev: ProjectAutomationEvent) => void) => () => void;};@@ -5188,7 +5541,9 @@ interface ElectronAPI {android: {status: () => Promise<AndroidStatusSummary>;getConfig: () => Promise<AndroidAutomationConfigState>;- setDefaultDevice: (defaultDeviceSerial: string | null) => Promise<AndroidAutomationConfigState>;+ setDefaultDevice: (+ defaultDeviceSerial: string | null,+ ) => Promise<AndroidAutomationConfigState>;setAdbPath: (adbPathOverride: string | null) => Promise<AndroidAutomationConfigState>;prepareAdb: () => Promise<AndroidAdbPreparationState>;};@@ -5210,9 +5565,7 @@ interface ElectronAPI {) => () => void;checkUpdate: () => Promise<ComputerDriverUpdateCheck>;updateDriver: (opts?: { joinOnly?: boolean }) => Promise<ComputerDriverInstallResult>;- onUpdateProgress: (- callback: (progress: ComputerDriverUpdateProgress) => void,- ) => () => void;+ onUpdateProgress: (callback: (progress: ComputerDriverUpdateProgress) => void) => () => void;};};}@@ -5330,9 +5683,7 @@ interface SkillhubSkill {}type SkillhubSourceStatus =- | { state: 'ok'; count: number }- | { state: 'missing' }- | { state: 'error'; message: string };+ { state: 'ok'; count: number } | { state: 'missing' } | { state: 'error'; message: string };interface SkillhubSourceReport {kind: SkillhubKind;@@ -5419,11 +5770,7 @@ interface SkillUsageSummary {trend: SkillUsageTrendPoint[];}-type SkillUsageEvidenceBucket =- | 'tool_failed'- | 'command_failed'- | 'repeated_calls'- | 'recent';+type SkillUsageEvidenceBucket = 'tool_failed' | 'command_failed' | 'repeated_calls' | 'recent';interface SkillUsageEvidenceIndex {id: string;@@ -5561,14 +5908,24 @@ type SkillhubPublishProgressEvent =name: string;version: string;status: string;- gates?: Array<{ name: string; label?: Record<string, string>; status: string; issues?: unknown[] }>;+ gates?: Array<{+ name: string;+ label?: Record<string, string>;+ status: string;+ issues?: unknown[];+ }>;}| {phase: 'scan-result';name: string;version: string;status: string;- gates?: Array<{ name: string; label?: Record<string, string>; status: string; issues?: unknown[] }>;+ gates?: Array<{+ name: string;+ label?: Record<string, string>;+ status: string;+ issues?: unknown[];+ }>;}| { phase: 'failed'; name?: string; errorCode: SkillhubPublishErrorCode; message: string };diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.tsindex e7be2af657..1c0843350f 100644--- a/apps/desktop/src/shared/agentInputQueue.ts+++ b/apps/desktop/src/shared/agentInputQueue.ts@@ -134,6 +134,11 @@ export interface AgentInputCreateOpts {resumeSessionId?: string;}+/** Optional optimistic-input epoch fence sent by a device-link controller. */+export interface AgentInputClearBoundaryOpts {+ expectedClearBoundaryMs?: number | null;+}+/*** 一次自动续跑(中断自愈)的展示信息,main 与 renderer 共用。*@@ -155,6 +160,14 @@ export interface AutoResumeInfo {export interface AgentInputQueuedMessage {clientId: string;text: string;+ /**+ * Host-owned receipt for the first acceptance boundary. The controlled+ * Desktop writes this value when it accepts an item; controller-provided+ * values are never trusted. It is deliberately omitted from projections,+ * but retained in crash snapshots so clear-boundary recovery can compare two+ * timestamps from the same host rather than a controller wall clock.+ */+ hostAcceptedAtMs?: number;/*** Main 在首次入队时从原始 text 冻结的合成指令意图。Ghost rewrite、队列编辑* 与 dispatch 前的其它正文变换都不得改写它;执行端用它判断 Continue 的@@ -258,9 +271,30 @@ export type AgentInputRecovery =| { kind: 'active-turn'; item: AgentInputQueuedMessage }| null;+/**+ * Normalize the persisted/device-link clear token used by optimistic input+ * preconditions. `null` is a known "never cleared" boundary; `undefined`+ * means the payload did not contain a usable token.+ */+export function normalizeAgentInputClearBoundaryMs(value: unknown): number | null | undefined {+ if (value === null) return null;+ if (typeof value === 'number') {+ return Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined;+ }+ if (typeof value !== 'string' || value.length === 0) return undefined;+ const parsed = new Date(value).getTime();+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;+}+export interface AgentInputProjection {sessionId: string;pendingQueue: AgentInputQueuedMessage[];+ /**+ * 被控端最近一次 `/clear` 的权威毫秒 token。只在会话至少 clear 过一次时出现;+ * 控制端必须在应用其它 projection 字段、尤其是触发 outbox pump 之前先处理它。+ * 老被控端可能缺省,消费方需继续兼容 sessions snapshot/patch 收敛。+ */+ clearBoundaryMs?: number | null;/*** Continue 已离开 pendingQueue、但仍占有 coordinator dispatch/turn 边界时* 的 clientId。renderer 用它区分「用户取消排队 Continue」与「Continue 正在@@ -342,8 +376,8 @@ export function sanitizeQueuedMessageForPersistence(}const record = reference as Record<string, unknown>;if (- record.kind !== 'message'- || (!Object.hasOwn(record, 'text') && !Object.hasOwn(record, 'truncated'))+ record.kind !== 'message' ||+ (!Object.hasOwn(record, 'text') && !Object.hasOwn(record, 'truncated'))) {return reference;}@@ -530,7 +564,8 @@ export function updateQueuedMessageContent(return merged;}-const SESSION_REF_LINK_RE = /(?:cindy|xdt-maker):\/\/session\/([A-Za-z0-9%~_-]+)(?:\?([A-Za-z0-9%&=~._-]*))?/g;+const SESSION_REF_LINK_RE =+ /(?:cindy|xdt-maker):\/\/session\/([A-Za-z0-9%~_-]+)(?:\?([A-Za-z0-9%&=~._-]*))?/g;/** Rebuild structured references from visible text while retaining device hints. */export function reconcileSessionRefsForText(@@ -722,7 +757,21 @@ const HAS_WORD_CHAR = /[\p{L}\p{N}]/u;* 括号刻意不在此列:`(见 @a/b.ts)` 里的 `)` 判成边界才切得干净,而真的带括号的* 文件名会在精确匹配那一步就命中。*/-const REF_CONTINUATION_CHARS = new Set(['.', '/', '\\', '-', '_', '~', '+', '=', '#', '@', '%', '&', '$']);+const REF_CONTINUATION_CHARS = new Set([+ '.',+ '/',+ '\\',+ '-',+ '_',+ '~',+ '+',+ '=',+ '#',+ '@',+ '%',+ '&',+ '$',+]);/*** ref 是纯 ASCII 而紧随其后的是非 ASCII 字母时,认边界。@@ -758,11 +807,7 @@ function splitTrailingAfterRef(ref: string, refs: ReadonlySet<string>): string |// `.` 只在它是 token **最后一个字符**时算边界:`@a/b.ts.`(英文句末)要拆,// 而 `@foo` + `.bar` 这种「更长的真实路径」不能被拆坏(review)。const trailingPeriod = next === '.' && candidate.length + 1 === ref.length;- if (- !isRefBoundary(next) &&- !isScriptChangeBoundary(candidate, next) &&- !trailingPeriod- ) {+ if (!isRefBoundary(next) && !isScriptChangeBoundary(candidate, next) && !trailingPeriod) {continue;}if (matched === null || candidate.length > matched.length) matched = candidate;diff --git a/apps/desktop/src/shared/dataOwnerPush.ts b/apps/desktop/src/shared/dataOwnerPush.tsnew file mode 100644index 0000000000..0d72c71645--- /dev/null+++ b/apps/desktop/src/shared/dataOwnerPush.ts@@ -0,0 +1,23 @@+/**+ * Ownership metadata attached to live main → renderer messages.+ *+ * The payload itself stays backwards compatible; this stamp is only an+ * ingress fence. `ownerGeneration` advances whenever main commits a new app+ * session, so a late message from an earlier account/session cannot be+ * applied to a newly mounted renderer slice with the same session id.+ */+export interface DataOwnerPushStamp {+ readonly dataOwnerId: string | null;+ readonly ownerGeneration: number;+}++export function isDataOwnerPushStamp(value: unknown): value is DataOwnerPushStamp {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const candidate = value as { dataOwnerId?: unknown; ownerGeneration?: unknown };+ return (+ (candidate.dataOwnerId === null || typeof candidate.dataOwnerId === 'string') &&+ typeof candidate.ownerGeneration === 'number' &&+ Number.isInteger(candidate.ownerGeneration) &&+ candidate.ownerGeneration >= 0+ );+}diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex bfe542166b..188499f666 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -876,13 +876,23 @@ export class DeviceLinkClient {}/** 被控端:广播转发 push 帧(fire-and-forget;失败由上层缓冲策略兜底) */- sendPush(dst: string, channel: string, payload: unknown): void {+ sendPush(+ dst: string,+ channel: string,+ payload: unknown,+ ownerStamp?: import('./protocol.js').PushOwnerStamp,+ ): void {if (this.status !== 'online') return;+ const pushPayload = {+ channel,+ payload,+ ...(ownerStamp ? { ownerStamp } : {}),+ };if (channel === DEVICE_LINK_TRANSPORT_ACK_CHANNEL) {- this.sendEnvelope({ v: PROTOCOL_VERSION, kind: 'push', dst, payload: { channel, payload } });+ this.sendEnvelope({ v: PROTOCOL_VERSION, kind: 'push', dst, payload: pushPayload });return;}- this.sendPeerEnvelope({ v: PROTOCOL_VERSION, kind: 'push', dst, payload: { channel, payload } });+ this.sendPeerEnvelope({ v: PROTOCOL_VERSION, kind: 'push', dst, payload: pushPayload });}/**diff --git a/packages/device-link/src/protocol.ts b/packages/device-link/src/protocol.tsindex 328f5414d8..5c7ec9e5c4 100644--- a/packages/device-link/src/protocol.ts+++ b/packages/device-link/src/protocol.ts@@ -173,9 +173,16 @@ export type InvokeResultPayload =};/** 被控端 → 控制端:广播转发(MAKER_PUSH.* / local-db 推送) */+export interface PushOwnerStamp {+ dataOwnerId: string | null;+ ownerGeneration: number;+}+export interface PushPayload {channel: string;payload: unknown;+ /** Optional for compatibility with older controlled desktops. */+ ownerStamp?: PushOwnerStamp;}// ─── REST 管理面(GET /api/device-link/devices)────────────────────────────────