Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 防止伙伴快照缺失或迟到时漂移模型 (#4441)
FicoWang1956d16fd53d
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 3beb1b7e55..f77a28af29 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -1651,7 +1651,10 @@ export function ChatInput({setRemoteSwitchInFlight(false);}, [sessionId]);- // initialModel/initialEffort 缺失的瞬态(会话快照未加载)兜底:读本地草稿 lastByVendor+ // Only a new draft inherits application defaults. A missing existing-task+ // snapshot must never become an implicit model switch on the next send.+ const sessionModelLoading = Boolean(sessionId && !initialModel && !runtimeEffective?.model);+ // 新草稿的缺省模型/档位:读本地草稿 lastByVendor// (localStorage,按 agent 分槽、sanitize 恒有种子值)。默认模型/档位偏好已全量本地化,// 不再依赖服务端 UserPreferences(登录态失效/离线时模型与档位选择必须照常工作)。const localVendorDefaults =@@ -1667,7 +1670,7 @@ export function ChatInput({const composerSelection = resolveComposerModelSelection({current: {agentKind: runtimeAgentKind ?? vendorKeyToAgentKind(vendorKey) ?? 'claude-code',- model: initialModel ?? localVendorDefaults.model,+ model: initialModel ?? (sessionId ? '' : localVendorDefaults.model),providerId: initialProviderId ?? null,effort: initialEffort ?? localVendorDefaults.effort,fastMode: fastMode === true,@@ -5003,7 +5006,7 @@ export function ChatInput({const dispatchSend = useCallback(async (deliveryMode: MessageDeliveryMode = 'queue') => {if (!editor) return;- if (disabled) return;+ if (disabled || sessionModelLoading) return;// React 的 disabled 状态可能尚未完成下一帧渲染;同步读协调器兜住点击、快捷键、// 语音发送等所有入口,确保 host 已登记切换意图后才允许 maker:send。if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;@@ -5826,6 +5829,7 @@ export function ChatInput({[editor,disabled,+ sessionModelLoading,sessionId,onSend,activeModel,@@ -8075,7 +8079,7 @@ export function ChatInput({).kind === 'start';const [voiceReleaseToSendActive, setVoiceReleaseToSendActive] = useState(false);const sendButtonDisabled = Boolean(- disabled ||+ disabled || sessionModelLoading ||// 空態:当前 agent 无已连接来源 → Send 禁用(设计 Q7NYAD「send 置灰」),引导用户先去连接来源。(!makeNeedsNoModel && noConnectedSource) ||// 会话显式选中的来源已断开 → Send 禁用(trigger 同步显示「已断开」错误态说明原因)。@@ -8722,8 +8726,17 @@ export function ChatInput({{/* 伙伴的模型链在设置中统一管理,并由宿主自动 fallback。对话输入框不再暴露单次任务的模型切换,避免会话态覆盖伙伴长期配置。 */}{!hideRuntimeControls ? (- <div className={useNarrowToolbar ? 'min-w-0 shrink' : undefined}>- <ModelSelector+ <div+ data-session-model-slot={sessionId ? '' : undefined}+ // A cold session has no trustworthy label yet. Keep the same geometry before+ // and after hydration without mounting an interactive default-model control.+ className={sessionId+ ? cn('h-[30px] shrink', useUltraCompactToolbar+ ? 'w-[64px] min-w-[64px]'+ : 'w-[148px] min-w-[72px]')+ : useNarrowToolbar ? 'min-w-0 shrink' : undefined}+ >+ {!sessionModelLoading && <ModelSelector// 选中态一律是会话 / 草稿持有的 **wire model id**(sessions.model 或// lastByVendor.model)。面板行的归一化 id 只活在面板内部 —— 从这里递进去// 会让"当前选中的那一行"在合并行上错位,也会把归一化 id 顺着@@ -8884,7 +8897,7 @@ export function ChatInput({// settings/CreateWorker 不传该 prop → Radix 回退,不 morph。useMorphPopoverrestoreFocusTarget={composerSuggestionFocusTarget}- />+ />}</div>) : null}<divdiff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputModelLoading.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputModelLoading.test.tsxnew file mode 100644index 0000000000..e2e3fc71fd--- /dev/null+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputModelLoading.test.tsx@@ -0,0 +1,145 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { ComponentProps } from 'react';+import type { Editor } from '@tiptap/react';+import { ChatInput } from '../ChatInput';++const h = vi.hoisted(() => ({ t: (key: string) => key, confirm: vi.fn(), editor: null as Editor | null, listening: false, stop: vi.fn().mockResolvedValue(undefined) }));+vi.mock('react-i18next', async (original) => ({ ...await original<typeof import('react-i18next')>(), useTranslation: () => ({ t: h.t }) }));+vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => ({ confirm: h.confirm }) }));+vi.mock('../ModelSelector', async (original) => ({ ...await original<typeof import('../ModelSelector')>(), ModelSelector: ({ modelId }: { modelId: string }) => <span data-testid="model-selector">{modelId}</span> }));+vi.mock('../ExtraDirsButton', () => ({ ExtraDirsButton: () => null }));+vi.mock('../PermissionSelector', () => ({ PermissionSelector: () => <span data-testid="permission-selector" /> }));+vi.mock('../NewGoalDialog', () => ({ NewGoalDialog: () => null }));+vi.mock('../FolderPickerPopover', () => ({ FolderPickerPopover: () => null, addRecentFolder: vi.fn() }));+vi.mock('../AtMentionPanel', () => ({ AtMentionPanel: () => null }));+vi.mock('../SlashCommandPalette', () => ({ SlashCommandPalette: () => null }));+vi.mock('@/voice-input/VoiceInputPointerHintLayer', () => ({ VoiceInputPointerHintLayer: ({ children }: { children: import('react').ReactNode }) => <>{children}</> }));+vi.mock('@/voice-input/VoiceInputStatusNotice', () => ({ VoiceInputStatusNotice: () => null }));+vi.mock('@/voice-input/useVoiceInput', () => ({ useVoiceInput: (editor: Editor | null) => {+ h.editor = editor;+ return { state: h.listening ? 'listening' : 'idle', isListening: h.listening, isBusy: h.listening, draftText: '', start: vi.fn(), stop: h.stop, cancel: vi.fn() };+} }));+vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({ providers: [], loading: false }) }));+vi.mock('@/hooks/useDeviceProviders', () => ({ useDeviceProviders: () => ({ providers: [], loading: false, unsupported: false }) }));+vi.mock('@/hooks/useConnectedSource', () => ({ useConnectedSource: () => ({ hasConnectedSource: true, loading: false }) }));+vi.mock('@/hooks/useAvailableAgents', () => ({ useAvailableAgents: () => ({ agents: [], loading: false }) }));+vi.mock('@/hooks/useAgentCapabilities', async (original) => ({ ...await original<typeof import('@/hooks/useAgentCapabilities')>(), useAgentCapabilities: () => ({ capabilities: null, loading: false }) }));++vi.mock('@/state/newMakerDraft', async (original) => {+ const actual = await original<typeof import('@/state/newMakerDraft')>();+ return { ...actual, getDraft: () => {+ const draft = actual.getDraft();+ return { ...draft, lastByVendor: { ...draft.lastByVendor, codex: { ...draft.lastByVendor.codex, model: 'claude-fable-5-1' } } };+ } };+});++const noOp = () => {};+// External host services are inert; the editor, composer state, and send dispatch run unchanged.+const api: any = new Proxy({}, { get: (_obj, key) => {+ if (key === 'listSync') return () => ({ ghosts: [] });+ if (key === 'getDataSnapshot') return () => { throw new Error('test bridge unavailable'); };+ if (key === 'setGlobalShortcut') return () => Promise.resolve({ ok: true });+ if (key === 'platform') return 'darwin';+ if (key === 'then') return undefined;+ if (String(key).startsWith('on')) return () => noOp;+ return new Proxy(() => Promise.resolve(undefined), { get: (_fn, nested) => api[nested] });+} });+const attachments: ComponentProps<typeof ChatInput>['attachmentState'] = {+ attachments: [], hasAttachments: false, addFiles: vi.fn(), addClipboardImage: vi.fn(),+ rejections: [], dismissRejection: noOp, clearRejections: noOp, addFolderPath: noOp,+ pendingFoldersVersion: 0, consumePendingFolders: () => [], addFileMention: noOp,+ pendingFileMentionsVersion: 0, consumePendingFileMentions: () => [],+ removeFile: noOp, updateFile: noOp, discardFiles: noOp, clearFiles: noOp, restoreFiles: (files) => [...files],+};+beforeEach(() => { h.listening = false; h.stop.mockClear(); window.electronAPI = api; vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} }); });+afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });++const props = {+ sessionId: 'loading-test', initialWorkingDir: '/workspace', runtimeAgentKind: 'codex' as const,+ vendorKey: 'codex' as const, deviceLinkDeviceId: 'test-host', attachmentState: attachments,+ hideRuntimeControls: true, showFolderPicker: false, disableAutofocus: true,+};++it.each(['button', 'Enter', 'voice'] as const)(+ 'blocks %s while metadata is absent, retains input, and sends Astra when metadata arrives', async (entry) => {+ const onSend = vi.fn().mockResolvedValue(true);+ const view = render(<ChatInput {...props} onSend={onSend} />);+ await waitFor(() => expect(view.container.querySelector('[contenteditable]')).not.toBeNull());+ await act(async () => { h.editor!.commands.setContent('<p>Continue the task</p>'); });+ const editor = view.container.querySelector('[contenteditable]') as HTMLElement;+ const send = () => screen.getByRole('button', { name: 'newChat.sendButton.send' }) as HTMLButtonElement;+ if (entry === 'voice') {+ h.listening = true;+ view.rerender(<ChatInput {...props} onSend={onSend} />);+ }+ const trigger = async () => {+ await act(async () => {+ if (entry === 'button') fireEvent.click(send());+ else fireEvent.keyDown(editor, { key: 'Enter', code: 'Enter' });+ });+ };+ expect(screen.getByTestId('permission-selector')).toBeTruthy();+ expect(screen.queryByTestId('model-selector')).toBeNull();+ expect(send().disabled).toBe(true);+ await trigger();+ expect(onSend).not.toHaveBeenCalled();+ expect(h.editor!.getText()).toBe('Continue the task');+ view.rerender(<ChatInput {...props} onSend={onSend}+ initialModel="gpt-6-astra" initialProviderId="openai" initialEffort="medium" />);+ await waitFor(() => expect(send().disabled).toBe(false));+ await trigger();+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));+ if (entry === 'voice') expect(h.stop).toHaveBeenCalled();+ expect(onSend.mock.calls[0][0]).toBe('Continue the task');+ expect(onSend.mock.calls[0][1]).toBe('gpt-6-astra');+ expect(onSend.mock.calls[0][2]).toBe('medium');+ expect(onSend.mock.calls[0][6]).toEqual(expect.objectContaining({ providerId: 'openai' }));+ },+);++it('hides a missing existing model, recovers from the effective runtime, and preserves new-draft defaults', async () => {+ const onSend = vi.fn();+ const view = render(<ChatInput {...props} hideRuntimeControls={false} onSend={onSend} />);+ expect(screen.queryByTestId('model-selector')).toBeNull();+ view.rerender(<ChatInput {...props} hideRuntimeControls={false} onSend={onSend}+ runtimeEffective={{ agentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai', effort: 'medium', fastMode: false }} />);+ expect(screen.getByTestId('model-selector').textContent).toBe('gpt-6-astra');+ view.rerender(<ChatInput {...props} hideRuntimeControls={false} onSend={onSend} />);+ expect(screen.queryByTestId('model-selector')).toBeNull();+ expect((screen.getByRole('button', { name: 'newChat.sendButton.send' }) as HTMLButtonElement).disabled).toBe(true);+ view.rerender(<ChatInput {...props} sessionId={undefined} hideRuntimeControls={false} onSend={onSend} />);+ expect(screen.getByTestId('model-selector').textContent).toBe('claude-fable-5-1');+ await act(async () => {});+ expect(onSend).not.toHaveBeenCalled();+});++// The slot survives missing metadata; only the model control is withheld.+it.each([320, 480, 800])('preserves the model slot across hydration (width=%s)', async (width) => {+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(width);+ const narrowToolbar = width < 600;+ const onSend = vi.fn();+ const inputProps = { ...props, hideRuntimeControls: false, narrowToolbar, onSend };+ const view = render(<ChatInput {...inputProps} />);+ const slot = view.container.querySelector('[data-session-model-slot]') as HTMLElement;+ expect(slot).not.toBeNull();+ const geometry = slot.className;+ expect(slot.textContent).toBe('');+ expect(slot.querySelector('button, [tabindex]')).toBeNull();+ expect(screen.queryByTestId('model-selector')).toBeNull();+ view.rerender(<ChatInput {...inputProps} initialModel="gpt-6-astra" />);+ expect(view.container.querySelector('[data-session-model-slot]')).toBe(slot);+ expect(slot.className).toBe(geometry);+ expect(slot.contains(screen.getByTestId('model-selector'))).toBe(true);+ view.rerender(<ChatInput {...inputProps} />);+ expect(view.container.querySelector('[data-session-model-slot]')).toBe(slot);+ expect(slot.className).toBe(geometry);+ expect(slot.textContent).toBe('');+ view.rerender(<ChatInput {...inputProps} hideRuntimeControls />);+ expect(view.container.querySelector('[data-session-model-slot]')).toBeNull();+ expect(screen.getByTestId('permission-selector')).toBeTruthy();+ await act(async () => {});+ expect(onSend).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsxindex 9c08a9b3aa..5ac28bc256 100644--- a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx@@ -48,14 +48,23 @@ export function RemoteBotSessionView() {throw new Error('Conflicting remote session owner');// Origin must precede every read/write in the shared conversation view.remoteProjectsStore.pinSessionOrigin(deviceId, canonicalId);+ const isSessionReadCurrent = remoteProjectsStore.captureSessionRead(deviceId, canonicalId);const value = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:get', [canonicalId,]);if (disposed) return;- const session = value as Session | null;- if (!session || session.id !== canonicalId || session.source !== 'bot')+ // A settings change or reconnect may finish while this GET is in flight.+ // Use the newer mirror when available; never publish the late response.+ const readIsCurrent = isSessionReadCurrent();+ const currentMirror = remoteProjectsStore.getDeviceSessions(deviceId).find((row) => row.id === canonicalId);+ const session = readIsCurrent ? value as Session | null : currentMirror;+ if (!session || session.id !== canonicalId || session.source !== 'bot' ||+ session.status !== 'active' ||+ (!readIsCurrent && session.deviceLinkConnectionStatus !== 'connected'))throw new Error('Invalid remote companion session');- remoteProjectsStore.mergeDeviceSessions(deviceId, bot.deviceName, [session]);+ if (readIsCurrent) remoteProjectsStore.mergeDeviceSessions(deviceId, currentMirror?.deviceLinkDeviceName ?? bot.deviceName, [+ isSessionReadCurrent.mergeActivity(session),+ ]);setReady(resolved);setValidatedSessionId(sessionId);})().catch(() => {diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotModelSnapshot.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotModelSnapshot.test.tsxnew file mode 100644index 0000000000..5418004111--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotModelSnapshot.test.tsx@@ -0,0 +1,293 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { Session } from '@/lib/ccAgent.types';+import { remoteProjectsStore, useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';+import { refreshRemoteDeviceSessions } from '@/features/device-link/refreshRemoteSessions';+import { makerApiFor } from '@/lib/makerTransport';+import { resolveComposerModelSelection } from '@/components/new-chat/composerModelSelection';++const h = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock('react-router-dom', () => ({ useParams: () => ({ deviceId: 'snapshot-host', botId: 'writer' }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('../useRemoteBots', () => ({+ markRemoteBotRead: vi.fn(),+ useRemoteBots: () => [{ id: 'writer', deviceId: 'snapshot-host', deviceName: 'Host', name: 'Writer', sessionId: 'canonical', online: true }],+}));+// Keep the real entry, mirror, reconciliation, model projection and transport.+// The expensive transcript/editor tree is represented by its model/send consumer.+vi.mock('@/features/cc-agent/CCAgentSessionView', () => ({+ CCAgentSessionView: ({ sessionIdProp }: { sessionIdProp: string }) => {+ const session = useRemoteProjectSessions().find((row) => row.id === sessionIdProp);+ if (!session) return <div>metadata-loading</div>;+ const selection = resolveComposerModelSelection({ current: {+ agentKind: 'codex', model: session.model, providerId: session.providerId ?? null,+ effort: session.effort, fastMode: session.fastMode,+ }, effective: session.runtimeEffective, pending: session.runtimePending });+ return <button onClick={() => void makerApiFor(session.id).send(session.id, 'next turn', {+ ...selection.display, effort: selection.display.effort ?? undefined,+ workingDir: '/remote/workspace',+ })}>{selection.display.model}</button>;+ },+}));+import { RemoteBotSessionView } from '../RemoteBotSessionView';++const astra = { id: 'canonical', source: 'bot', status: 'active', agentKind: 'codex',+ model: 'gpt-6-astra', providerId: 'openai', effort: 'medium', fastMode: false,+ workingDir: '/remote/workspace', title: 'Writer', createdAt: '2026-09-14T00:00:00Z',+ updatedAt: '2026-09-14T00:00:00Z' } as Session;+const fable = { ...astra, model: 'claude-fable-5-1', providerId: 'anthropic', effort: 'high' };+function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => { resolve = done; });+ return { promise, resolve };+}+function entry(detail: Promise<Session>) {+ h.invoke.mockImplementation(async (_device, channel) => {+ if (channel === 'maker:remote-resources:get') return {+ ref: { collectionId: 'teammates', kind: 'bot', id: 'writer' },+ display: { title: 'Writer' }, links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'canonical' } }],+ };+ if (channel === 'local-db:sessions:get') return detail;+ if (channel === 'local-db:sessions:list') return [];+ return undefined;+ });+ return render(<RemoteBotSessionView />);+}+beforeEach(() => {+ remoteProjectsStore.clear();+ h.invoke.mockReset();+ window.electronAPI = { deviceLink: { invoke: h.invoke } } as unknown as Window['electronAPI'];+});+afterEach(() => { cleanup(); remoteProjectsStore.clear(); });++it('keeps Astra through reply completion and delayed ordinary-list refresh, then routes the next send to Astra', async () => {+ entry(Promise.resolve(astra));+ await screen.findByRole('button', { name: 'gpt-6-astra' });+ await act(async () => {+ remoteProjectsStore.applyPatch('snapshot-host', astra.id, { lastTurnEndedAt: Date.now() });+ for (let i = 0; i < 3; i++) await refreshRemoteDeviceSessions('snapshot-host', 'Host');+ });+ fireEvent.click(screen.getByRole('button', { name: 'gpt-6-astra' }));+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'maker:send', [+ astra.id, 'next turn', expect.objectContaining({ model: astra.model, providerId: 'openai', effort: 'medium' }),+ ]));+ expect(h.invoke.mock.calls.some((call) => call[1] === 'maker:set-model')).toBe(false);+});++it('does not roll back an explicit model switch with a late companion-entry GET', async () => {+ const detail = deferred<Session>();+ remoteProjectsStore.mergeDeviceSessions('snapshot-host', 'Host', [fable]);+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ remoteProjectsStore.applyPatch('snapshot-host', astra.id, { ...astra });+ detail.resolve(fable);+ });+ await screen.findByRole('button', { name: 'gpt-6-astra' });+ await act(async () => remoteProjectsStore.applyPatch('snapshot-host', astra.id, fable));+ fireEvent.click(screen.getByRole('button', { name: fable.model }));+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'maker:send', [+ astra.id, 'next turn', expect.objectContaining({ model: fable.model, providerId: 'anthropic', effort: 'high' }),+ ]));+});++it.each(['disconnect', 'remove', 'clear', 'delete', 'archive'] as const)(+ 'does not revive a companion from a late GET after %s', async (event) => {+ const detail = deferred<Session>();+ remoteProjectsStore.mergeDeviceSessions('snapshot-host', 'Host', [astra]);+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ if (event === 'disconnect') remoteProjectsStore.markDeviceDisconnected('snapshot-host');+ if (event === 'remove') remoteProjectsStore.removeDevice('snapshot-host');+ if (event === 'clear') remoteProjectsStore.clear();+ if (event === 'delete' || event === 'archive') remoteProjectsStore.applyPatch('snapshot-host', astra.id, { status: event === 'delete' ? 'deleted' : 'archived' });+ detail.resolve(astra);+ });+ await screen.findByText('bots.sessionLoadFailedDescription');+ expect(screen.queryByRole('button', { name: astra.model })).toBeNull();+ },+);++it('invalidates an initial detail read even if clear happens before the first shard exists', () => {+ const current = remoteProjectsStore.captureSessionRead('unloaded-host', 'unloaded-session');+ remoteProjectsStore.clear();+ expect(current()).toBe(false);+});+++it.each(['active', 'archived'] as const)('accepts the first companion detail across an unrelated %s list refresh', async (status) => {+ const detail = deferred<Session>();+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ remoteProjectsStore.nextSnapshotEpoch('snapshot-host', status);+ remoteProjectsStore.setDeviceSessions('snapshot-host', 'Host', [], status);+ detail.resolve(astra);+ });+ await screen.findByRole('button', { name: astra.model });+});++it.each([+ { deviceName: 'Host', mode: 'replace' },+ { deviceName: 'Renamed host', mode: 'replace' },+ { deviceName: 'Host', mode: 'merge' },+ { deviceName: 'Renamed host', mode: 'merge' },+] as const)('accepts authoritative detail when reconnect only restamps a cached companion: $mode / $deviceName', async ({ deviceName, mode }) => {+ remoteProjectsStore.hydrateFromCache([{ deviceId: 'snapshot-host', deviceName: 'Host', sessions: [fable] }]);+ const detail = deferred<Session>();+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ if (mode === 'merge') remoteProjectsStore.mergeDeviceSessions('snapshot-host', deviceName, []);+ else remoteProjectsStore.setDeviceSessions('snapshot-host', deviceName, []);+ detail.resolve(astra);+ });+ fireEvent.click(await screen.findByRole('button', { name: astra.model }));+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'maker:send', [+ astra.id, 'next turn', expect.objectContaining({ model: astra.model, providerId: 'openai', effort: 'medium' }),+ ]));+ expect(screen.queryByRole('button', { name: fable.model })).toBeNull();+});++it.each(['replace', 'merge'].flatMap(mode => [+ { mode, event: 'tokens', patch: { totalTokenUsage: 1200 } },+ { mode, event: 'preview', patch: { preview: 'new preview' } },+ { mode, event: 'title', patch: { title: 'generated title' } },+ { mode, event: 'sent-at', patch: { userSendAt: 1789466400000 } },+ { mode, event: 'updated-at', patch: { updatedAt: '2026-09-16T04:00:00Z' } },+ { mode, event: 'cost', patch: { totalCostUsd: 2 } },+ { mode, event: 'money', patch: { totalMoney: { amount: 2, currency: 'USD', approximate: false, kind: 'actual-cost' } } },+ { mode, event: 'completion', patch: { lastTurnEndedAt: 1789466400000 } },+ { mode, event: 'rename', patch: {} },+ { mode, event: 'combined', patch: { totalTokenUsage: 1200, lastTurnEndedAt: 1789466400000 } },+]))('keeps Astra and newer activity across reconnect plus $event ($mode)', async ({ mode, event, patch }) => {+ remoteProjectsStore.hydrateFromCache([{ deviceId: 'snapshot-host', deviceName: 'Host', sessions: [fable] }]);+ const detail = deferred<Session>();+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ if (mode === 'merge') remoteProjectsStore.mergeDeviceSessions('snapshot-host', 'Host', []);+ else remoteProjectsStore.setDeviceSessions('snapshot-host', 'Host', []);+ remoteProjectsStore.applyPatch('snapshot-host', astra.id, patch);+ if (event === 'rename' || event === 'combined') remoteProjectsStore.renameDevice('snapshot-host', 'Renamed host');+ detail.resolve(astra);+ });+ fireEvent.click(await screen.findByRole('button', { name: astra.model }));+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'maker:send', [+ astra.id, 'next turn', expect.objectContaining({ model: astra.model, providerId: 'openai' }),+ ]));+ expect(remoteProjectsStore.getDeviceSessions('snapshot-host')[0]).toMatchObject({ ...patch, model: astra.model });+ if (event === 'rename' || event === 'combined') {+ expect(remoteProjectsStore.getDeviceSessions('snapshot-host')[0]?.deviceLinkDeviceName).toBe('Renamed host');+ }+});++it('merges only activity pushed after capture, including equal-value and cleared fields', async () => {+ remoteProjectsStore.mergeDeviceSessions('snapshot-host', 'Host', [{ ...astra, totalTokenUsage: 10, totalCostUsd: 1 }]);+ const detail = deferred<Session>();+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ remoteProjectsStore.applyPatch('snapshot-host', astra.id, { totalTokenUsage: 10, lastTurnEndedAt: null });+ detail.resolve({ ...astra, totalTokenUsage: 5, totalCostUsd: 3, lastTurnEndedAt: 1789466400000 });+ });+ await screen.findByRole('button', { name: astra.model });+ expect(remoteProjectsStore.getDeviceSessions('snapshot-host')[0]).toMatchObject({+ totalTokenUsage: 10, totalCostUsd: 3, lastTurnEndedAt: null,+ });+});++it.each(['deleted', 'archived'] as const)('rejects a first detail after an unknown-session %s patch', async (status) => {+ const detail = deferred<Session>();+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ remoteProjectsStore.applyPatch('snapshot-host', astra.id, { status });+ detail.resolve(astra);+ });+ await screen.findByText('bots.sessionLoadFailedDescription');+ expect(screen.queryByRole('button', { name: astra.model })).toBeNull();+});++it.each([+ { name: 'spend', patch: { totalMoney: { amount: 2, currency: 'USD', approximate: false, kind: 'actual-cost' }, totalCostUsd: 2 } },+ { name: 'tokens', patch: { totalTokenUsage: 1200 } },+ { name: 'preview', patch: { preview: 'first preview' } },+ { name: 'title', patch: { title: 'first title' } },+ { name: 'send registration', patch: { userSendAt: 1789466400000, updatedAt: '2026-09-16T04:00:00Z' } },+ { name: 'turn completion', patch: { lastTurnEndedAt: 1789466400000 } },+ { name: 'usage and turn completion', patch: { lastTurnEndedAt: 1789466400000, totalTokenUsage: 1200 } },+])('accepts the first companion detail across activity-only $name', async ({ patch }) => {+ const detail = deferred<Session>();+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ remoteProjectsStore.applyPatch('snapshot-host', astra.id, patch);+ detail.resolve(astra);+ });+ fireEvent.click(await screen.findByRole('button', { name: astra.model }));+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'maker:send', [+ astra.id, 'next turn', expect.objectContaining({ model: astra.model, providerId: 'openai' }),+ ]));+ expect(screen.queryByText('bots.sessionLoadFailedDescription')).toBeNull();+});++it('preserves newer cumulative usage in an existing mirror instead of publishing a late GET', async () => {+ const detail = deferred<Session>();+ remoteProjectsStore.mergeDeviceSessions('snapshot-host', 'Host', [astra]);+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ remoteProjectsStore.applyPatch('snapshot-host', astra.id, { totalTokenUsage: 1200, totalCostUsd: 2, lastTurnEndedAt: 1789466400000 });+ detail.resolve(astra);+ });+ await screen.findByRole('button', { name: astra.model });+ expect(remoteProjectsStore.getDeviceSessions('snapshot-host')[0]).toMatchObject({ totalTokenUsage: 1200, totalCostUsd: 2, lastTurnEndedAt: 1789466400000 });+});++it.each([+ { model: astra.model, providerId: astra.providerId },+ { model: astra.model, providerId: astra.providerId, totalTokenUsage: 1200 },+ { model: astra.model, providerId: astra.providerId, lastTurnEndedAt: 1789466400000 },+])('rejects a stale first detail after a route push (including mixed usage) and retries with the new route: %j', async (patch) => {+ const detail = deferred<Session>();+ entry(detail.promise);+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'local-db:sessions:get', ['canonical']));+ await act(async () => {+ remoteProjectsStore.applyPatch('snapshot-host', astra.id, patch);+ detail.resolve(fable);+ });+ await screen.findByText('bots.sessionLoadFailedDescription');+ expect(remoteProjectsStore.getDeviceSessions('snapshot-host')).toEqual([]);+ h.invoke.mockImplementation(async (_device, channel) => {+ if (channel === 'maker:remote-resources:get') return {+ ref: { collectionId: 'teammates', kind: 'bot', id: 'writer' },+ display: { title: 'Writer' }, links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'canonical' } }],+ };+ if (channel === 'local-db:sessions:get') return astra;+ });+ fireEvent.click(screen.getByRole('button', { name: 'bots.retry' }));+ fireEvent.click(await screen.findByRole('button', { name: astra.model }));+ await waitFor(() => expect(h.invoke).toHaveBeenCalledWith('snapshot-host', 'maker:send', [+ astra.id, 'next turn', expect.objectContaining({ model: astra.model, providerId: 'openai' }),+ ]));+});++it('keeps a target detail valid across another session patch and another device disconnect', () => {+ const current = remoteProjectsStore.captureSessionRead('snapshot-host', 'canonical');+ remoteProjectsStore.applyPatch('snapshot-host', 'other-session', { model: fable.model });+ remoteProjectsStore.markDeviceDisconnected('other-host');+ expect(current()).toBe(true);+});++it.each(['disconnect', 'remove', 'all-disconnected'] as const)(+ 'invalidates a detail before its first shard exists on %s', (event) => {+ const current = remoteProjectsStore.captureSessionRead('snapshot-host', 'canonical');+ if (event === 'disconnect') remoteProjectsStore.markDeviceDisconnected('snapshot-host');+ if (event === 'remove') remoteProjectsStore.removeDevice('snapshot-host');+ if (event === 'all-disconnected') remoteProjectsStore.markAllDisconnected();+ expect(current()).toBe(false);+ },+);diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsxindex 2494fb5e04..22599640f3 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx@@ -31,6 +31,8 @@ vi.mock('@/features/device-link/remoteProjectsStore', () => ({pinSessionOrigin: h.pin,getSessionDeviceId: () => undefined,mergeDeviceSessions: h.merge,+ getDeviceSessions: () => [],+ captureSessionRead: () => Object.assign(() => true, { mergeActivity: <T,>(detail: T) => detail }),},}));vi.mock('@/features/cc-agent/CCAgentSessionView', () => ({@@ -56,7 +58,7 @@ beforeEach(() => {}expect(h.pin).toHaveBeenCalledWith('home', 'new-canonical');expect(args).toEqual(['new-canonical']);- return { id: 'new-canonical', source: 'bot' };+ return { id: 'new-canonical', source: 'bot', status: 'active' };});window.electronAPI = { deviceLink: { invoke: h.invoke } } as unknown as Window['electronAPI'];});diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.tsindex 3faed93c54..75defbdc6d 100644--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts@@ -98,12 +98,41 @@ const renameSubs = new Set<(deviceId: string, name: string) => void>();* 故 mark disconnected / remove / clear 都用自增(条目保留,仅随 distinct 设备数增长,可忽略)。*/const snapshotEpoch = new Map<string, number>();+// Detail reads do not share list epochs: sessions:list deliberately omits bots.+// Keep monotonic lifecycle/patch revisions only for devices and sessions opened+// through detail reads, including reads begun before the first shard exists.+const detailDeviceEpoch = new Map<string, number>();+const detailPatchEpoch = new Map<string, number>();+// Origin/connection restamps retain content identity. Authoritative snapshots+// and route/content patches produce a new identity, even when values are equal.+const sessionContentOrigins = new WeakMap<Session, Session>();+// Activity and list presentation pushes do not establish a newer model route.+const activityFields = ['totalMoney', 'totalCostUsd', 'totalTokenUsage', 'lastTurnEndedAt',+ 'preview', 'title', 'userSendAt', 'updatedAt'] as const;+const activityFieldNames: ReadonlySet<string> = new Set(activityFields);+type ActivityField = typeof activityFields[number];+// Per-field markers distinguish pushes after a GET began, even equal-value pushes.+const sessionActivityChanges = new WeakMap<Session, Partial<Record<ActivityField, object>>>();++function preserveSessionContent(previous: Session, next: Session): Session {+ sessionContentOrigins.set(next, sessionContentOrigin(previous)!);+ const changes = sessionActivityChanges.get(previous);+ if (changes) sessionActivityChanges.set(next, changes);+ return next;+}++function sessionContentOrigin(session: Session | undefined): Session | undefined {+ return session && (sessionContentOrigins.get(session) ?? session);+}function snapshotEpochKey(deviceId: string, status: RemoteSessionStatus): string {return `${deviceId}\u0000${status}`;}function invalidateDeviceSnapshotEpochs(deviceId: string): void {+ if (detailDeviceEpoch.has(deviceId)) {+ detailDeviceEpoch.set(deviceId, detailDeviceEpoch.get(deviceId)! + 1);+ }for (const status of ['active', 'archived'] as const) {const key = snapshotEpochKey(deviceId, status);snapshotEpoch.set(key, (snapshotEpoch.get(key) ?? 0) + 1);@@ -394,12 +423,13 @@ function stamp(deviceName: string,connectionStatus: DeviceLinkConnectionStatus,): Session {- return {+ const stamped: Session = {...session,deviceLinkDeviceId: deviceId,deviceLinkDeviceName: deviceName,deviceLinkConnectionStatus: connectionStatus,};+ return preserveSessionContent(session, stamped);}const actions = {@@ -583,8 +613,11 @@ const actions = {deviceName,[...rawSessions,+ // setDeviceSessions already preserves missing companions. Feeding them+ // back as incoming rows would turn a connection restamp into a snapshot....existing.sessions.filter(- (session) => session.status === status && !incomingIds.has(session.id),+ (session) =>+ session.source !== 'bot' && session.status === status && !incomingIds.has(session.id),),],status,@@ -599,6 +632,19 @@ const actions = {* 为用户尚未查看的历史记录额外取数。*/applyPatch(deviceId: string, sessionId: string, patch: Record<string, unknown>): void {+ // Even an unknown row can be deleted/archived while its first GET is in flight.+ // Usage, reply timestamps and list presentation cannot change its route+ // or lifecycle. These activity-only pushes are+ // dropped before a row exists, so they must not invalidate the only detail+ // capable of loading it. Mixed patches still invalidate; existing rows also+ // retain newer activity through the detail read's per-field merge.+ const changesDetail = Object.keys(patch).some((key) =>+ !activityFieldNames.has(key),+ );+ const detailKey = `${deviceId}\u0000${sessionId}`;+ if (changesDetail && detailPatchEpoch.has(detailKey)) {+ detailPatchEpoch.set(detailKey, detailPatchEpoch.get(detailKey)! + 1);+ }const deleted = patch.status === 'deleted';// 删除清缓存必须放在**所有早退之前**:这个会话可能不在当前(有界)分片里、甚至这台设备// 还没有分片,但它完全可能有一份上次打开时留下的消息缓存文件 —— 那时早退就等于把@@ -633,17 +679,20 @@ const actions = {const wasPinned = shard.sessions[idx]?.pinnedAt != null;const unpinned =Object.prototype.hasOwnProperty.call(patch, 'pinnedAt') && patch.pinnedAt == null;- shard.sessions = shard.sessions.map((s) =>- s.id === sessionId- ? {- ...s,- ...(patch as Partial<Session>),- deviceLinkDeviceId: shard.deviceId,- deviceLinkDeviceName: shard.deviceName,- deviceLinkConnectionStatus: shard.connectionStatus,- }- : s,- );+ shard.sessions = shard.sessions.map((session) => {+ if (session.id !== sessionId) return session;+ const next = stamp({ ...session, ...(patch as Partial<Session>) },+ shard.deviceId, shard.deviceName, shard.connectionStatus);+ if (!changesDetail) {+ preserveSessionContent(session, next);+ const changes = { ...sessionActivityChanges.get(session) };+ for (const field of activityFields) {+ if (Object.prototype.hasOwnProperty.call(patch, field)) changes[field] = {};+ }+ sessionActivityChanges.set(next, changes);+ }+ return next;+ });recompute();if (wasPinned && unpinned) requestRemoteReseed(deviceId, 'active');},@@ -656,11 +705,9 @@ const actions = {const shard = shards.get(deviceId);if (shard && shard.deviceName !== name) {shard.deviceName = name;- shard.sessions = shard.sessions.map((s) => ({- ...s,- deviceLinkDeviceName: name,- deviceLinkConnectionStatus: shard.connectionStatus,- }));+ shard.sessions = shard.sessions.map((session) =>+ stamp(session, deviceId, name, shard.connectionStatus),+ );recompute();}renameSubs.forEach((fn) => fn(deviceId, name));@@ -702,6 +749,7 @@ const actions = {/** 标记全部已缓存远程设备暂不可达,但不清空侧边栏会话快照。 */markAllDisconnected(): void {for (const [k, v] of snapshotEpoch) snapshotEpoch.set(k, v + 1);+ for (const [k, v] of detailDeviceEpoch) detailDeviceEpoch.set(k, v + 1);const bootstrapStateChanged =bootstrapLoadingDeviceIds.size > 0 ||archivedLoadingDeviceIds.size > 0 ||@@ -760,6 +808,7 @@ const actions = {// 所有设备 epoch 无条件**自增**(不 clear-to-0,见 snapshotEpoch 注释的 ABA):清空时在途// 首拉立即失效;下一轮 bootstrap 拿到更高 epoch,不会与清空前的 epoch 撞值把陈旧 snapshot 盖回。for (const [k, v] of snapshotEpoch) snapshotEpoch.set(k, v + 1);+ for (const [k, v] of detailDeviceEpoch) detailDeviceEpoch.set(k, v + 1);// 登出 / device-link stopped 是明确的生命周期边界:叠加层是本次会话期的临时// 显示态,跨过边界后不该复活(也避免长期留存用户输入的文本)。pendingTitlePreview.clear();@@ -855,6 +904,38 @@ const actions = {return status ? sessions.filter((session) => session.status === status) : sessions;},+ /** A detail read must not roll back a newer push, deletion, or device lifecycle. */+ captureSessionRead(deviceId: string, sessionId: string): (() => boolean) & { mergeActivity: (detail: Session) => Session } {+ const beforeRow = shards.get(deviceId)?.sessions.find((session) => session.id === sessionId);+ const before = sessionContentOrigin(beforeRow);+ const beforeActivity = beforeRow ? sessionActivityChanges.get(beforeRow) : undefined;+ const deviceEpoch = detailDeviceEpoch.get(deviceId) ?? 0;+ detailDeviceEpoch.set(deviceId, deviceEpoch);+ const detailKey = `${deviceId}\u0000${sessionId}`;+ const patchEpoch = detailPatchEpoch.get(detailKey) ?? 0;+ detailPatchEpoch.set(detailKey, patchEpoch);+ const isCurrent = () =>+ sessionContentOrigin(+ shards.get(deviceId)?.sessions.find((session) => session.id === sessionId),+ ) === before &&+ detailDeviceEpoch.get(deviceId) === deviceEpoch &&+ detailPatchEpoch.get(detailKey) === patchEpoch;+ return Object.assign(isCurrent, {+ mergeActivity(detail: Session): Session {+ const current = shards.get(deviceId)?.sessions.find((session) => session.id === sessionId);+ if (!current || !isCurrent()) return detail;+ const changes = sessionActivityChanges.get(current);+ const overrides: Partial<Session> = {};+ for (const field of activityFields) {+ if (changes?.[field] && changes[field] !== beforeActivity?.[field]) {+ Object.assign(overrides, { [field]: current[field] });+ }+ }+ return { ...detail, ...overrides };+ },+ });+ },+/** 该设备的指定状态桶是否已成功拿到过权威列表(权威空数组也算)。 */hasLoadedSessionStatus(deviceId: string, status: RemoteSessionStatus): boolean {return shards.get(deviceId)?.loadedStatuses.has(status) ?? false;