Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 将历史过滤登记绑定到当前控制连接
Dash9d5d9704714f
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.tsindex 79dd8558a1..9a45ca967c 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts@@ -45,6 +45,7 @@ vi.mock('../settings-store', () => ({import { __testing, runInvoke, wireInboundDispatch } from '../dispatch';import { __testing as registry } from '../invoke-registry';import { setRemoteBotSessionLookup } from '../remoteBotSessionBoundary';+import { getDeviceLinkInvokeContext } from '../invoke-context';import * as subscriptions from '../subscriptions';/** 最小 mock client:只实现被测路径用到的两个发送方法。 */@@ -121,14 +122,68 @@ describe('negotiated mobile tool projection', () => {});describe('history detail interest', () => {+ it.each(['local-db:messages:view', 'local-db:messages:view-intent'])('binds %s before asynchronous authorization', async (channel) => {+ let finish!: () => void;+ const pending = new Promise<void>((resolve) => { finish = resolve; });+ setRemoteBotSessionLookup(async () => { await pending; return 'ordinary'; });+ subscriptions.subscribe('ctrl', ['session:s1']);+ subscriptions.prepareHistoryView('ctrl', 's1')!.update('work');+ registry.register(channel, () => {+ const view = getDeviceLinkInvokeContext()?.historyView;+ if (channel.endsWith(':view')) view?.update('stale');+ else view?.setExpanded(['new']);+ return {};+ });+ const request = runInvoke('ctrl', { channel, args: ['s1'] });+ subscriptions.clearHistoryViews('ctrl');+ const current = subscriptions.prepareHistoryView('ctrl', 's1')!;+ current.update('new');+ finish();+ expect(await request).toMatchObject({ ok: true });+ expect(subscriptions.projectsHistoryDetails('ctrl', 's1')).toBe(true);+ current.setExpanded(['new']);+ expect(subscriptions.projectsHistoryDetails('ctrl', 's1')).toBe(false);+ });+ it('does not clear working history when link acceptance fails', () => {+ const client = mkClient();+ subscriptions.subscribe('ctrl', ['session:s1']);+ subscriptions.prepareHistoryView('ctrl', 's1')!.update('work');+ client.sendLinkAccept.mockImplementation(() => { throw new Error('backpressure'); });+ __testing.handleLinkOpen(client as never, 'ctrl', 'failed-open', undefined);+ expect(subscriptions.hasHistoryView('ctrl', 's1')).toBe(true);+ __testing.reset();+ });+ it.each([false, true])('restores full pushes on a replacement link (offline first=%s)', (offline) => {+ const client = mkClient();+ __testing.setActiveClient(client as never);+ for (const peer of ['changed', 'untouched']) {+ subscriptions.subscribe(peer, ['session:s1']);+ subscriptions.prepareHistoryView(peer, 's1')!.update('work');+ }+ const old = subscriptions.prepareHistoryView('changed', 's1')!;+ if (offline) subscriptions.clearController('changed');+ __testing.handleLinkOpen(client as never, 'changed', 'new-link', undefined);+ subscriptions.subscribe('changed', ['session:s1']);+ old.update('work');+ old.setExpanded(['work']);+ client.sendPush.mockClear();+ const payload = { sessionId: 's1', event: { type: 'thinking', data: { stage: 'delta', text: 'full detail' } } };+ __testing.forwardPush('maker:event', payload);+ expect(client.sendPush).toHaveBeenCalledWith('changed', 'maker:event', payload);+ expect(client.sendPush.mock.calls.some(([peer]) => peer === 'untouched')).toBe(false);+ subscriptions.prepareHistoryView('changed', 's1')!.update('work');+ client.sendPush.mockClear();+ __testing.forwardPush('maker:event', payload);+ expect(client.sendPush.mock.calls.some(([peer]) => peer === 'changed')).toBe(false);+ });it('sends full thinking only to expanded/legacy peers and coalesces folded summaries', async () => {vi.useFakeTimers();try {const client = mkClient();__testing.setActiveClient(client as never);for (const peer of ['folded', 'expanded', 'legacy']) subscriptions.subscribe(peer, ['session:s1']);- for (const peer of ['folded', 'expanded']) subscriptions.updateHistoryView(peer, 's1', 'work');- subscriptions.setHistoryExpanded('expanded', 's1', ['work']);+ for (const peer of ['folded', 'expanded']) subscriptions.prepareHistoryView(peer, 's1')!.update('work');+ subscriptions.prepareHistoryView('expanded', 's1')!.setExpanded(['work']);const push = (stage: string) => ({ sessionId: 's1', event: { type: 'thinking', data: { stage, blockId: 'b', text: 'private detail' } } });__testing.forwardPush('maker:event', push('start'));for (let n = 0; n < 100; n++) __testing.forwardPush('maker:event', push('delta'));diff --git a/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.ts b/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.tsindex 593139a7e3..af6265cbfa 100644--- a/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/historyViewPush.test.ts@@ -5,16 +5,45 @@ afterEach(() => subscriptions.__testing.reset());describe('per-controller deferred history', () => {it('separates collapsed, expanded and legacy peers and refuses late intent after unsubscribe', () => {for (const peer of ['closed', 'open', 'old']) subscriptions.subscribe(peer, ['session:s']);- for (const peer of ['closed', 'open']) subscriptions.updateHistoryView(peer, 's', 'w');- subscriptions.setHistoryExpanded('open', 's', ['w']);+ for (const peer of ['closed', 'open']) subscriptions.prepareHistoryView(peer, 's')!.update('w');+ subscriptions.prepareHistoryView('open', 's')!.setExpanded(['w']);expect(subscriptions.projectsHistoryDetails('closed', 's')).toBe(true);expect(subscriptions.projectsHistoryDetails('open', 's')).toBe(false);expect(subscriptions.projectsHistoryDetails('old', 's')).toBe(false);subscriptions.unsubscribe('closed', ['session:s']);- subscriptions.updateHistoryView('closed', 's', 'w');- subscriptions.setHistoryExpanded('closed', 's', ['w']);+ expect(subscriptions.prepareHistoryView('closed', 's')).toBeUndefined();expect(subscriptions.hasHistoryView('closed', 's')).toBe(false);});+ it.each(['disconnect', 'reopen', 'unsubscribe', 'revoke', 'clear-all'])('invalidates old reads and intents across %s, including re-subscription', (boundary) => {+ for (const peer of ['a', 'b']) subscriptions.subscribe(peer, ['sessions', 'session:s', 'session:other']);+ const old = subscriptions.prepareHistoryView('a', 's')!;+ const other = subscriptions.prepareHistoryView('b', 's')!;+ old.setExpanded(['w']);+ expect(subscriptions.hasHistoryView('a', 's')).toBe(false);+ expect(subscriptions.projectsHistoryDetails('a', 's')).toBe(false);+ old.update('w');+ old.setExpanded(['w']);+ if (boundary === 'disconnect') subscriptions.clearController('a');+ if (boundary === 'reopen') subscriptions.clearHistoryViews('a');+ if (boundary === 'unsubscribe') subscriptions.unsubscribe('a', ['session:s']);+ if (boundary === 'revoke') subscriptions.forgetKnownController('a');+ if (boundary === 'clear-all') subscriptions.clearAll();+ subscriptions.subscribe('a', ['session:s']);+ old.update('w');+ old.setExpanded(['w']);+ expect(subscriptions.hasHistoryView('a', 's')).toBe(false);+ const current = subscriptions.prepareHistoryView('a', 's')!;+ current.update('new');+ old.update('old');+ old.setExpanded(['new']);+ expect(subscriptions.projectsHistoryDetails('a', 's')).toBe(true);+ current.setExpanded(['new']);+ expect(subscriptions.projectsHistoryDetails('a', 's')).toBe(false);+ other.update('b-work');+ other.setExpanded(['b-work']);+ expect(subscriptions.hasHistoryView('b', 's')).toBe(boundary !== 'clear-all');+ expect(subscriptions.projectsHistoryDetails('b', 's')).toBe(false);+ });it('defers thinking/tool bodies but retains prose, interactions, errors and artifacts', () => {const push = (type: string, data: unknown) => ({ sessionId: 's', event: { type, data } });const names = () => 'Read';diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 0a890379c7..9ebf1d9af4 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -2249,6 +2249,7 @@ function handleLinkOpen(return;}markControllerLinkActive(client, src);+ subscriptions.clearHistoryViews(src);acceptedLinkControllers.add(src);if (knownModernController) {subscriptions.updateControllerMetadata(src, name, capabilities);@@ -3492,6 +3493,8 @@ export async function runInvoke(try {const args = payload.args ?? [];const invocationOwner = broadcastTap.captureDataOwnerBroadcastScope();+ const historyView = (payload.channel === 'local-db:messages:view' || payload.channel === 'local-db:messages:view-intent')+ && typeof args[0] === 'string' ? subscriptions.prepareHistoryView(src, args[0]) : undefined;if (hasRemoteBotSessionLookup()) await assertRemoteBotInvocationAllowed(args, payload.channel);const listingCapabilities = payload.channel === 'maker:provider:list'? invokeControllerCapabilities(payload)@@ -3503,6 +3506,7 @@ export async function runInvoke(// 平台按 server 盖章的 src 查本机 presence 登记表,不采信控制端自报的任何// 帧内字段(allowlist 只挡 channel 不挡 args,见下方 dispatchLocalInvoke 前的说明)。controllerPlatform: getControllerPlatform(src),+ historyView,},// provider:list 的首参只承载隧道能力协商,不进入本机 IPC handler。() => dispatchLocalInvoke(diff --git a/apps/desktop/src/main/device-link/invoke-context.ts b/apps/desktop/src/main/device-link/invoke-context.tsindex f22ab44f8e..6bb548c661 100644--- a/apps/desktop/src/main/device-link/invoke-context.ts+++ b/apps/desktop/src/main/device-link/invoke-context.ts@@ -31,6 +31,8 @@ export interface DeviceLinkInvokeContext {* 跳过校验或做任何安全判定。*/controllerPlatform?: string;+ /** Captured before asynchronous dispatch checks; cannot mutate a replacement subscription. */+ historyView?: ReturnType<typeof subscriptions.prepareHistoryView>;}const storage = new AsyncLocalStorage<DeviceLinkInvokeContext>();diff --git a/apps/desktop/src/main/device-link/subscriptions.ts b/apps/desktop/src/main/device-link/subscriptions.tsindex 29240038dd..199f90336e 100644--- a/apps/desktop/src/main/device-link/subscriptions.ts+++ b/apps/desktop/src/main/device-link/subscriptions.ts@@ -48,34 +48,42 @@ const rememberedTopicsByController = new Map<string, Set<StoredTopic>>();* 新控制端误判成 legacy,否则 set-model 的显式 provider null 会被当成占位。*/const rememberedCapabilitiesByController = new Map<string, Set<string>>();-const historyViewsByController = new Map<string, Map<string, { liveKey: string | null; expanded: Set<string> }>>();+const historyViewsByController = new Map<string, Map<string, { ready: boolean; liveKey: string | null; expanded: Set<string> }>>();-export function updateHistoryView(deviceId: string, sessionId: string, liveKey: string | null): void {- if (!controllerHasTopic(deviceId, `session:${sessionId}`)) return;+/** Capture this subscription before reading; only its successful result may enable filtering. */+export function prepareHistoryView(deviceId: string, sessionId: string) {+ if (!controllerHasTopic(deviceId, `session:${sessionId}`)) return undefined;const views = historyViewsByController.get(deviceId) ?? new Map();- const view = views.get(sessionId) ?? { liveKey: null, expanded: new Set<string>() };- view.liveKey = liveKey;- views.set(sessionId, view);- historyViewsByController.set(deviceId, views);-}--export function setHistoryExpanded(deviceId: string, sessionId: string, keys: readonly string[]): void {- // Do not recreate detail intent after an explicit session unsubscribe.- if (!controllerHasTopic(deviceId, `session:${sessionId}`)) return;- const views = historyViewsByController.get(deviceId) ?? new Map();- const view = views.get(sessionId) ?? { liveKey: null, expanded: new Set<string>() };- view.expanded = new Set(keys);+ const view = views.get(sessionId) ?? { ready: false, liveKey: null, expanded: new Set<string>() };views.set(sessionId, view);historyViewsByController.set(deviceId, views);+ const isCurrent = () => historyViewsByController.get(deviceId)?.get(sessionId) === view;+ return {+ update(liveKey: string | null): void {+ if (!isCurrent()) return;+ view.liveKey = liveKey;+ view.ready = true;+ },+ setExpanded(keys: readonly string[]): void {+ // Intent alone cannot opt a peer in or revive an old link/subscription.+ if (!isCurrent() || !view.ready) return;+ view.expanded = new Set(keys);+ },+ };+}++/** History opt-in belongs to one accepted link, unlike remembered routing topics. */+export function clearHistoryViews(deviceId: string): void {+ historyViewsByController.delete(deviceId);}export function hasHistoryView(deviceId: string, sessionId: string): boolean {- return historyViewsByController.get(deviceId)?.has(sessionId) === true;+ return historyViewsByController.get(deviceId)?.get(sessionId)?.ready === true;}export function projectsHistoryDetails(deviceId: string, sessionId: string): boolean {const view = historyViewsByController.get(deviceId)?.get(sessionId);- return !!view && (!view.liveKey || !view.expanded.has(view.liveKey));+ return !!view?.ready && (!view.liveKey || !view.expanded.has(view.liveKey));}/**@@ -214,6 +222,7 @@ export function unsubscribe(deviceId: string, topics: readonly string[]): void {/** 整条移除某控制端(link-close / presence-offline 兜底)。返回是否确实移除。 */export function clearController(deviceId: string): boolean {+ clearHistoryViews(deviceId);const e = registry.get(deviceId);if (!e) return false;const held = [...e.topics];@@ -224,7 +233,6 @@ export function clearController(deviceId: string): boolean {/** 显式撤销/账号边界使用:释放 active topics,并删除断线恢复状态。 */export function forgetKnownController(deviceId: string): void {- historyViewsByController.delete(deviceId);clearController(deviceId);knownControllerIds.delete(deviceId);rememberedTopicsByController.delete(deviceId);diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.tsindex 0d18953f58..0b1fd7f020 100644--- a/apps/desktop/src/main/localDb/ipc/messages.ts+++ b/apps/desktop/src/main/localDb/ipc/messages.ts@@ -45,7 +45,6 @@ import {import { importExternalCodexMessagesForSession } from '../../maker-host/codex-local-sessions';import { importExternalClaudeCodeMessagesForSession } from '../../maker-host/claude-local-sessions';import { getDeviceLinkInvokeContext, isDeviceLinkInvoke } from '../../device-link/invoke-context';-import { updateHistoryView, setHistoryExpanded } from '../../device-link/subscriptions';import { onMessageCreated as onChatMessageCreatedForEmbedding } from '../../embedders/chat-history-embedder';import { recomputePrRefsForSession, recordPrRefsForMessage } from '../../git-context/prRefsStore';import {@@ -381,20 +380,18 @@ export function registerMessageIpc(const sid = requireString(sessionId, 'sessionId');const before = (opts as { before?: unknown } | null)?.before;const page = await historyView.page(sid, before == null ? undefined : requireString(before, 'before'));- const controller = getDeviceLinkInvokeContext()?.controllerDeviceId;- if (controller && before == null) {+ if (before == null) {const live = page.items.find((item) => item.type === 'work' && item.summary.isStreaming);- updateHistoryView(controller, sid, live?.key ?? null);+ getDeviceLinkInvokeContext()?.historyView?.update(live?.key ?? null);}return page;});ipcMain.handle('local-db:messages:view-intent', (event, sessionId: unknown, refs: unknown) => {if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);- const sid = requireString(sessionId, 'sessionId');+ requireString(sessionId, 'sessionId');if (!Array.isArray(refs) || refs.length > 100) throwIpcError('INVALID_PARAMS', 'Invalid expanded work groups');const keys = refs.map((ref) => requireString(ref?.key, 'key'));- const controller = getDeviceLinkInvokeContext()?.controllerDeviceId;- if (controller) setHistoryExpanded(controller, sid, keys);+ getDeviceLinkInvokeContext()?.historyView?.setExpanded(keys);});ipcMain.handle('local-db:messages:work-details', async (event, sessionId: unknown, ref: unknown, opts: unknown) => {if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);