Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): negotiate history projection before invoking legacy hosts
DavidShen36bd8a21e6a0
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.tsindex 8882266de2..ea14741f91 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts@@ -14,6 +14,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import {DeviceLinkClient,DeviceLinkError,+ DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1,DL_SUBSCRIBE_CHANNEL,INVOKE_TIMEOUT_OVERRIDES_MS,PROTOCOL_VERSION,@@ -234,6 +235,15 @@ afterEach(() => {});describe('[1] link-accept 发送失败的有限重试', () => {+ it('declares history projection support in the host accept, including for legacy controllers', () => {+ const client = mkClient();+ __testing.setActiveClient(client as never);+ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-1', undefined);+ expect(client.sendLinkAccept).toHaveBeenCalledWith('ctrl-a', 'open-1', expect.objectContaining({+ capabilities: expect.arrayContaining([DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1]),+ }));+ });+it('背压首发失败 → 不提交订阅;500ms 重试成功后才提交', () => {const sendLinkAccept = vi.fn().mockImplementationOnce(() => {throw backpressure();diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 4a7de252fc..7124b8de0f 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -43,6 +43,7 @@ import {CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,+ DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1,byteLength,DeviceLinkError,parseFsWatchTopic,@@ -2275,6 +2276,7 @@ function handleLinkOpen(client.sendLinkAccept(src, requestId, {appVersion: app.getVersion(),allowlistHash: computeAllowlistHash(),+ capabilities: [DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1],});} catch (err) {// 背压等瞬时失败:短退避重试(见 LINK_ACCEPT_RETRY_DELAYS_MS 注释),diff --git a/apps/mobile/src/__tests__/historyViewCapability.test.ts b/apps/mobile/src/__tests__/historyViewCapability.test.tsnew file mode 100644index 0000000000..4d46d77869--- /dev/null+++ b/apps/mobile/src/__tests__/historyViewCapability.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it, vi } from 'vitest';+import { DeviceLinkError, DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1, type LinkAcceptPayload } from '@cindy/device-link';+import { HistoryViewController, isHistoryViewUnavailable, projectHistoryView } from '@cindy/maker-shared/message-window';+import { invokeWithHistoryViewCapability } from '../device-link/historyViewCapability';+import { createMobileMakerTransport, type RemoteInvoke } from '../device-link/mobileMakerTransport';+import type { RemoteMessage } from '../session/types';++const message: RemoteMessage = { id: 'm', clientId: 'm', sessionId: 's', role: 'assistant',+ content: 'saved answer', createdAt: '2026-09-10T00:00:00Z', toolUseId: null, agentMeta: null };+const page = { version: 1 as const, items: projectHistoryView([message], false), hasMore: false, nextCursor: null };+const accepted = (capabilities?: string[]): LinkAcceptPayload => ({ appVersion: 'test', allowlistHash: 'test', capabilities });++describe('history capability negotiation', () => {+ it.each([undefined, [], ['unrelated-capability']])('falls back on old hosts with capabilities %j and still loads older messages', async (capabilities) => {+ const open = vi.fn(async () => accepted(capabilities));+ const wire = vi.fn<RemoteInvoke>(async (_device, channel) => {+ if (channel === 'local-db:messages:list') return [message] as never;+ throw new Error('unsupported channel reached old host');+ });+ const maker = createMobileMakerTransport({ deviceId: 'd',+ invoke: <T,>(device: string, channel: string, args?: unknown[]) =>+ invokeWithHistoryViewCapability(channel, open, () => wire(device, channel, args) as Promise<T>),+ });+ const view = new HistoryViewController<RemoteMessage>({+ page: before => maker.readHistoryView('s', before),+ details: (ref, after) => maker.readWorkDetails('s', ref, after),+ expanded: refs => maker.setHistoryExpanded('s', refs),+ });+ await view.refresh();+ expect(isHistoryViewUnavailable(view.getSnapshot().error)).toBe(true);+ expect(view.getSnapshot()).toMatchObject({ ready: false, loading: false });+ expect(wire).not.toHaveBeenCalled();+ expect(await maker.listMessages('s', { limit: 20 })).toEqual([message]);+ expect(await maker.listMessages('s', { limit: 20, before: 'older' })).toEqual([message]);+ expect(open).toHaveBeenCalledTimes(1);+ await expect(maker.setHistoryExpanded('s', [])).rejects.toThrow('CHANNEL_NOT_ALLOWED');+ view.setNetworkAvailable(false);+ view.setActive(false);+ });++ it.each(['local-db:messages:view', 'local-db:messages:work-details', 'local-db:messages:view-intent'])(+ 'waits for the host handshake before sending %s', async (channel) => {+ let resolve!: (value: LinkAcceptPayload) => void;+ const open = vi.fn(() => new Promise<LinkAcceptPayload>(done => { resolve = done; }));+ const wire = vi.fn(async () => page);+ const pending = invokeWithHistoryViewCapability(channel, open, wire);+ expect(wire).not.toHaveBeenCalled();+ resolve(accepted([DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1]));+ expect(await pending).toBe(page);+ expect(wire).toHaveBeenCalledTimes(1);+ },+ );++ it('retires cached projection on downgrade, preserves it on transient failure, and recovers on upgrade', async () => {+ const open = vi.fn(async () => accepted([DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1]));+ const wire = vi.fn(async () => page);+ const view = new HistoryViewController<RemoteMessage>({+ page: () => invokeWithHistoryViewCapability('local-db:messages:view', open, wire),+ details: async () => ({ version: 1, messages: [], hasMore: false, nextCursor: null }),+ expanded: async () => {},+ });+ await view.refresh();+ expect(view.getSnapshot().ready).toBe(true);+ const offline = new DeviceLinkError('NOT_CONNECTED', 'offline');+ open.mockRejectedValueOnce(offline);+ await view.refresh();+ expect(view.getSnapshot()).toMatchObject({ ready: true, error: offline });+ expect(isHistoryViewUnavailable(view.getSnapshot().error)).toBe(false);+ open.mockResolvedValueOnce(accepted());+ await view.refresh();+ expect(view.getSnapshot()).toMatchObject({ ready: false, items: [] });+ expect(isHistoryViewUnavailable(view.getSnapshot().error)).toBe(true);+ await view.refresh();+ expect(view.getSnapshot()).toMatchObject({ ready: true, error: null });+ expect(wire).toHaveBeenCalledTimes(2);+ view.setNetworkAvailable(false);+ view.setActive(false);+ });+});diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 9561da9ee8..fd5a27eeea 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -2,6 +2,7 @@ import Constants from 'expo-constants';import { isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';import { findRemoteHistoryView } from '@/session/remoteHistoryView';import { createBackgroundConnection } from './backgroundConnection';+import { invokeWithHistoryViewCapability } from './historyViewCapability';import { createRecoveryDiagnostics, settleMeasuredSnapshot, type RecoveryPhase } from './recoveryDiagnostics';import { confirmTrackedSubscription, SubscriptionAcknowledgements } from './subscriptionAcknowledgements';import { AppState, Platform } from 'react-native';@@ -1315,8 +1316,23 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {opts?.preSend?.();};preSend();- return sendInvokeWithAccessHandling<T>(requireClient(clientRef.current), deviceId, channel, args, { preSend });- }, []);+ const client = requireClient(clientRef.current);+ return invokeWithHistoryViewCapability(+ channel,+ async () => {+ // Reuse the existing peer-scoped handshake cache and its invalidation.+ // A late accept from an obsolete link must not declare a downgrade.+ const tracked = sendOpenLinkOnce(client, deviceId);+ const accepted = await tracked.request;+ if (clientRef.current !== client || openLinkInFlightRef.current.get(deviceId) !== tracked) {+ throw new DeviceLinkError('NOT_CONNECTED', 'history link was superseded');+ }+ preSend();+ return accepted;+ },+ () => sendInvokeWithAccessHandling<T>(client, deviceId, channel, args, { preSend }),+ );+ }, [sendOpenLinkOnce]);const subscribe = useCallback(async (owner: string, deviceId: string, topics: string[]) => {// `owner` is the stable id of the mounted consumer (e.g. `session:<id>`). Tracking isdiff --git a/apps/mobile/src/device-link/historyViewCapability.ts b/apps/mobile/src/device-link/historyViewCapability.tsnew file mode 100644index 0000000000..ec4e0e62fa--- /dev/null+++ b/apps/mobile/src/device-link/historyViewCapability.ts@@ -0,0 +1,24 @@+import { DeviceLinkError, DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1, type LinkAcceptPayload } from '@cindy/device-link';++const HISTORY_VIEW_CHANNELS = new Set([+ 'local-db:messages:view',+ 'local-db:messages:work-details',+ 'local-db:messages:view-intent',+]);++/** Negotiate before sending projection requests; legacy reads and reachability stay independent. */+export async function invokeWithHistoryViewCapability<T>(+ channel: string,+ openLink: () => Promise<LinkAcceptPayload>,+ invoke: () => Promise<T>,+): Promise<T> {+ if (HISTORY_VIEW_CHANNELS.has(channel)) {+ const accepted = await openLink();+ if (!accepted.capabilities?.includes(DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1)) {+ // Use the existing unavailable path to retire memory/disk projections and+ // read the raw message window. Do not turn connection failures into fallback.+ throw new DeviceLinkError('CHANNEL_NOT_ALLOWED', '[CHANNEL_NOT_ALLOWED] History view is unavailable');+ }+ }+ return invoke();+}diff --git a/packages/device-link/src/transport.ts b/packages/device-link/src/transport.tsindex ab09396d83..ad94716ecd 100644--- a/packages/device-link/src/transport.ts+++ b/packages/device-link/src/transport.ts@@ -31,6 +31,9 @@ export const DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM = 'reliable-link-confi* list/created/maker:event. Around reads retain full detail; old peers stay unchanged. */export const DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1 = 'compact-message-history-v1';+/** Desktop declares support for the structured history projection channels. */+export const DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1 = 'history-view-v1';+/** transport ACK 使用普通 push 承载,且 ACK 本身永不再包 transport。 */export const DEVICE_LINK_TRANSPORT_ACK_CHANNEL = '__cindy/device-link/transport-ack';