Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): keep cached teammates accessible and recover remote reads (#5928)
Chris Zhange0cbabf7884a
diff --git a/apps/mobile/app/resources/[collectionId]/[resourceId].tsx b/apps/mobile/app/resources/[collectionId]/[resourceId].tsxindex d3215c2345..556bf0ad7e 100644--- a/apps/mobile/app/resources/[collectionId]/[resourceId].tsx+++ b/apps/mobile/app/resources/[collectionId]/[resourceId].tsx@@ -13,7 +13,8 @@ import { Text } from '@/components/AppText';import { MainWindowActionButton, MainWindowEmptyState } from '@/components/MobilePrimitives';import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { getRemoteResource, invokeRemoteResourceAction, isMobileRemoteCollectionSupported, type RemoteResourceHostTarget } from '@/device-link/remoteResources';-import { formatRemoteError } from '@/device-link/remoteStatus';+import { createRemoteReadRecovery } from '@/device-link/remoteReadRecovery';+import { humanizeRemoteError } from '@/device-link/remoteStatus';import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome';import { remoteSessionStore } from '@/session/remoteSessionStore';import type { RemoteSession } from '@/session/types';@@ -37,7 +38,7 @@ function RemoteResourceResolverScreenContent() {const { colors } = useTheme();const { t, i18n } = useTranslation();const router = useRouter();- const { invoke, connectionEpoch, status, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();+ const { invoke, openLink, connectionEpoch, status, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();const { accountGeneration } = useAuth();const binding = `${accountGeneration}:${connectionEpoch}`;const currentBinding = useRef(binding); currentBinding.current = binding;@@ -78,6 +79,7 @@ function RemoteResourceResolverScreenContent() {const historySessionId = historyTarget?.kind === 'session' && typeof historyTarget.sessionId === 'string' ? historyTarget.sessionId : null;const [attempt, setAttempt] = useState(0);const resolveGenerationRef = useRef(0);+ const recovery = useRef<ReturnType<typeof createRemoteReadRecovery> | null>(null);const resolveConversation = useCallback(async () => {const generation = ++resolveGenerationRef.current;@@ -88,8 +90,11 @@ function RemoteResourceResolverScreenContent() {return;}try {+ if (status !== 'online') { setError(t('devices.resources.hostOffline')); return; }// Resolve the opaque resource again on every open. A desktop module may// roll its canonical Session without invalidating the permanent route.+ await openLink(deviceId);+ if (resolveGenerationRef.current !== generation || currentBinding.current !== binding) return;const response = await getRemoteResource(invoke, host, {collectionId,id: resourceId,@@ -116,6 +121,7 @@ function RemoteResourceResolverScreenContent() {if (!session || session.id !== target.sessionId || (resourceKind === 'bot' && session.source !== 'bot')) throw new Error(t('devices.resources.noConversation'));const existingOrigin = remoteSessionStore.getSessionDeviceId(session.id);if (existingOrigin && existingOrigin !== deviceId) throw new Error(t('devices.resources.noConversation'));+ recovery.current?.succeeded();setPreparation(null);remoteSessionStore.upsertDeviceSession(deviceId, deviceName, session);router.replace({@@ -131,9 +137,11 @@ function RemoteResourceResolverScreenContent() {});} catch (cause) {if (profileOpenRef.current) return true;- if (resolveGenerationRef.current === generation && currentBinding.current === binding) setError(formatRemoteError(cause));+ if (resolveGenerationRef.current === generation && currentBinding.current === binding) {+ setError(humanizeRemoteError(cause)); recovery.current?.failed(cause);+ }}- }, [binding, collectionId, deviceId, deviceName, host, i18n.language, invoke, resourceId, resourceKind, router, t]);+ }, [binding, collectionId, deviceId, deviceName, host, i18n.language, invoke, openLink, resourceId, resourceKind, router, status, t]);useFocusEffect(useCallback(() => {let disposed = false;@@ -151,16 +159,18 @@ function RemoteResourceResolverScreenContent() {if (refreshAgain) { refreshAgain = false; void load(); }else if (pending) timer = setTimeout(() => { void load(); }, 2500);};+ recovery.current = createRemoteReadRecovery(() => { void load(); },+ () => !disposed && status === 'online' && AppState.currentState === 'active');const offPush = onRemoteResourceChanged((source, payload) => {if (source === deviceId && payload.collectionId === collectionId) void load();});const offTopic = startFocusedTopicSubscription({ deviceId, owner: `resource-resolver:${resourceId}`, topic: 'sessions', subscribe, unsubscribe });const appState = AppState.addEventListener('change', state => {- if (state === 'active') void load();- else { resolveGenerationRef.current += 1; if (timer) clearTimeout(timer); }+ if (state === 'active') { recovery.current = createRemoteReadRecovery(() => { void load(); }, () => !disposed && status === 'online' && AppState.currentState === 'active'); void load(); }+ else { resolveGenerationRef.current += 1; recovery.current?.dispose(); if (timer) clearTimeout(timer); }});void load();- return () => { disposed = true; resolveGenerationRef.current += 1; if (timer) clearTimeout(timer); offPush(); offTopic(); appState.remove(); };+ return () => { disposed = true; recovery.current?.dispose(); resolveGenerationRef.current += 1; if (timer) clearTimeout(timer); offPush(); offTopic(); appState.remove(); };}, [attempt, collectionId, deviceId, onRemoteResourceChanged, resolveConversation, resourceId, status, subscribe, unsubscribe]));const retryInvitation = async () => {diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 422242e99a..e0cfef5ba0 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -998,6 +998,8 @@ function SessionScreenContent() {sessionId: string;notificationResponse?: string;resourceKind?: string;+ resourceCollectionId?: string;+ resourceId?: string;deviceId?: string;deviceName?: string;draft?: string;@@ -2559,7 +2561,7 @@ function SessionScreenContent() {setPendingPlanViewerState('half');}}, [activePendingKind, activePendingRequestId, sessionOperationLayout.composerSlot]);- const canUseComposer = sessionOperationLayout.canUseComposer && !sessionResourceCards.blocked && companionEntry.ready;+ const canUseComposer = sessionOperationLayout.canUseComposer && !sessionResourceCards.blocked && companionEntry.canCompose;const canUseRemoteSessionControls = canUseComposer&& !sessionSettingsLocked&& !remoteRealtimeControlsUnavailable;@@ -2573,7 +2575,7 @@ function SessionScreenContent() {const composerDisabledReasonKey = composerDisabledReasonI18nKey(sessionOperationLayout.composerDisabledReasonSource,);- const composerDisabledReason = !companionEntry.ready ? t('shared.syncing') : composerDisabledReasonKey+ const composerDisabledReason = !companionEntry.canCompose ? t('shared.syncing') : composerDisabledReasonKey? t(composerDisabledReasonKey): sessionOperationLayout.composerDisabledReason?? (sessionResourceCards.blocked@@ -2605,7 +2607,7 @@ function SessionScreenContent() {showSyncingShell,messageCount: historyView.snapshot.ready ? historyView.snapshot.items.length : messages.length,hasSyncedThisOpen: lastSyncedAt !== null,- remoteUnavailable: !!remoteUnavailableReason,+ remoteUnavailable: !!remoteUnavailableReason || status !== 'online' || targetAvailableForDispatch === false,});const voiceIsProcessing = voiceState === 'submitting' || voiceState === 'refining';const composerSendUnavailableReason = canUseComposer ? null : composerDisabledReason;@@ -6373,19 +6375,20 @@ function SessionScreenContent() {else if (options.draftOverride !== undefined) setComposerDraft(options.draftOverride);return;}- // 需要远端会话的命令在会话建成前必须挡住(review P1)。+ // 需要远端会话的命令在会话建成且可连接、身份已核对后执行。//// 命令走的是下方「豁免 outbox」的原路径:/context 直接向被控端取用量、/learn 直接// 打蒸馏管线。合成行此刻在被控端还不存在,执行的唯一结果是把草稿消费掉、再糊一张// 错误卡。排队也不成立——outbox 的派发动作是「enqueue 一条消息」,命令原样入队// agent 只会当普通文本忽略。所以挡住 + 明说:草稿此刻还没被乐观清空(清空在下面- // 几行),原文留在输入框,几秒后重试即可。纯本地卡不受影响(判据见+ // 几行),原文留在输入框,连接恢复且任务就绪后可重试。纯本地卡不受影响(判据见// commandNeedsRemoteSession)。if (commandNeedsRemoteSession(earlyLocalCommand, earlyDesktopCommand)- && isRemoteSessionMissing(readSessionRowNow())+ && (isRemoteSessionMissing(readSessionRowNow()) || connectionDispatchBlockedAtSend || !companionEntry.ready)) {- setError(t('session.screen.commandWaitsForSession'));+ setError(t(isRemoteSessionMissing(readSessionRowNow())+ ? 'session.screen.commandWaitsForSession' : 'session.screen.sessionNotSyncedRetry'));sendInFlightRef.current = false;setSending(false);return;@@ -6542,6 +6545,8 @@ function SessionScreenContent() {const clearedAt = currentSession.clearedAt ? Date.parse(currentSession.clearedAt) : null;record = {version: 1, accountId: ownerAtSend.accountKey, deviceId, item, createdAt: Date.now(),+ ...(readRouteParam(params.resourceKind) === 'bot' && readRouteParam(params.resourceCollectionId) && readRouteParam(params.resourceId)+ ? { resourceRef: { collectionId: readRouteParam(params.resourceCollectionId)!, kind: 'bot', id: readRouteParam(params.resourceId)! } } : {}),draftHandoff: { before: documentBeforeSend, after: documentAfterOptimisticClear },state: 'queued', uploads: [], clearBoundaryMs: clearedAt !== null && Number.isFinite(clearedAt) ? clearedAt : null,};@@ -10026,6 +10031,9 @@ function SessionScreenContent() {busyClientId={messageActionBusy?.clientId ?? null}canLoadEarlier={canLoadEarlierHistory}emptyTestID="session.messageList.empty"+ emptyMessage={companionChat && lastSyncedAt === null+ && (status !== 'online' || targetAvailableForDispatch === false)+ ? t('message.renderer.historyNotCached') : undefined}focusedItemKey={focusedMessageItemKey ?? null}focusedRequestKey={focusedMessageRequestKey}followLatestRequestKey={messageListFollowLatestRequestKey}diff --git a/apps/mobile/src/__tests__/TeammateList.test.tsx b/apps/mobile/src/__tests__/TeammateList.test.tsxindex 7487be9561..c81a3a365c 100644--- a/apps/mobile/src/__tests__/TeammateList.test.tsx+++ b/apps/mobile/src/__tests__/TeammateList.test.tsx@@ -167,3 +167,14 @@ it('mixes group chats into the list by latest activity', async () => {await act(async () => (node.querySelector('[data-testid="group.g1"]') as HTMLButtonElement).click());expect(onGroup).toHaveBeenCalledWith(group);});++it.each([false, null, true])('opens cached teammates while connection evidence is %s and the roster is unverified', async connected => {+ const select = vi.fn();+ await act(async () => root.render(el(TeammateList, { items: [item], error: null, isOnline: () => false,+ connectionState: () => connected, loading: false, refreshing: false, onRefresh: vi.fn(), onSelect: select, embedded: true })));+ const button = node.querySelector<HTMLButtonElement>('[data-testid="teammates.item.host.bot"]')!;+ expect(button.disabled).toBe(false);+ await act(async () => button.click());+ expect(select).toHaveBeenCalledExactlyOnceWith(item);+ if (connected === true) expect(button.textContent).not.toContain('devices.resources.hostOffline');+});diff --git a/apps/mobile/src/__tests__/durableOutbox.test.ts b/apps/mobile/src/__tests__/durableOutbox.test.tsindex 763f3dc813..898bf99947 100644--- a/apps/mobile/src/__tests__/durableOutbox.test.ts+++ b/apps/mobile/src/__tests__/durableOutbox.test.ts@@ -1170,3 +1170,40 @@ describe("app-owned delivery and reconciliation", () => {).toEqual(["first", "follow-up"]);});});++it('persists companion identity across restart and refuses a changed resource before starting enqueue', async () => {+ const { store, storage, deps } = await setup();+ const resourceRef = { collectionId: 'teammates', kind: 'bot', id: 'writer' };+ await store.add({ ...message(), resourceRef });+ const restarted = createDurableOutbox(storage); await restarted.activate('alice');+ expect(restarted.getSnapshot()[0].resourceRef).toEqual(resourceRef);+ const beforeEnqueue = vi.fn(async () => { throw new Error('ACCESS_REVOKED'); });+ const guarded = createDurableOutboxDelivery({ ...deps, store: restarted, beforeEnqueue, retryable: () => false });+ await guarded.run();+ expect(beforeEnqueue).toHaveBeenCalledTimes(1); expect(deps.enqueue).not.toHaveBeenCalled();+ expect(restarted.getSnapshot()[0]).toMatchObject({ state: 'failed', enqueueStarted: false, resourceRef });+ expect(restarted.getSnapshot()[0].item.clientId).toBe('id-1');+});++it('does not drop the resource gate when its persisted identity is corrupt', async () => {+ const storage = disk();+ const store = createDurableOutbox(storage); await store.activate('alice');+ await store.add(message());+ const [key, raw] = [...storage.data.entries()][0];+ storage.data.set(key, JSON.stringify({ ...JSON.parse(raw), resourceRef: null }));+ const restarted = createDurableOutbox(storage); await restarted.activate('alice');+ expect(restarted.getSnapshot()).toEqual([]);+ expect(storage.data.has(key)).toBe(true);+});++it('cancels an enqueue if its page-independent resource check spans an account or foreground change', async () => {+ const { store, deps, deactivate } = await setup(); await store.add(message());+ const check = deferred<void>();+ const beforeEnqueue = vi.fn(() => check.promise);+ const guarded = createDurableOutboxDelivery({ ...deps, beforeEnqueue });+ const run = guarded.run();+ for (let n = 0; n < 40 && !beforeEnqueue.mock.calls.length; n++) await Promise.resolve();+ expect(beforeEnqueue).toHaveBeenCalledTimes(1);+ deactivate(); check.resolve(); await run;+ expect(deps.enqueue).not.toHaveBeenCalled(); expect(store.getSnapshot()[0].enqueueStarted).toBe(false);+});diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.tsindex 6801cdb83a..6832ec7704 100644--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts@@ -12,7 +12,8 @@*/import { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { describe, expect, it } from 'vitest';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';function readSource(relativePath: string): string {return readFileSync(resolve(process.cwd(), relativePath), 'utf8').replace(/\r\n/g, '\n');@@ -453,9 +454,44 @@ describe('mobile optimistic composer while session is not ready', () => {expect(gate).toBeLessThan(clear);const branch = source.slice(gate, clear);expect(branch).toContain('isRemoteSessionMissing(readSessionRowNow())');- expect(branch).toContain("setError(t('session.screen.commandWaitsForSession'));");// 早退必须自己解掉发送锁(这一段在 try/finally 之前)。expect(branch).toContain('sendInFlightRef.current = false;');expect(branch).toContain('setSending(false);');++ // 执行实际门禁,避免把错误提示的固定语法当作行为契约。+ const screen = ts.createSourceFile(SCREEN, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ let guard: ts.IfStatement | undefined;+ const visit = (node: ts.Node) => {+ if (ts.isIfStatement(node) && node.expression.getText(screen).includes('commandNeedsRemoteSession(')) guard = node;+ ts.forEachChild(node, visit);+ };+ visit(screen);+ expect(guard).toBeDefined();+ const run = new Function('args', `+ const { missing, companionEntry, connectionDispatchBlockedAtSend, setError, setSending, sendInFlightRef, consume } = args;+ const earlyLocalCommand = {}, earlyDesktopCommand = null;+ const commandNeedsRemoteSession = () => true;+ const readSessionRowNow = () => missing ? null : { id: 'existing' };+ const isRemoteSessionMissing = row => row === null;+ const t = key => key;+ ${guard!.getText(screen)}+ consume();+ `);+ for (const [missing, ready, blocked] of [[true, true, false], [false, false, false], [false, true, true], [false, true, false]]) {+ const setError = vi.fn(), setSending = vi.fn(), consume = vi.fn();+ const sendInFlightRef = { current: true };+ run({ missing, companionEntry: { ready }, connectionDispatchBlockedAtSend: blocked,+ setError, setSending, sendInFlightRef, consume });+ if (missing || !ready || blocked) {+ expect(setError).toHaveBeenCalledExactlyOnceWith(missing+ ? 'session.screen.commandWaitsForSession' : 'session.screen.sessionNotSyncedRetry');+ expect(consume).not.toHaveBeenCalled();+ expect(sendInFlightRef.current).toBe(false);+ expect(setSending).toHaveBeenCalledExactlyOnceWith(false);+ } else {+ expect(setError).not.toHaveBeenCalled();+ expect(consume).toHaveBeenCalledOnce();+ }+ }});});diff --git a/apps/mobile/src/__tests__/outboxResourceBinding.test.ts b/apps/mobile/src/__tests__/outboxResourceBinding.test.tsnew file mode 100644index 0000000000..c63975af5d--- /dev/null+++ b/apps/mobile/src/__tests__/outboxResourceBinding.test.ts@@ -0,0 +1,35 @@+import { beforeEach, expect, it, vi } from 'vitest';+import { REMOTE_RESOURCE_GET_CHANNEL } from '@cindy/device-link';+import { validateOutboxResourceBinding } from '@/session/outboxResourceBinding';+const ref = { collectionId: 'teammates', kind: 'bot', id: 'writer' };+const resource = (stage = 'ready', sessionId = 'canonical') => ({ ref, revision: '1', display: { title: 'Writer' },+ links: [{ rel: 'conversation', target: { kind: 'session', sessionId } }],+ blocks: [{ id: 'invitation', primitive: 'status', fallbackMarkdown: '', data: { stage } }],+});+const invoke = vi.fn();+beforeEach(() => { invoke.mockReset(); invoke.mockImplementation(async (_device, channel) => channel === REMOTE_RESOURCE_GET_CHANNEL+ ? resource() : { id: 'canonical', source: 'bot', status: 'active' }); });+it('reads current resource and source-owned canonical metadata without creating or sending anything', async () => {+ await validateOutboxResourceBinding(invoke, 'mac', 'canonical', ref, 'en');+ expect(invoke.mock.calls.map(([, channel]) => channel)).toEqual([REMOTE_RESOURCE_GET_CHANNEL, 'local-db:sessions:get']);+ expect(invoke.mock.calls.every(([device]) => device === 'mac')).toBe(true);+});+it.each(['ACCESS_REVOKED', 'NOT_FOUND', 'REMOTE_DISABLED'])('propagates host rejection %s', async code => {+ invoke.mockRejectedValue(new Error(code));+ await expect(validateOutboxResourceBinding(invoke, 'mac', 'canonical', ref, 'en')).rejects.toThrow(code);+ expect(invoke).toHaveBeenCalledTimes(1);+});+it.each(['skills', 'failed'])('does not dispatch while initialization is %s', async stage => {+ invoke.mockResolvedValue(resource(stage));+ await expect(validateOutboxResourceBinding(invoke, 'mac', 'canonical', ref, 'en')).rejects.toThrow(stage === 'failed' ? 'PRECONDITION_FAILED' : 'DEVICE_LINK_BUSY');+ expect(invoke).toHaveBeenCalledTimes(1);+});+it('rejects a changed canonical target without redirecting or manufacturing another task', async () => {+ invoke.mockResolvedValue(resource('ready', 'different-canonical'));+ await expect(validateOutboxResourceBinding(invoke, 'mac', 'canonical', ref, 'en')).rejects.toThrow('PRECONDITION_FAILED');+ expect(invoke).toHaveBeenCalledTimes(1);+});+it.each([{ id: 'canonical', source: 'user', status: 'active' }, { id: 'canonical', source: 'bot', status: 'deleted' }, null])('rejects unavailable or unrelated task metadata %s', async session => {+ invoke.mockImplementation(async (_device, channel) => channel === REMOTE_RESOURCE_GET_CHANNEL ? resource() : session);+ await expect(validateOutboxResourceBinding(invoke, 'mac', 'canonical', ref, 'en')).rejects.toThrow('PRECONDITION_FAILED');+});diff --git a/apps/mobile/src/__tests__/remoteReadRecovery.test.ts b/apps/mobile/src/__tests__/remoteReadRecovery.test.tsnew file mode 100644index 0000000000..c155229024--- /dev/null+++ b/apps/mobile/src/__tests__/remoteReadRecovery.test.ts@@ -0,0 +1,31 @@+import { afterEach, expect, it, vi } from 'vitest';+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));+import { createRemoteReadRecovery } from '@/device-link/remoteReadRecovery';+afterEach(() => vi.useRealTimers());+it('backs off failed reads, coalesces events, resets after success and cancels on disposal', async () => {+ vi.useFakeTimers();+ const retry = vi.fn();+ const recovery = createRemoteReadRecovery(retry, () => true);+ recovery.failed(new Error('INVOKE_TIMEOUT'));+ recovery.failed(new Error('INVOKE_TIMEOUT'));+ await vi.advanceTimersByTimeAsync(899); expect(retry).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1); expect(retry).toHaveBeenCalledTimes(1);+ recovery.failed(new Error('DEVICE_UNRESPONSIVE'));+ await vi.advanceTimersByTimeAsync(1799); expect(retry).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1); expect(retry).toHaveBeenCalledTimes(2);+ recovery.succeeded(); recovery.failed(new Error('NOT_CONNECTED'));+ await vi.advanceTimersByTimeAsync(900); expect(retry).toHaveBeenCalledTimes(3);+ recovery.failed(new Error('NOT_CONNECTED')); recovery.dispose();+ await vi.advanceTimersByTimeAsync(60000); expect(retry).toHaveBeenCalledTimes(3);+});+it.each(['ACCESS_REVOKED', 'NOT_FOUND', 'REMOTE_DISABLED', 'CHANNEL_NOT_ALLOWED', 'PRECONDITION_FAILED', 'INTERNAL'])('does not retry permanent failure %s', async code => {+ vi.useFakeTimers(); const retry = vi.fn(); const recovery = createRemoteReadRecovery(retry, () => true);+ recovery.failed(new Error(code)); await vi.advanceTimersByTimeAsync(60000);+ expect(retry).not.toHaveBeenCalled(); recovery.dispose();+});+it('drops a timer when the account, foreground or page is no longer current', async () => {+ vi.useFakeTimers(); let current = true; const retry = vi.fn();+ const recovery = createRemoteReadRecovery(retry, () => current);+ recovery.failed(new Error('NOT_CONNECTED')); current = false;+ await vi.advanceTimersByTimeAsync(60000); expect(retry).not.toHaveBeenCalled(); recovery.dispose();+});diff --git a/apps/mobile/src/__tests__/remoteResourceInvitation.test.tsx b/apps/mobile/src/__tests__/remoteResourceInvitation.test.tsxindex 2f2455771e..7cec2f2bc2 100644--- a/apps/mobile/src/__tests__/remoteResourceInvitation.test.tsx+++ b/apps/mobile/src/__tests__/remoteResourceInvitation.test.tsx@@ -8,7 +8,7 @@ const h = vi.hoisted(() => ({params: { collectionId: 'teammates', resourceId: 'bot-1', resourceKind: 'bot', deviceId: 'mac', deviceName: 'Mac' },translation: { t: (key: string) => key, i18n: { language: 'en' } },read: vi.fn(), action: vi.fn(), upsert: vi.fn(), push: null as null | ((device: string, payload: any) => void),- link: { connectionEpoch: 1, status: 'online', invoke: vi.fn(), onRemoteResourceChanged: vi.fn(), subscribe: vi.fn(), unsubscribe: vi.fn() },+ link: { openLink: vi.fn(), connectionEpoch: 1, status: 'online', invoke: vi.fn(), onRemoteResourceChanged: vi.fn(), subscribe: vi.fn(), unsubscribe: vi.fn() },}));vi.mock('react-native', async () => {const { createElement: el } = await import('react');@@ -19,6 +19,7 @@ vi.mock('expo-router', async () => {const { useEffect } = await import('react');return { Redirect: ({ href }: { href: string }) => { useEffect(() => h.router.replace(href), [href]); return null; }, useFocusEffect: (effect: () => void | (() => void)) => useEffect(effect, [effect]), useRouter: () => h.router, useLocalSearchParams: () => h.params };});+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));vi.mock('react-i18next', () => ({ useTranslation: () => h.translation }));vi.mock('react-native-safe-area-context', async () => { const { createElement: el } = await import('react'); return { SafeAreaView: ({ children }: any) => el('div', {}, children) }; });vi.mock('@/components/AppText', () => ({ Text: 'span' }));@@ -36,7 +37,7 @@ vi.mock('@/components/MobilePrimitives', async () => {vi.mock('@/platform/chrome', () => ({ SimpleStackHeader: () => null, simpleScreenSafeAreaEdges: () => [] }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: h.generation }) }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));-vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));+vi.mock('@/device-link/remoteStatus', async () => ({ ...await vi.importActual<typeof import('@/device-link/remoteStatus')>('@/device-link/remoteStatus'), formatRemoteError: String }));vi.mock('@/device-link/focusedTopicSubscription', () => ({ startFocusedTopicSubscription: () => () => {} }));vi.mock('@/device-link/remoteResources', async (importOriginal) => ({ ...await importOriginal<typeof import('../device-link/remoteResources')>(), getRemoteResource: h.read, invokeRemoteResourceAction: h.action }));vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: { getSessionDeviceId: () => null, upsertDeviceSession: h.upsert } }));@@ -48,7 +49,7 @@ const resource = (stage: string) => ({ ref: { collectionId: 'teammates', kind: 'let container: HTMLDivElement;let root: ReturnType<typeof createRoot>;beforeEach(() => {- vi.clearAllMocks(); h.generation = 1; h.params.collectionId = 'teammates';+ vi.clearAllMocks(); h.link.openLink.mockResolvedValue(undefined); h.generation = 1; h.params.collectionId = 'teammates';h.link.onRemoteResourceChanged.mockImplementation(callback => { h.push = callback; return () => { h.push = null; }; });h.link.invoke.mockResolvedValue({ id: 'chat-1', source: 'bot' });container = document.createElement('div'); root = createRoot(container);diff --git a/apps/mobile/src/__tests__/remoteResources.test.ts b/apps/mobile/src/__tests__/remoteResources.test.tsindex 1128f88577..c75b921255 100644--- a/apps/mobile/src/__tests__/remoteResources.test.ts+++ b/apps/mobile/src/__tests__/remoteResources.test.ts@@ -115,6 +115,17 @@ describe('remote resource discovery', () => {.rejects.toThrow('temporarily offline');});+ it('commits an authoritative empty manifest even when an uncached sibling fails', async () => {+ const invoke = vi.fn(async (deviceId: string) => {+ if (deviceId === 'mac-2') throw new Error('temporarily offline');+ return { protocolVersion: 1, collections: [] };+ }) as RemoteInvoke;+ const previous = [{ id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope', targets: [targets[0]] }];+ const progress = vi.fn();+ await expect(discoverRemoteHomeCollections(invoke, targets, 'en', previous, progress)).resolves.toEqual([]);+ expect(progress).toHaveBeenLastCalledWith([]);+ });+it('treats an old host as unsupported while retaining collections from newer hosts', async () => {const invoke = vi.fn(async (deviceId: string) => {if (deviceId === 'mac-1') throw new DeviceLinkError('CHANNEL_NOT_ALLOWED', 'old desktop');diff --git a/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceList.test.tsxindex 5f60815f06..a699adeeac 100644--- a/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx+++ b/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx@@ -7,15 +7,17 @@ const h = vi.hoisted(() => ({auth: { user: { id: 'owner' }, accountGeneration: 1 }, focused: true,link: { connectionEpoch: 1, status: 'online', presenceVersion: 1, getPresenceAvailability: vi.fn(() => true as boolean | null),invoke: vi.fn(), openLink: vi.fn(), onRemoteResourceChanged: vi.fn((_listener: (deviceId: string, payload: { collectionId: string }) => void) => () => {}), subscribe: vi.fn(), unsubscribe: vi.fn() },+ app: { currentState: 'active', listener: null as null | ((state: string) => void) },translation: { t: (key: string) => key, i18n: { language: 'en' } },list: vi.fn(), cached: [] as HostedRemoteCollectionItem[], persist: vi.fn(), snapshot: vi.fn(),}));-vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) } }));+vi.mock('react-native', () => ({ AppState: { get currentState() { return h.app.currentState; }, addEventListener: (_event: string, listener: (state: string) => void) => { h.app.listener = listener; return { remove() { h.app.listener = null; } }; } } }));vi.mock('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (effect: () => void | (() => void)) => useEffect(() => h.focused ? effect() : undefined, [effect, h.focused]) }; });+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));vi.mock('react-i18next', () => ({ useTranslation: () => h.translation }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));-vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: (error: unknown) => String(error) }));+vi.mock('@/device-link/remoteStatus', async () => ({ ...await vi.importActual<typeof import('@/device-link/remoteStatus')>('@/device-link/remoteStatus'), formatRemoteError: (error: unknown) => String(error) }));vi.mock('@/device-link/focusedTopicSubscription', () => ({ startFocusedTopicSubscription: () => () => {} }));vi.mock('@/device-link/remoteResourceCache', () => ({readRemoteResourceSnapshot: h.snapshot, cacheRemoteResourceItems: h.persist,@@ -37,7 +39,7 @@ let result: ReturnType<typeof useRemoteResourceList>;function Probe({ enabled = true }: { enabled?: boolean }) { result = useRemoteResourceList('teammates', targets, enabled); return null; }async function render(enabled = true) { root ??= createRoot(document.createElement('div')); await act(async () => root!.render(createElement(Probe, { enabled }))); }beforeEach(() => {- vi.clearAllMocks(); h.auth.accountGeneration = 1; h.auth.user.id = 'owner'; h.cached = []; h.focused = true;+ vi.clearAllMocks(); h.app.currentState = 'active'; h.app.listener = null; h.auth.accountGeneration = 1; h.auth.user.id = 'owner'; h.cached = []; h.focused = true;h.link.status = 'online'; h.link.connectionEpoch = 1; h.link.getPresenceAvailability.mockReturnValue(true);h.list.mockResolvedValue({ items: [] }); h.link.openLink.mockResolvedValue(undefined);h.snapshot.mockImplementation(async () => ({ home: [], items: { teammates: h.cached }, read: {} }));@@ -178,3 +180,66 @@ it('shows disk-cached rows during the first slow network read without claiming aexpect(result.loading).toBe(false); expect(result.syncing).toBe(true);expect(result.isOnline(targets[0])).toBe(false);});++it('commits and persists a successful host before a slow sibling settles', async () => {+ let finish!: (value: unknown) => void;+ h.list.mockImplementation(async (_invoke, host) => host.deviceId === 'mac' ? { items: [item('fresh-mac')] }+ : new Promise(resolve => { finish = resolve; }));+ await render();+ expect(result.items.map(row => row.item.ref.id)).toEqual(['fresh-mac']);+ expect(result.isOnline(targets[0])).toBe(true);+ expect(result.syncing).toBe(true);+ expect(h.persist).toHaveBeenCalledWith('owner', 'teammates', result.items);+ await act(async () => finish({ items: [] }));+ expect(result.syncing).toBe(false);+});++it('keeps current-epoch evidence through a failed refresh, retries only failures, then stops on success', async () => {+ vi.useFakeTimers();+ h.list.mockResolvedValue({ items: [item('previous')] }); await render();+ h.list.mockImplementation(async (_invoke, host) => {+ if (host.deviceId === 'mac') throw new Error('INVOKE_TIMEOUT');+ return { items: [item('fresh-pc')] };+ });+ await act(async () => { void result.refresh(); });+ await act(async () => vi.advanceTimersByTimeAsync(7750));+ expect(result.isOnline(targets[0])).toBe(true);+ expect(result.items.map(row => row.item.ref.id)).toEqual(['previous', 'fresh-pc']);+ const before = h.list.mock.calls.length;+ h.list.mockResolvedValue({ items: [item('recovered')] });+ await act(async () => vi.advanceTimersByTimeAsync(900));+ expect(h.list.mock.calls.slice(before).map(([, host]) => host.deviceId)).toEqual(['mac']);+ expect(result.items.map(row => row.item.ref.id)).toEqual(['recovered', 'fresh-pc']);+ await act(async () => vi.advanceTimersByTimeAsync(60000));+ expect(h.list).toHaveBeenCalledTimes(before + 1);+});++it('does not authorize an old epoch while a new read is pending and cancels retry when hidden', async () => {+ vi.useFakeTimers(); await render();+ h.link.connectionEpoch++;+ h.list.mockRejectedValue(new Error('INVOKE_TIMEOUT'));+ await render(); expect(result.isOnline(targets[0])).toBe(false);+ await act(async () => vi.advanceTimersByTimeAsync(7750));+ h.focused = false; await render();+ const before = h.list.mock.calls.length;+ await act(async () => vi.advanceTimersByTimeAsync(60000));+ expect(h.list).toHaveBeenCalledTimes(before);+});++it('cancels foreground retries and late replies in the background and resumes on return', async () => {+ vi.useFakeTimers();+ let finish!: (value: unknown) => void;+ h.list.mockReturnValue(new Promise(resolve => { finish = resolve; }));+ await render();+ h.app.currentState = 'background';+ await act(async () => h.app.listener!('background'));+ await act(async () => finish({ items: [item('background-late')] }));+ expect(result.items).toEqual([]);+ const before = h.list.mock.calls.length;+ await act(async () => vi.advanceTimersByTimeAsync(60000));+ expect(h.list).toHaveBeenCalledTimes(before);+ h.list.mockResolvedValue({ items: [item('foreground-fresh')] });+ h.app.currentState = 'active';+ await act(async () => h.app.listener!('active'));+ expect(result.items.map(row => row.item.ref.id)).toEqual(['foreground-fresh', 'foreground-fresh']);+});diff --git a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsxindex 0f11432a85..f7fc878a88 100644--- a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx+++ b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx@@ -5,6 +5,8 @@ import ts from 'typescript';import { act, createElement } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { commandNeedsRemoteSession, parseMobileLocalSystemCommand } from '@/session/systemCard';+import { parseMobileDesktopCommand } from '@/session/desktopSlashCommands';const h = vi.hoisted(() => ({get: vi.fn(),@@ -15,8 +17,9 @@ const h = vi.hoisted(() => ({store: { getSessionDeviceId: vi.fn(), upsertDeviceSession: vi.fn() },router: { replace: vi.fn(), setParams: vi.fn() },auth: { user: { id: 'owner' }, accountGeneration: 1 },- link: { invoke: vi.fn(), connectionEpoch: 1, status: 'online', onRemoteResourceChanged: vi.fn(() => () => {}), subscribe: vi.fn(), unsubscribe: vi.fn() },+ link: { openLink: vi.fn(), invoke: vi.fn(), connectionEpoch: 1, status: 'online', onRemoteResourceChanged: vi.fn(() => () => {}), subscribe: vi.fn(), unsubscribe: vi.fn() },}));+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: h.t, i18n: { language: h.language } }) }));vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) } }));vi.mock('expo-router', async () => {@@ -30,7 +33,7 @@ vi.mock('expo-router', async () => {});vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));-vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));+vi.mock('@/device-link/remoteStatus', async () => ({ ...await vi.importActual<typeof import('@/device-link/remoteStatus')>('@/device-link/remoteStatus'), formatRemoteError: String }));vi.mock('@/device-link/remoteResources', () => ({ getRemoteResource: h.get }));vi.mock('@/device-link/remoteResourceCache', () => ({ markRemoteResourceRead: h.markRead }));vi.mock('@/device-link/focusedTopicSubscription', () => ({ startFocusedTopicSubscription: () => () => {} }));@@ -74,8 +77,8 @@ async function render(canMarkRead = false) {// A viewport receipt is separate from loading/entering the chat.result.markReadThrough(200);}-beforeEach(() => { vi.clearAllMocks(); h.openSearch = ''; h.auth.accountGeneration = 1; h.metadataVerified = true; h.focused = true; h.language = "en"; h.resourceId = 'bot-1'; h.sessionId = 'task-1'; h.link.status = 'online'; h.link.connectionEpoch = 1; h.store.getSessionDeviceId.mockReturnValue(undefined); });-afterEach(() => { act(() => root?.unmount()); root = undefined; });+beforeEach(() => { vi.clearAllMocks(); h.link.openLink.mockResolvedValue(undefined); h.openSearch = ''; h.auth.accountGeneration = 1; h.metadataVerified = true; h.focused = true; h.language = "en"; h.resourceId = 'bot-1'; h.sessionId = 'task-1'; h.link.status = 'online'; h.link.connectionEpoch = 1; h.store.getSessionDeviceId.mockReturnValue(undefined); });+afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });describe('companion task visibility refresh', () => {it('does not acknowledge on entry and never acknowledges beyond the rendered tail', async () => {@@ -187,9 +190,11 @@ it('does not refetch the profile when history becomes readable', async () => {await render(false); await render(true);expect(h.get).toHaveBeenCalledTimes(1);});-it('keeps a cached chat unavailable on a transient lookup error and retries in place', async () => {- h.get.mockRejectedValueOnce(new Error('NOT_CONNECTED'));+it('keeps dispatch unavailable on a transient lookup error and retries in place', async () => {+ vi.useFakeTimers();+ h.get.mockRejectedValue(new Error('NOT_CONNECTED'));await render(true);+ await act(async () => vi.advanceTimersByTimeAsync(7750));expect(result.ready).toBe(false); expect(result.error).toContain('NOT_CONNECTED');h.get.mockResolvedValue({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }], display: { title: 'Teammate' } });await act(async () => result.retry());@@ -243,7 +248,7 @@ it('drops a late response when switching companions and fences a disconnected/reawait render(true); expect(result.ready).toBe(false);});-it.each([false, true])('wires entry readiness=%s to production composer, realtime controls and outbox gates', ready => {+it.each([false, true])('keeps local composing available while dispatch readiness=%s', ready => {const expressions = new Map<string, string>();const visit = (node: ts.Node) => {if (ts.isVariableDeclaration(node) && node.initializer) expressions.set(node.name.getText(screen), node.initializer.getText(screen));@@ -253,12 +258,12 @@ it.each([false, true])('wires entry readiness=%s to production composer, realtimconst names = ['canUseComposer', 'remoteRealtimeControlsUnavailable', 'outboxConnectionState'];const code = names.map(name => `const ${name} = ${expressions.get(name)};`).join('\n');const gates = new Function('ready', `- const companionEntry = { ready }, sessionOperationLayout = { canUseComposer: true }, sessionResourceCards = { blocked: false };+ const companionEntry = { ready, canCompose: true }, sessionOperationLayout = { canUseComposer: true }, sessionResourceCards = { blocked: false };const status = 'online', targetAvailableForDispatch = true, isDeviceUnresponsive = false, outboxRecoverySyncHeld = false, loading = false;${code}return { canUseComposer, remoteRealtimeControlsUnavailable, outboxConnectionState };`)(ready);- expect(gates.canUseComposer).toBe(ready);+ expect(gates.canUseComposer).toBe(true);expect(gates.remoteRealtimeControlsUnavailable).toBe(!ready);expect(gates.outboxConnectionState.autoRecoveringError).toBe(!ready);});@@ -334,3 +339,59 @@ it('still leaves failed invitation history when the host revokes the resource',expect(result.ready).toBe(false);expect(h.router.replace).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/resources/[collectionId]/[resourceId]' }));});++it('keeps local editing and durable queuing available offline, and reopens only the target on recovery', async () => {+ const { readRemoteCollectionCache, writeRemoteCollectionCache } = await import('@/device-link/remoteResourceAvailability');+ readRemoteCollectionCache('owner:1', 'teammates');+ writeRemoteCollectionCache('owner:1', 'teammates', [{ key: 'offline', host: { deviceId: 'mac', deviceName: 'My Mac' }, item: {+ ref: { collectionId: 'teammates', kind: 'bot', id: 'bot-1' }, revision: 'cached', display: { title: 'Cached teammate' },+ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }],+ } }]);+ h.link.status = 'offline'; await render();+ expect(container.textContent).toBe('Cached teammate');+ expect(result.canCompose).toBe(true); expect(result.ready).toBe(false);+ expect(h.get).not.toHaveBeenCalled(); expect(h.link.openLink).not.toHaveBeenCalled();+ h.link.status = 'online'; h.link.connectionEpoch++;+ h.get.mockResolvedValue({ display: { title: 'Recovered teammate' }, links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }] });+ await render();+ expect(h.link.openLink).toHaveBeenCalledExactlyOnceWith('mac');+ expect(result.ready).toBe(true); expect(container.textContent).toBe('Recovered teammate');+ // No mutation or automatic read receipt merely for opening and reconnecting.+ expect(h.link.invoke).not.toHaveBeenCalled(); expect(h.markRead).not.toHaveBeenCalled();+});++it.each(['ACCESS_REVOKED', 'REMOTE_DISABLED', 'NOT_FOUND'])('closes local queuing and dispatch on explicit rejection %s without retrying', async code => {+ vi.useFakeTimers(); h.get.mockRejectedValue(Object.assign(new Error(code), { code }));+ await render(); expect(result.canCompose).toBe(false); expect(result.ready).toBe(false);+ await act(async () => vi.advanceTimersByTimeAsync(60000));+ expect(h.get).toHaveBeenCalledTimes(1);+});++it.each(['/context', '/learn keep this', '/help', 'keep this message'])('preserves offline command drafts without blocking local text: %s', draft => {+ let guard: ts.IfStatement | undefined;+ const visit = (node: ts.Node) => {+ if (ts.isIfStatement(node) && node.expression.getText(screen).includes('commandNeedsRemoteSession(')) guard = node;+ ts.forEachChild(node, visit);+ };+ visit(screen);+ expect(guard).toBeDefined();+ const error = vi.fn();+ const consume = vi.fn();+ const run = new Function('args', `+ const { earlyLocalCommand, earlyDesktopCommand, commandNeedsRemoteSession, connectionDispatchBlockedAtSend,+ companionEntry, setError, consume } = args;+ const readSessionRowNow = () => ({ id: 'existing' });+ const isRemoteSessionMissing = () => false;+ const t = key => key, sendInFlightRef = { current: true }, setSending = () => {};+ ${guard!.getText(screen)}+ consume();+ `);+ for (const [ready, blocked] of [[false, false], [true, true]]) {+ error.mockClear(); consume.mockClear();+ run({ earlyLocalCommand: parseMobileLocalSystemCommand(draft), earlyDesktopCommand: parseMobileDesktopCommand(draft),+ commandNeedsRemoteSession, connectionDispatchBlockedAtSend: blocked, companionEntry: { ready }, setError: error, consume });+ const remote = draft.startsWith('/context') || draft.startsWith('/learn');+ expect(consume).toHaveBeenCalledTimes(remote ? 0 : 1);+ expect(error).toHaveBeenCalledTimes(remote ? 1 : 0);+ }+});diff --git a/apps/mobile/src/__tests__/useTeammateNavigation.test.tsx b/apps/mobile/src/__tests__/useTeammateNavigation.test.tsxindex 2fbb68e5ab..e96ea7bfa4 100644--- a/apps/mobile/src/__tests__/useTeammateNavigation.test.tsx+++ b/apps/mobile/src/__tests__/useTeammateNavigation.test.tsx@@ -6,7 +6,7 @@ import type { MobileUser } from '@/auth/AuthContext';const h = vi.hoisted(() => ({disk: new Map<string, string>(), push: vi.fn(), dismissTo: vi.fn(), dismiss: vi.fn(), reset: vi.fn(), accountGeneration: 1,user: { id: 'account', passportId: 'passport', membershipKind: 'personal', orgId: null } as MobileUser,- get: vi.fn(), set: vi.fn(), routes: [] as Array<{ name: string; params?: unknown }>,+ sessions: [] as import('@/session/types').RemoteSession[], upsert: vi.fn(), get: vi.fn(), set: vi.fn(), routes: [] as Array<{ name: string; params?: unknown }>,}));vi.mock('expo-router', () => ({ useRouter: () => ({ dismissTo: h.dismissTo, dismiss: h.dismiss }), useNavigation: () => ({ reset: h.reset, getState: () => ({ routes: h.routes, index: h.routes.length - 1 }) }) }));vi.mock('react-native', () => ({ Keyboard: { dismiss() {} } }));@@ -14,6 +14,7 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'envi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: h.user, accountGeneration: h.accountGeneration }) }));vi.mock('@/utils/useGuardedPush', () => ({ useGuardedPush: () => h.push }));vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: h.get, setItem: h.set } }));+vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: { getSessions: () => h.sessions, getSessionDeviceId: () => undefined, upsertDeviceSession: h.upsert } }));import { useTeammateNavigation } from '@/session/useTeammateNavigation';import { homeNavigationOwner } from '@/session/useHomeMode';import { readHomeNavigationPreferences, saveHomeNavigationPreferences } from '@/session/homeViewPreferenceStore';@@ -29,7 +30,7 @@ function Probe() { result = useTeammateNavigation(); return null; }async function render() { root ??= createRoot(document.createElement('div')); await act(async () => root!.render(createElement(Probe))); }let serial = 0;beforeEach(() => {- vi.clearAllMocks(); h.routes = []; h.disk.clear(); h.accountGeneration = ++serial;+ vi.clearAllMocks(); h.sessions = []; h.routes = []; h.disk.clear(); h.accountGeneration = ++serial;h.user = { id: `account-${serial}`, passportId: 'passport', membershipKind: 'personal', orgId: null } as MobileUser;h.get.mockImplementation(async (key: string) => h.disk.get(key) ?? null);h.set.mockImplementation(async (key: string, value: string) => { h.disk.set(key, value); });@@ -182,3 +183,17 @@ it('opens a known conversation directly and seeds its first-frame identity', asy} });expect(readRemoteCollectionCache(`${h.user.id}:${h.accountGeneration}`, 'teammates')[0]).toBe(linked);});++it('opens a disk-cached canonical chat without a task row, seeds presentation once, and preserves real metadata', async () => {+ const linked = { ...teammate, item: { ...teammate.item, links: [{ rel: 'conversation', target: { kind: 'session' as const, sessionId: 'canonical' } }] } };+ h.upsert.mockImplementation((_device, _name, session) => { h.sessions.push(session); });+ await render();+ await act(async () => Promise.all([result.openTeammate(linked), result.openTeammate(linked)]));+ expect(h.push).toHaveBeenCalledTimes(1);+ expect(h.upsert).toHaveBeenCalledExactlyOnceWith('mac', 'My Mac', expect.objectContaining({ id: 'canonical', source: 'bot', cacheSeeded: true, workingDir: null }));+ expect(h.push.mock.calls[0][0].pathname).toBe('/sessions/[sessionId]');+ h.sessions[0] = { ...h.sessions[0], cacheSeeded: undefined, model: 'real-model', workingDir: '/real' };+ await act(async () => result.openTeammate(linked));+ expect(h.upsert).toHaveBeenCalledTimes(1);+ expect(h.sessions[0].model).toBe('real-model');+});diff --git a/apps/mobile/src/__tests__/useTeammateRoster.test.tsx b/apps/mobile/src/__tests__/useTeammateRoster.test.tsxindex fc8464b4f8..f3e12e5461 100644--- a/apps/mobile/src/__tests__/useTeammateRoster.test.tsx+++ b/apps/mobile/src/__tests__/useTeammateRoster.test.tsx@@ -4,19 +4,21 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';const h = vi.hoisted(() => ({auth: { user: { id: 'owner' }, accountGeneration: 1 }, revoked: new Set<string>(),+ snapshot: vi.fn(),translation: { t: (key: string) => key, i18n: { language: 'en' } },link: { status: 'online', connectionEpoch: 1, presenceVersion: 1, invoke: vi.fn(), openLink: vi.fn(), readDeviceList: vi.fn() },list: { items: [] as import('@/device-link/remoteResources').HostedRemoteCollectionItem[], loading: false, refreshing: false, error: null, isOnline: vi.fn(() => true), refresh: vi.fn() },}));-vi.mock('react-native', () => ({ AppState: { addEventListener: () => ({ remove() {} }) } }));+vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) } }));vi.mock('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (effect: any) => useEffect(effect, [effect]) }; });+vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));vi.mock('react-i18next', () => ({ useTranslation: () => h.translation }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));vi.mock('@/device-link/devices', () => ({ toDeviceListItems: (devices: unknown) => devices }));vi.mock('@/device-link/revokedDevicesStore', () => ({ useRevokedDevices: () => h.revoked }));-vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));-vi.mock('@/device-link/remoteResourceCache', () => ({ cacheRemoteResourceHome: vi.fn(), readRemoteResourceSnapshot: async () => ({ home: [], items: {}, read: {} }) }));+vi.mock('@/device-link/remoteStatus', async () => ({ ...await vi.importActual<typeof import('@/device-link/remoteStatus')>('@/device-link/remoteStatus'), formatRemoteError: String }));+vi.mock('@/device-link/remoteResourceCache', () => ({ cacheRemoteResourceHome: vi.fn(), readRemoteResourceSnapshot: h.snapshot }));vi.mock('@/session/useRemoteResourceList', () => ({ useRemoteResourceList: () => h.list }));import { useTeammateRoster } from '@/session/useTeammateRoster';Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });@@ -27,10 +29,11 @@ async function render() { root ??= createRoot(document.createElement('div')); awbeforeEach(() => {vi.clearAllMocks(); h.list.items = []; h.revoked.clear(); h.link.openLink.mockResolvedValue(undefined); h.link.status = 'online'; h.link.connectionEpoch = 1; h.auth.accountGeneration = 1;h.list.isOnline.mockReturnValue(true);+ h.snapshot.mockResolvedValue({ home: [], items: {}, read: {} });h.link.readDeviceList.mockResolvedValue({ devices: ['old', 'new'].map(deviceId => ({ device: { deviceId, name: deviceId }, canOpen: true, state: 'online' })) });h.link.invoke.mockImplementation(async (deviceId) => ({ protocolVersion: 1, collections: [{ id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope', ...(deviceId === 'new' ? { actions: [{ id: 'open-create', label: 'Create' }] } : {}) }] }));});-afterEach(() => { act(() => root?.unmount()); root = undefined; });+afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });it('offers only real online hosts advertising create, including a host with an empty roster', async () => {await render();expect(result.targets.map(host => host.deviceId)).toEqual(['old', 'new']);@@ -52,6 +55,22 @@ it('drops old account discovery replies', async () => {expect(result.targets).toEqual([]); expect(result.createTargets).toEqual([]);});+it('clears prior-account create and group capabilities before the new directory answers', async () => {+ h.link.invoke.mockResolvedValue({ protocolVersion: 1, collections: [+ { id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope', actions: [{ id: 'open-create', label: 'Create' }] },+ { id: 'bot-groups', title: 'Groups', resourceKind: 'bot-group' },+ ] });+ await render();+ expect(result.createTargets).not.toEqual([]);+ expect(result.groupTargets).not.toEqual([]);+ h.auth.accountGeneration++;+ h.link.readDeviceList.mockReturnValue(new Promise(() => {}));+ await render();+ expect(result.createTargets).toEqual([]);+ expect(result.groupTargets).toEqual([]);+ expect(result.targets).toEqual([]);+});+it('does not request the manifest until the host link is established', async () => {const release: Array<() => void> = [];h.link.openLink.mockImplementation(() => new Promise<void>(resolve => release.push(resolve)));@@ -66,6 +85,8 @@ it('shows cached teammates while host discovery is pending, then removes revokedref: { collectionId: 'teammates', kind: 'bot', id: 'bot' }, revision: '1', display: { title: 'Cached' }, links: [],} }];h.link.readDeviceList.mockReturnValue(new Promise(() => {}));+ h.snapshot.mockResolvedValue({ home: [], items: { teammates: h.list.items }, read: {} });+ h.list.isOnline.mockReturnValue(false);await render();expect(result.items).toHaveLength(1); expect(result.loading).toBe(false);expect(result.authoritative).toBe(false); expect(result.isOnline(h.list.items[0].host)).toBe(false);@@ -90,3 +111,108 @@ it('exposes only computers whose manifest advertises group chats, keeping them th.link.connectionEpoch++; await render();expect(result.groupTargets).toEqual([]);});++it('publishes a discovered teammate host without waiting for an unrelated manifest', async () => {+ let finish!: (value: unknown) => void;+ h.link.invoke.mockImplementation(async device => device === 'old'+ ? { protocolVersion: 1, collections: [{ id: 'teammates', resourceKind: 'bot', title: 'Teammates', placement: 'home-scope' }] }+ : new Promise(resolve => { finish = resolve; }));+ await render();+ expect(result.targets.map(host => host.deviceId)).toEqual(['old']);+ expect(result.authoritative).toBe(false);+ await act(async () => finish({ protocolVersion: 1, collections: [] }));+ expect(result.targets.map(host => host.deviceId)).toEqual(['old']);+ expect(result.authoritative).toBe(true);+});++it('retries only failed manifests while preserving healthy capabilities and stable list targets', async () => {+ vi.useFakeTimers();+ h.link.invoke.mockImplementation(async device => {+ if (device === 'new') throw new Error('INVOKE_TIMEOUT');+ return { protocolVersion: 1, collections: [+ { id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope', actions: [{ id: 'open-create', label: 'Create' }] },+ { id: 'bot-groups', title: 'Groups', resourceKind: 'bot-group' },+ ] };+ });+ await render();+ await act(async () => vi.advanceTimersByTimeAsync(7750));+ const stableTargets = result.targets;+ expect(h.link.openLink.mock.calls.filter(([device]) => device === 'old')).toHaveLength(1);+ const before = h.link.openLink.mock.calls.length;+ h.link.invoke.mockImplementation(async device => device === 'new'+ ? { protocolVersion: 1, collections: [] }+ : { protocolVersion: 1, collections: [+ { id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope', actions: [{ id: 'open-create', label: 'Create' }] },+ { id: 'bot-groups', title: 'Groups', resourceKind: 'bot-group' },+ ] });+ await act(async () => vi.advanceTimersByTimeAsync(900));+ expect(h.link.openLink.mock.calls.slice(before)).toEqual([['new']]);+ expect(result.targets).toBe(stableTargets);+ expect(h.link.openLink.mock.calls.filter(([device]) => device === 'old')).toHaveLength(1);+ expect(result.createTargets.map(host => host.deviceId)).toEqual(['old']);+ expect(result.groupTargets.map(host => host.deviceId)).toEqual(['old']);+ const recovered = h.link.openLink.mock.calls.length;+ await act(async () => vi.advanceTimersByTimeAsync(60000));+ expect(h.link.openLink).toHaveBeenCalledTimes(recovered);+});++it('does not restore a removed capability from cached rows on a sibling retry', async () => {+ vi.useFakeTimers();+ const cached = { key: 'old:bot', host: { deviceId: 'old', deviceName: 'Old' }, item: {+ ref: { collectionId: 'teammates', kind: 'bot', id: 'bot' }, revision: '1', display: { title: 'Cached' }, links: [],+ } };+ h.snapshot.mockResolvedValue({ home: [], items: { teammates: [cached] }, read: {} });+ h.list.items = [cached];+ h.link.invoke.mockImplementation(async device => {+ if (device === 'new') throw new Error('INVOKE_TIMEOUT');+ return { protocolVersion: 1, collections: [] };+ });+ await render();+ await act(async () => vi.advanceTimersByTimeAsync(7750));+ expect(result.targets).toEqual([]); expect(result.items).toEqual([]);+ const before = h.link.openLink.mock.calls.length;+ h.link.invoke.mockResolvedValue({ protocolVersion: 1, collections: [] });+ await act(async () => vi.advanceTimersByTimeAsync(900));+ expect(h.link.openLink.mock.calls.slice(before)).toEqual([['new']]);+ expect(result.targets).toEqual([]); expect(result.items).toEqual([]);+});++it('retains in-memory teammates if the disk capability read stalls', async () => {+ vi.useFakeTimers();+ const { readRemoteCollectionCache, writeRemoteCollectionCache } = await import('@/device-link/remoteResourceAvailability');+ const cached = { key: 'old:bot', host: { deviceId: 'old', deviceName: 'Old' }, item: {+ ref: { collectionId: 'teammates', kind: 'bot', id: 'bot' }, revision: '1', display: { title: 'Cached' }, links: [],+ } };+ readRemoteCollectionCache('owner:1', 'teammates');+ writeRemoteCollectionCache('owner:1', 'teammates', [cached]);+ h.list.items = [cached];+ h.snapshot.mockReturnValue(new Promise(() => {}));+ h.link.readDeviceList.mockReturnValue(new Promise(() => {}));+ await render();+ await act(async () => vi.advanceTimersByTimeAsync(2000));+ expect(result.targets.map(host => host.deviceId)).toEqual(['old']);+ expect(result.items).toEqual([cached]);+ expect(result.loading).toBe(false);+});++it('keeps every cached roster host in the list targets while a partial home manifest catches up', async () => {+ const hosts = ['old', 'new'].map(deviceId => ({ deviceId, deviceName: deviceId }));+ const rows = hosts.map(host => ({ key: host.deviceId, host, item: {+ ref: { collectionId: 'teammates', kind: 'bot', id: host.deviceId }, revision: '1', display: { title: host.deviceId }, links: [],+ } }));+ h.snapshot.mockResolvedValue({ home: [{ id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope', targets: [hosts[0]] }],+ items: { teammates: rows }, read: {} });+ h.list.items = rows;+ let finish!: (value: unknown) => void;+ h.link.invoke.mockImplementation(async device => device === 'old'+ ? { protocolVersion: 1, collections: [{ id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope' }] }+ : new Promise(resolve => { finish = resolve; }));+ await render();+ // The real list reader may persist a successful old-host shard now. It must+ // still receive the new host as a target so it cannot prune its cached rows.+ expect(result.targets.map(host => host.deviceId)).toEqual(['old', 'new']);+ expect(result.items).toEqual(rows);+ await act(async () => finish({ protocolVersion: 1, collections: [] }));+ expect(result.targets.map(host => host.deviceId)).toEqual(['old']);+ expect(result.items).toEqual([rows[0]]);+});diff --git a/apps/mobile/src/device-link/remoteReadRecovery.ts b/apps/mobile/src/device-link/remoteReadRecovery.tsnew file mode 100644index 0000000000..bfe7c73994--- /dev/null+++ b/apps/mobile/src/device-link/remoteReadRecovery.ts@@ -0,0 +1,20 @@+import { connectionRecoverySyncRetryDelayMs, isAutoRecoveringRemoteError } from './remoteStatus';++/** Retry failed reads only while their owning page/connection is current. Never replay writes. */+export function createRemoteReadRecovery(retry: () => void, current: () => boolean) {+ let timer: ReturnType<typeof setTimeout> | undefined;+ let attempt = 0;+ let disposed = false;+ const cancel = () => { if (timer) clearTimeout(timer); timer = undefined; };+ return {+ failed(error: unknown) {+ if (disposed || !current() || timer || !isAutoRecoveringRemoteError(error)) return;+ timer = setTimeout(() => {+ timer = undefined;+ if (!disposed && current()) retry();+ }, connectionRecoverySyncRetryDelayMs(attempt++));+ },+ succeeded() { cancel(); attempt = 0; },+ dispose() { disposed = true; cancel(); },+ };+}diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.tsindex 765e5414a7..3d975660e2 100644--- a/apps/mobile/src/device-link/remoteResources.ts+++ b/apps/mobile/src/device-link/remoteResources.ts@@ -288,6 +288,7 @@ export async function discoverRemoteHomeCollections(targets: readonly RemoteResourceDiscoveryTarget[],locale?: string,previous: readonly RemoteHomeCollection[] = [],+ onProgress?: (collections: RemoteHomeCollection[]) => void,): Promise<RemoteHomeCollection[]> {const cachedManifest = (target: RemoteResourceHostTarget): RemoteResourceManifestResponse => ({protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION,@@ -301,45 +302,43 @@ export async function discoverRemoteHomeCollections(...(collection.iconName ? { icon: { name: collection.iconName, fallbackText: '' } } : {}),})),});- const settled = await Promise.allSettled(targets.map(async ({ offline, ...target }) => ({- target,- manifest: offline ? cachedManifest(target) : await loadRemoteResourceManifest(invoke, target, locale),- })));- const discovered = settled.flatMap((result, index) => {- if (result.status === 'fulfilled') {- return result.value.manifest ? [result.value] : [];+ const merge = (discovered: { target: RemoteResourceHostTarget; manifest: RemoteResourceManifestResponse | null }[]) => {+ const byId = new Map<string, RemoteHomeCollection>();+ for (const { target, manifest } of discovered) {+ for (const collection of manifest?.collections ?? []) {+ if (collection.placement !== 'home-scope' || !isMobileRemoteCollectionSupported(collection.id)) continue;+ const existing = byId.get(collection.id);+ if (existing && existing.resourceKind === collection.resourceKind) {+ existing.targets.push(target);+ continue;+ }+ if (existing) continue;+ byId.set(collection.id, {+ id: collection.id,+ title: resolveRemoteText(collection.title, locale),+ resourceKind: collection.resourceKind,+ placement: collection.placement,+ iconName: collection.icon?.name,+ targets: [target],+ });+ }}- const selected = targets[index];- if (!selected) return [];- const target = { deviceId: selected.deviceId, deviceName: selected.deviceName };- const manifest = cachedManifest(target);- return manifest.collections.length ? [{ target, manifest }] : [];- });- if (targets.length > 0 && discovered.length === 0) {+ return [...byId.values()];+ };+ const discovered = targets.map(({ offline: _offline, ...target }) => ({ target, manifest: cachedManifest(target) as RemoteResourceManifestResponse | null }));+ const settled = await Promise.allSettled(targets.map(async ({ offline, ...target }, index) => {+ const manifest = offline ? cachedManifest(target) : await loadRemoteResourceManifest(invoke, target, locale);+ discovered[index] = { target, manifest };+ onProgress?.(merge(discovered));+ return { target, manifest };+ }));+ const hasManifestReply = settled.some((result, index) => result.status === 'fulfilled'+ && result.value.manifest !== null && !targets[index].offline);+ if (targets.length > 0 && !hasManifestReply && !discovered.some(entry => entry.manifest?.collections.length)) {const failure = settled.find((result) => result.status === 'rejected');if (failure && failure.status === 'rejected') throw failure.reason;}- const byId = new Map<string, RemoteHomeCollection>();- for (const { target, manifest } of discovered) {- for (const collection of manifest?.collections ?? []) {- if (collection.placement !== 'home-scope' || !isMobileRemoteCollectionSupported(collection.id)) continue;- const existing = byId.get(collection.id);- if (existing && existing.resourceKind === collection.resourceKind) {- existing.targets.push(target);- continue;- }- if (existing) continue;- byId.set(collection.id, {- id: collection.id,- title: resolveRemoteText(collection.title, locale),- resourceKind: collection.resourceKind,- placement: collection.placement,- iconName: collection.icon?.name,- targets: [target],- });- }- }- return [...byId.values()];+ return merge(discovered);}export async function invokeRemoteResourceAction(diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex 4dae669aa2..df42287d0b 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -15,6 +15,7 @@"openForkOrigin": "Open fork source message","viewForkOrigin": "View fork source","emptyMessages": "No messages yet",+ "historyNotCached": "No history cached on this phone. Connect to the computer to sync.","syncing": "Syncing","copyLinkHint": "Tap to copy message link","sentTime": "Sent at {{time}}",diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.jsonindex d3e0217aa8..f25fc196d1 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -15,6 +15,7 @@"openForkOrigin": "分岐元メッセージを開く","viewForkOrigin": "分岐元を表示","emptyMessages": "メッセージはありません",+ "historyNotCached": "この端末に履歴がありません。コンピューターに接続すると同期します。","syncing": "同期中","copyLinkHint": "タップしてメッセージリンクをコピー","sentTime": "送信時刻 {{time}}",diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex 2d9f9c99cf..9cdaef64c0 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -15,6 +15,7 @@"openForkOrigin": "분기 원본 메시지 열기","viewForkOrigin": "분기 원본 보기","emptyMessages": "메시지가 없습니다",+ "historyNotCached": "이 휴대폰에 저장된 기록이 없습니다. 컴퓨터에 연결하면 동기화됩니다.","syncing": "동기화 중","copyLinkHint": "탭하여 메시지 링크 복사","sentTime": "보낸 시간 {{time}}",diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.jsonindex 3761007f1b..390f3e411d 100644--- a/apps/mobile/src/i18n/locales/zh-CN/message.json+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json@@ -15,6 +15,7 @@"openForkOrigin": "打开分叉来源消息","viewForkOrigin": "查看分叉来源","emptyMessages": "暂无消息",+ "historyNotCached": "历史消息尚未缓存,连接电脑后同步","syncing": "正在同步","copyLinkHint": "点按复制消息链接","sentTime": "发送时间 {{time}}",diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.jsonindex c3f5050f03..39d39abf3b 100644--- a/apps/mobile/src/i18n/locales/zh-TW/message.json+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json@@ -15,6 +15,7 @@"openForkOrigin": "開啟分叉來源訊息","viewForkOrigin": "檢視分叉來源","emptyMessages": "暫無訊息",+ "historyNotCached": "歷史訊息尚未快取,連線電腦後同步","syncing": "正在同步","copyLinkHint": "點按複製訊息連結","sentTime": "傳送時間 {{time}}",diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 947f467555..742c94ee18 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -766,6 +766,7 @@ export function MessageRenderer({busyAction,canLoadEarlier,emptyTestID,+ emptyMessage,bottomOverlayHeight,contentBottomInset,isSessionStreaming,@@ -805,6 +806,7 @@ export function MessageRenderer({/** Oldest loaded host cursor; synthetic cards must not mask successful history prepends. */loadEarlierProgressKey?: string | null;emptyTestID?: string;+ emptyMessage?: string;/** 排队消息 inline 区(InlineQueueSection),渲染在最后一条消息之后、随内容滚动。 */queueFooter?: ReactNode;scrollResetKey?: string;@@ -2822,7 +2824,7 @@ export function MessageRenderer({]}ListEmptyComponent={syncingWhileEmpty? <SyncingMessages />- : <EmptyMessages testID={emptyTestID} />}+ : <EmptyMessages testID={emptyTestID} copy={emptyMessage} />}ListHeaderComponent={loadEarlierAction.visible ? (<MessageListActionButton@@ -3276,12 +3278,12 @@ function ForkOriginMarker({ onOpenForkOrigin }: { onOpenForkOrigin?: () => void);}-function EmptyMessages({ testID }: { testID?: string }) {+function EmptyMessages({ testID, copy }: { testID?: string; copy?: string }) {const styles = useThemedStyles(makeStyles);const { t } = useTranslation();return (<View style={styles.emptyCard} testID={testID ?? 'message.empty'}>- <Text style={styles.emptyTitle}>{t('message.renderer.emptyMessages')}</Text>+ <Text style={styles.emptyTitle}>{copy ?? t('message.renderer.emptyMessages')}</Text></View>);}diff --git a/apps/mobile/src/session/MobileOutboxBridge.tsx b/apps/mobile/src/session/MobileOutboxBridge.tsxindex 6746b80037..4a8826eddf 100644--- a/apps/mobile/src/session/MobileOutboxBridge.tsx+++ b/apps/mobile/src/session/MobileOutboxBridge.tsx@@ -48,6 +48,7 @@ import {} from "./sessionReferences";import { remoteSessionStore } from "./remoteSessionStore";import { cacheOutboxHistory } from "./outboxHistoryCache";+import { validateOutboxResourceBinding } from './outboxResourceBinding';import { findRemoteHistoryView } from "./remoteHistoryViews";import {isDurableOutboxHandedOff,@@ -303,8 +304,15 @@ export function MobileOutboxBridge() {}: attachment;},- enqueue: (r) =>- maker(r).input.enqueue(+ beforeEnqueue: async (r) => {+ if (r.resourceRef) {+ await latest.current.link.openLink(r.deviceId);+ guard();+ await validateOutboxResourceBinding(invokeOwned(r), r.deviceId, r.item.sessionId, r.resourceRef, i18n.language);+ guard();+ }+ },+ enqueue: (r) => maker(r).input.enqueue(r.item.sessionId,r.prepared!,{diff --git a/apps/mobile/src/session/TeammateList.tsx b/apps/mobile/src/session/TeammateList.tsxindex 97c24cdfc6..a36d1a4145 100644--- a/apps/mobile/src/session/TeammateList.tsx+++ b/apps/mobile/src/session/TeammateList.tsx@@ -176,8 +176,8 @@ export function TeammateList({ items, loading, refreshing, error, isOnline, connaccessibilityLabel={[title, ambiguous ? row.host.deviceName : '', connection, prefix, generating ? workingCopy : summary, time,unread ? t('devices.companions.unread') : ''].filter(Boolean).join(', ')}avatar={<>- <View style={!online ? { opacity: OFFLINE_AVATAR_OPACITY } : undefined}>- <RemoteCompanionAvatar avatar={display.avatar} deviceId={row.host.deviceId} name={title} online={online} size={COMPANION_ROW_AVATAR_SIZE} framed />+ <View style={connected === false ? { opacity: OFFLINE_AVATAR_OPACITY } : undefined}>+ <RemoteCompanionAvatar avatar={display.avatar} deviceId={row.host.deviceId} name={title} online={connected === true} size={COMPANION_ROW_AVATAR_SIZE} framed /></View><CompanionPresenceRing active={generating} /><CompanionPresenceDot connected={connected} />@@ -193,7 +193,6 @@ export function TeammateList({ items, loading, refreshing, error, isOnline, connpreviewPrefixTestID={attention ? 'teammate.attention' : undefined}unread={unread}unreadLabel={t('devices.companions.unread')}- disabled={!online}last={last}onPress={() => onSelect(row)} />;};diff --git a/apps/mobile/src/session/durableOutbox.ts b/apps/mobile/src/session/durableOutbox.tsindex dcf72de222..c334bf4a78 100644--- a/apps/mobile/src/session/durableOutbox.ts+++ b/apps/mobile/src/session/durableOutbox.ts@@ -21,6 +21,8 @@ export interface DurableOutboxRecord {/** Canonical realm-qualified auth accountKey; unqualified pre-release rows are never claimed. */accountId: string;deviceId: string;+ /** Permanent resource identity for sends queued from a companion, including after page exit/restart. */+ resourceRef?: import('@cindy/device-link').RemoteResourceRef;/** Stable disk/file identity when a cancelled creation is retried with a fresh session ID. */storageSessionId?: string;item: MobileOutboxItem;@@ -252,6 +254,10 @@ function isLoadableOutboxRecord(&& !!row.deviceId&& !!row.item?.sessionId&& !!row.item.clientId+ && (row.resourceRef === undefined || (row.resourceRef !== null+ && typeof row.resourceRef.collectionId === 'string' && !!row.resourceRef.collectionId+ && typeof row.resourceRef.kind === 'string' && !!row.resourceRef.kind+ && typeof row.resourceRef.id === 'string' && !!row.resourceRef.id))&& (row.storageSessionId === undefined|| (typeof row.storageSessionId === 'string' && row.storageSessionId.length > 0))&& keyFor(row) === keydiff --git a/apps/mobile/src/session/durableOutboxDelivery.ts b/apps/mobile/src/session/durableOutboxDelivery.tsindex d881b1f949..2dd3348a8f 100644--- a/apps/mobile/src/session/durableOutboxDelivery.ts+++ b/apps/mobile/src/session/durableOutboxDelivery.ts@@ -30,6 +30,8 @@ export interface DurableOutboxDeliveryDeps {upload: DurableUpload,): Promise<RemoteSerializedAttachment>;enqueue(record: DurableOutboxRecord): Promise<InputProjection>;+ /** Recheck resource ownership before recording that an external write has started. */+ beforeEnqueue?(record: DurableOutboxRecord): Promise<void>;cancel(record: DurableOutboxRecord): Promise<boolean>;history(record: DurableOutboxRecord): Promise<boolean>;/** A remote row alone cannot release the local bubble before offline history owns it. */@@ -286,6 +288,8 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {sendAtMs: record.sendAtMs ?? Date.now(),});}+ await deps.beforeEnqueue?.(record);+ if (!current(record) || !deps.canRun(record)) return;// This write precedes every external enqueue. Crash recovery therefore knows it must reconcile.await update({ state: "sending", enqueueStarted: true, error: undefined });const result = await deps.enqueue(record);diff --git a/apps/mobile/src/session/outboxResourceBinding.ts b/apps/mobile/src/session/outboxResourceBinding.tsnew file mode 100644index 0000000000..17372060b0--- /dev/null+++ b/apps/mobile/src/session/outboxResourceBinding.ts@@ -0,0 +1,26 @@+import type { RemoteResourceRef } from '@cindy/device-link';+import { getRemoteResource } from '@/device-link/remoteResources';+import type { RemoteInvoke } from '@/device-link/mobileMakerTransport';+import type { RemoteSession } from './types';++/** Presentation caches never authorize the app-owned outbox to send to a companion. */+export async function validateOutboxResourceBinding(+ invoke: RemoteInvoke, deviceId: string, sessionId: string, ref: RemoteResourceRef, locale: string,+) {+ const resource = await getRemoteResource(invoke, { deviceId, deviceName: deviceId }, ref, locale);+ if (resource.ref.collectionId !== ref.collectionId || resource.ref.kind !== ref.kind || resource.ref.id !== ref.id) {+ throw new Error('[PRECONDITION_FAILED] Resource identity changed');+ }+ const stage = (resource.blocks?.find(block => block.id === 'invitation' && block.primitive === 'status')?.data as { stage?: string } | undefined)?.stage;+ if (stage && stage !== 'ready') {+ throw new Error(stage === 'failed' ? '[PRECONDITION_FAILED] Resource preparation failed' : '[DEVICE_LINK_BUSY] Resource preparing');+ }+ const target = resource.links.find(link => link.rel === 'conversation')?.target;+ if (target?.kind !== 'session' || target.sessionId !== sessionId) {+ throw new Error('[PRECONDITION_FAILED] Resource conversation changed');+ }+ const session = await invoke<RemoteSession>(deviceId, 'local-db:sessions:get', [sessionId]);+ if (!session || session.id !== sessionId || session.status !== 'active' || (ref.kind === 'bot' && session.source !== 'bot')) {+ throw new Error('[PRECONDITION_FAILED] Resource conversation unavailable');+ }+}diff --git a/apps/mobile/src/session/teammateNavigation.ts b/apps/mobile/src/session/teammateNavigation.tsindex 22bda95aa6..be46181ecf 100644--- a/apps/mobile/src/session/teammateNavigation.ts+++ b/apps/mobile/src/session/teammateNavigation.ts@@ -1,6 +1,19 @@import { resolveRemoteText } from '@cindy/device-link';import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';import type { LastTeammateIdentity } from './homeViewPreferenceStore';+import type { RemoteSession } from './types';++/** Presentation skeleton only; cacheSeeded blocks dispatch until host metadata replaces it. */+export function teammateSessionPreview(hosted: HostedRemoteCollectionItem, userId: string, locale: string): RemoteSession | null {+ const target = hosted.item.links.find(link => link.rel === 'conversation')?.target;+ if (hosted.item.ref.kind !== 'bot' || target?.kind !== 'session' || !target.sessionId) return null;+ return {+ id: target.sessionId, userId, source: 'bot', title: resolveRemoteText(hosted.item.display.title, locale),+ cacheSeeded: true, workingDir: null, workspaceKind: 'dialogue', model: '', effort: '',+ permissionMode: 'ask', fastMode: false, agentKind: 'cc', status: 'active', userSendAt: null,+ createdAt: '', updatedAt: '',+ };+}export function teammateIdentity(hosted: HostedRemoteCollectionItem): LastTeammateIdentity | null {return hosted.item.ref.kind === 'bot' ? {diff --git a/apps/mobile/src/session/useRemoteResourceList.ts b/apps/mobile/src/session/useRemoteResourceList.tsindex 177e236cf7..efdeb37474 100644--- a/apps/mobile/src/session/useRemoteResourceList.ts+++ b/apps/mobile/src/session/useRemoteResourceList.ts@@ -12,8 +12,9 @@ import {import { remoteResourceConnectionState, hasRemoteCollectionCache, isRemoteResourceHostOnline, readRemoteCollectionCache, writeRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';import { listRemoteCollection, mergeRemoteCollectionHostShards, normalizeRemoteCollectionItems,type HostedRemoteCollectionItem, type RemoteResourceHostTarget } from '@/device-link/remoteResources';-import { formatRemoteError } from '@/device-link/remoteStatus';-import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';+import { formatRemoteError, isAutoRecoveringRemoteError } from '@/device-link/remoteStatus';+import { createRemoteReadRecovery } from '@/device-link/remoteReadRecovery';+import { retryRemoteSyncRead, type RemoteSyncRun, useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';import { startBoundedStartupRead } from './mobileHomeStartup';/** One roster reader for resource routes, home and the picker. Host shards reconcile independently. */@@ -33,6 +34,9 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Re}>(() => ({ binding, items: readRemoteCollectionCache(owner, collectionId), replies: {}, settled: hasRemoteCollectionCache(owner, collectionId), loading: true, refreshing: false, error: null }));const generation = useRef(0);const active = useRef(false);+ const focusController = useRef(new AbortController());+ const recovery = useRef<ReturnType<typeof createRemoteReadRecovery> | null>(null);+ const failedHosts = useRef(new Set<string>());const presenceKey = targets.map((target) => `${target.deviceId}:${getPresenceAvailability(target.deviceId)}`).join('|');void presenceVersion;useEffect(() => {@@ -50,59 +54,82 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Rereturn () => { cancelled = true; generation.current += 1; };}, [binding, collectionId, owner, user?.id]);- const read = useCallback(async (visible: boolean, isStale: () => boolean) => {+ const read = useCallback(async (run: RemoteSyncRun) => {if (!enabled || !active.current || hydrated !== binding || !collectionId) return;const expected = ++generation.current;- const current = () => !isStale() && generation.current === expected && bindingRef.current === binding && active.current;- setState((old) => ({ ...old, loading: true, refreshing: visible, error: null }));- const next: HostedRemoteCollectionItem[] = [];- const succeeded = new Set<string>();- const failures: string[] = [];- // Resource refresh must not fan out an unbounded burst on the shared relay.- for (let offset = 0; offset < targets.length; offset += 2) {- if (!current()) return;- const results = await Promise.allSettled(targets.slice(offset, offset + 2).map(async (host) => {- if (status !== 'online' || getPresenceAvailability(host.deviceId) === false) throw new Error(t('devices.resources.hostOffline'));- await openLink(host.deviceId);- const response = await listRemoteCollection(invoke, host, collectionId, i18n.language);- if (!response || !Array.isArray(response.items)) throw new Error(t('devices.resources.loadFailed'));- return { host, items: normalizeRemoteCollectionItems(response, collectionId) };- }));- if (!current()) return;- for (const result of results) {- if (result.status === 'rejected') { failures.push(formatRemoteError(result.reason)); continue; }- const { host, items } = result.value;- succeeded.add(host.deviceId);- for (const item of items) next.push({ host, item, key: JSON.stringify([host.deviceId, item.ref.collectionId, item.ref.kind, item.ref.id]) });+ const signal = focusController.current.signal;+ const current = () => !run.isStale() && !signal.aborted && generation.current === expected+ && bindingRef.current === binding && active.current && AppState.currentState === 'active';+ const selected = run.reasons.every(reason => reason === 'retry')+ ? targets.filter(host => failedHosts.current.has(host.deviceId)) : targets;+ failedHosts.current.clear();+ setState((old) => ({ ...old, loading: true, refreshing: run.reasons.includes('visible'), error: null }));+ const failures: unknown[] = [];+ let offset = 0;+ // Two workers, committing each host as it answers. A slow peer does not+ // hold successful shards or the next free worker behind a batch barrier.+ const worker = async () => {+ while (offset < selected.length && current()) {+ const host = selected[offset++];+ try {+ if (status !== 'online' || getPresenceAvailability(host.deviceId) === false) throw new Error(t('devices.resources.hostOffline'));+ const response = await retryRemoteSyncRead({ signal, isStale: () => !current() }, async () => {+ await openLink(host.deviceId);+ return listRemoteCollection(invoke, host, collectionId, i18n.language);+ });+ if (!current()) return;+ if (!response || !Array.isArray(response.items)) throw new Error(t('devices.resources.loadFailed'));+ const next = normalizeRemoteCollectionItems(response, collectionId).map(item => ({ host, item,+ key: JSON.stringify([host.deviceId, item.ref.collectionId, item.ref.kind, item.ref.id]) }));+ setState(old => ({ ...old,+ items: mergeRemoteCollectionHostShards(old.items, next, new Set([host.deviceId]), targets),+ replies: { ...old.replies, [host.deviceId]: connectionEpoch }, settled: true,+ }));+ } catch (error) {+ if (!current()) return;+ failures.push(error);+ if (isAutoRecoveringRemoteError(error)) failedHosts.current.add(host.deviceId);+ }}- }+ };+ await Promise.all([worker(), worker()]);if (!current()) return;- setState((old) => {- const items = mergeRemoteCollectionHostShards(old.items, next, succeeded, targets);- return { binding, items, replies: Object.fromEntries([...succeeded].map((id) => [id, connectionEpoch])),- settled: true, loading: false, refreshing: false,- error: failures.length ? failures.slice(0, 2).join('\n') : targets.length ? null : t('devices.resources.noHosts') };- });+ setState((old) => ({ ...old, binding,+ items: mergeRemoteCollectionHostShards(old.items, [], new Set(), targets),+ replies: Object.fromEntries(Object.entries(old.replies).filter(([id]) => targets.some(host => host.deviceId === id))),+ settled: true, loading: false, refreshing: false,+ error: failures.length ? failures.slice(0, 2).map(formatRemoteError).join('\n') : targets.length ? null : t('devices.resources.noHosts'),+ }));+ if (!failures.length) recovery.current?.succeeded();+ else failures.forEach(error => recovery.current?.failed(error));}, [binding, collectionId, connectionEpoch, enabled, getPresenceAvailability, hydrated, i18n.language, invoke, openLink, presenceKey, status, t, targets]);// Phase pushes can arrive faster than a roster RPC. Keep one active read and// one latest follow-up, using the same coordinator as other remote snapshots.const requestRefresh = useRemoteSyncCoordinator(- (run) => read(run.reasons.includes('visible'), run.isStale), binding,+ read, JSON.stringify([binding, connectionEpoch, status, presenceKey, targets, enabled, hydrated]),);const refresh = useCallback((visible = true) => requestRefresh({ reason: visible ? 'visible' : 'changed' }), [read, requestRefresh]);// Persist after commit, never from a React state updater (which may be replayed).useEffect(() => {- if (state.binding !== binding || state.loading || hydrated !== binding) return;+ if (state.binding !== binding || !state.settled || hydrated !== binding) return;writeRemoteCollectionCache(owner, collectionId, state.items);void cacheRemoteResourceItems(user?.id ?? '', collectionId, state.items);- }, [binding, collectionId, hydrated, owner, state.items, state.loading, state.binding, user?.id]);+ }, [binding, collectionId, hydrated, owner, state.items, state.settled, state.binding, user?.id]);useFocusEffect(useCallback(() => {if (!enabled) return;- active.current = true;- void refresh(false);- const foreground = AppState.addEventListener('change', (value) => { if (value === 'active') void refresh(false); });+ const start = () => {+ active.current = AppState.currentState === 'active';+ focusController.current = new AbortController();+ recovery.current = createRemoteReadRecovery(() => { void requestRefresh({ reason: 'retry' }); },+ () => active.current && status === 'online' && AppState.currentState === 'active');+ if (active.current) void refresh(false);+ };+ const stop = () => { active.current = false; generation.current += 1;+ focusController.current.abort(); recovery.current?.dispose(); };+ start();+ const foreground = AppState.addEventListener('change', (value) => { stop(); if (value === 'active') start(); });const off = onRemoteResourceChanged((deviceId, payload) => {if (AppState.currentState === 'active' && payload.collectionId === collectionId && targets.some((host) => host.deviceId === deviceId)) void refresh(false);});@@ -110,8 +137,8 @@ export function useRemoteResourceList(collectionId: string, targets: readonly RedeviceId: target.deviceId, owner: `remote-collection:${collectionId}:${target.deviceId}`,subscribe, topic: 'sessions', unsubscribe,}));- return () => { active.current = false; generation.current += 1; foreground.remove(); off(); cleanups.forEach((cleanup) => cleanup()); };- }, [collectionId, enabled, onRemoteResourceChanged, refresh, subscribe, targets, unsubscribe]));+ return () => { stop(); foreground.remove(); off(); cleanups.forEach((cleanup) => cleanup()); };+ }, [collectionId, enabled, onRemoteResourceChanged, refresh, requestRefresh, status, subscribe, targets, unsubscribe]));const ownState = state.binding === binding;const isOnline = useCallback((host: RemoteResourceHostTarget) => ownState && isRemoteResourceHostOnline(status, getPresenceAvailability(host.deviceId), state.replies[host.deviceId], connectionEpoch,diff --git a/apps/mobile/src/session/useRemoteResourceSession.ts b/apps/mobile/src/session/useRemoteResourceSession.tsindex 96700aca6a..0f3edbc0e1 100644--- a/apps/mobile/src/session/useRemoteResourceSession.ts+++ b/apps/mobile/src/session/useRemoteResourceSession.ts@@ -7,7 +7,9 @@ import { useAuth } from '@/auth/AuthContext';import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { getRemoteResource } from '@/device-link/remoteResources';import { readRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';-import { formatRemoteError } from '@/device-link/remoteStatus';+import { createRemoteReadRecovery } from '@/device-link/remoteReadRecovery';+import { createRemoteSyncCoordinator, retryRemoteSyncRead, type RemoteSyncRun } from '@/device-link/remoteSyncTask';+import { isAutoRecoveringRemoteError, formatRemoteError } from '@/device-link/remoteStatus';import { markRemoteResourceRead } from '@/device-link/remoteResourceCache';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';import { remoteSessionStore } from './remoteSessionStore';@@ -20,7 +22,7 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, sconst resourceId = typeof params.resourceId === 'string' ? params.resourceId : '';const resourceKind = typeof params.resourceKind === 'string' ? params.resourceKind : '';const historyEntry = params.openSearch === '1';- const { invoke, connectionEpoch, status, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();+ const { invoke, openLink, connectionEpoch, status, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();const { user, accountGeneration } = useAuth();const { t, i18n } = useTranslation();const router = useRouter();@@ -37,6 +39,13 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, sconst cached = readRemoteCollectionCache(`${user?.id ?? ''}:${accountGeneration}`, collectionId).find(row => row.host.deviceId === deviceId && row.item.ref.id === resourceId && row.item.ref.kind === resourceKind)?.item;const resource = display?.identity === identity ? display.resource : cached ?? null;+ const stage = (display?.identity === identity+ ? display.resource.blocks?.find(block => block.id === 'invitation' && block.primitive === 'status')?.data as { stage?: string } | undefined+ : undefined)?.stage;+ const cachedTarget = resource?.links.find(link => link.rel === 'conversation')?.target;+ // Local editing and durable queuing do not confer permission to dispatch.+ const canCompose = !required || (!!resource && cachedTarget?.kind === 'session' && cachedTarget.sessionId === sessionId+ && (!stage || stage === 'ready') && (!failure || failure.binding !== binding || isAutoRecoveringRemoteError(failure.message)));const ready = !required || (focused && AppState.currentState === 'active' && status === 'online' && verified === binding && metadataVerified);const markReadThrough = useCallback((at: number) => {if (current.current === binding && AppState.currentState === 'active' && ready && canMarkRead && resourceKind === 'bot' && resource && Number.isFinite(at) && at > 0) {@@ -49,12 +58,17 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, slet disposed = false;let generation = 0;let timer: ReturnType<typeof setTimeout> | undefined;- const load = async () => {+ const recovery = createRemoteReadRecovery(() => { void coordinator.request({ reason: 'retry' }); },+ () => !disposed && current.current === binding && AppState.currentState === 'active');+ const load = async (run: RemoteSyncRun) => {if (AppState.currentState !== 'active') return;const expected = ++generation;- const valid = () => !disposed && current.current === binding && generation === expected && AppState.currentState === 'active';+ const valid = () => !run.isStale() && !disposed && current.current === binding && generation === expected && AppState.currentState === 'active';try {- const resource = await getRemoteResource(invoke, { deviceId, deviceName }, { collectionId, id: resourceId, kind: resourceKind }, i18n.language);+ const resource = await retryRemoteSyncRead(run, async () => {+ await openLink(deviceId);+ return getRemoteResource(invoke, { deviceId, deviceName }, { collectionId, id: resourceId, kind: resourceKind }, i18n.language);+ });if (!valid()) return;// Reuse this existing read rather than issuing a second profile request per turn.setDisplay({ identity, resource });@@ -72,7 +86,7 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, sif (target?.kind !== 'session') throw new Error(t('devices.resources.noConversation'));if (target.sessionId !== sessionId) {setVerified(null);- const session = await invoke<RemoteSession>(deviceId, 'local-db:sessions:get', [target.sessionId]);+ const session = await retryRemoteSyncRead(run, () => invoke<RemoteSession>(deviceId, 'local-db:sessions:get', [target.sessionId]));if (!valid()) return;if (!session || session.id !== target.sessionId || (resourceKind === 'bot' && session.source !== 'bot')) throw new Error(t('devices.resources.noConversation'));const prior = remoteSessionStore.getSessionDeviceId(session.id);@@ -84,10 +98,12 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, s// History remains visible during preparation, but must not enable the// composer, realtime controls or queued sends until the invitation is ready.setVerified(invitationPending ? null : binding);+ recovery.succeeded();} catch (error) {if (!valid()) return;setVerified(null);setFailure({ binding, message: formatRemoteError(error) });+ recovery.failed(error);const code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;if (code === 'NOT_FOUND' || /\[NOT_FOUND\]/.test(String(error))) {setDisplay(null);@@ -100,17 +116,20 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, s// Transient link errors retain the normal task recovery path.}};+ const coordinator = createRemoteSyncCoordinator(load);+ coordinator.setContext(binding);+ const refresh = () => { void coordinator.request({ reason: 'changed' }); };const offPush = onRemoteResourceChanged((source, payload) => {if (source !== deviceId || payload.collectionId !== collectionId || timer) return;if (payload.resourceRefs?.length && !payload.resourceRefs.some((ref) => ref.id === resourceId && ref.kind === resourceKind)) return;generation += 1;setVerified(null);- timer = setTimeout(() => { timer = undefined; void load(); }, 300);+ timer = setTimeout(() => { timer = undefined; refresh(); }, 300);});const offTopic = startFocusedTopicSubscription({ deviceId, owner: `resource-session:${sessionId}`, topic: 'sessions', subscribe, unsubscribe });- const appState = AppState.addEventListener('change', (state) => { generation += 1; setVerified(null); if (state === 'active') void load(); });- void load();- return () => { disposed = true; setVerified(null); offPush(); offTopic(); appState.remove(); if (timer) clearTimeout(timer); };- }, [attempt, binding, historyEntry, collectionId, deviceId, deviceName, identity, invoke, i18n.language, onRemoteResourceChanged, resourceId, resourceKind, router, sessionId, status, subscribe, t, unsubscribe, user?.id]));- return { resource, ready, markReadThrough, error: failure?.binding === binding ? failure.message : null, retry };+ const appState = AppState.addEventListener('change', (state) => { generation += 1; setVerified(null); if (state === 'active') { coordinator.setContext(binding); refresh(); } else coordinator.setContext('background'); });+ refresh();+ return () => { disposed = true; recovery.dispose(); coordinator.setContext('disposed'); setVerified(null); offPush(); offTopic(); appState.remove(); if (timer) clearTimeout(timer); };+ }, [attempt, binding, historyEntry, collectionId, deviceId, deviceName, identity, invoke, openLink, i18n.language, onRemoteResourceChanged, resourceId, resourceKind, router, sessionId, status, subscribe, t, unsubscribe, user?.id]));+ return { resource, ready, canCompose, markReadThrough, error: failure?.binding === binding ? failure.message : null, retry };}diff --git a/apps/mobile/src/session/useTeammateNavigation.ts b/apps/mobile/src/session/useTeammateNavigation.tsindex 7cfb370a53..5ebfd6435b 100644--- a/apps/mobile/src/session/useTeammateNavigation.ts+++ b/apps/mobile/src/session/useTeammateNavigation.ts@@ -8,7 +8,8 @@ import type { HostedRemoteCollectionItem, RemoteResourceHostTarget } from '@/devimport { useGuardedPush } from '@/utils/useGuardedPush';import { useHomeMode } from './useHomeMode';import type { HomeMode } from './homeViewPreferenceStore';-import { homeDismissCount, teammateIdentity, teammateResourceRoute } from './teammateNavigation';+import { homeDismissCount, teammateIdentity, teammateResourceRoute, teammateSessionPreview } from './teammateNavigation';+import { remoteSessionStore } from './remoteSessionStore';import { readRemoteCollectionCache, writeRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';/** Push keeps the current chat/composer mounted; known teammates validate in the destination. */@@ -61,6 +62,13 @@ export function useTeammateNavigation() {const cached = readRemoteCollectionCache(owner, identity.collectionId);// Seed presentation from the clicked row, never an authorization result.writeRemoteCollectionCache(owner, identity.collectionId, [hosted, ...cached.filter(row => row.key !== hosted.key)].slice(0, 200));+ const preview = teammateSessionPreview(hosted, user?.id ?? '', i18n.language);+ // The home task cache is bounded and may not contain this canonical task.+ // Seed only missing local presentation, never replace real metadata or create a task.+ if (preview && !remoteSessionStore.getSessions().some(session => session.id === preview.id)+ && !remoteSessionStore.getSessionDeviceId(preview.id)) {+ remoteSessionStore.upsertDeviceSession(hosted.host.deviceId, hosted.host.deviceName, preview);+ }push(teammateResourceRoute(hosted, i18n.language));}} finally { if (pendingAccount.current === accountGeneration) pendingAccount.current = null; }diff --git a/apps/mobile/src/session/useTeammateRoster.ts b/apps/mobile/src/session/useTeammateRoster.tsindex f4539fc6ba..b44f9e0848 100644--- a/apps/mobile/src/session/useTeammateRoster.ts+++ b/apps/mobile/src/session/useTeammateRoster.ts@@ -8,11 +8,14 @@ import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { toDeviceListItems } from '@/device-link/devices';import { useRevokedDevices } from '@/device-link/revokedDevicesStore';import { cacheRemoteResourceHome, readRemoteResourceSnapshot } from '@/device-link/remoteResourceCache';+import { readRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';import { discoverRemoteHomeCollections, remoteResourceDiscoveryTargets,type RemoteHomeCollection, type RemoteResourceHostTarget } from '@/device-link/remoteResources';-import { formatRemoteError } from '@/device-link/remoteStatus';+import { formatRemoteError, isAutoRecoveringRemoteError } from '@/device-link/remoteStatus';import { hasBotGroupCollection } from './botGroupRemote';import { useRemoteResourceList } from './useRemoteResourceList';+import { createRemoteReadRecovery } from '@/device-link/remoteReadRecovery';+import { retryRemoteSyncRead, type RemoteSyncRun, useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';import { startBoundedStartupRead } from './mobileHomeStartup';const NO_TARGETS: RemoteResourceHostTarget[] = [];@@ -27,27 +30,64 @@ export function useTeammateRoster(enabled = true) {const binding = `${user?.id ?? ''}:${accountGeneration}`;const ownerRef = useRef(binding); ownerRef.current = binding;const generation = useRef(0);+ const active = useRef(false);+ const focusController = useRef(new AbortController());+ const recovery = useRef<ReturnType<typeof createRemoteReadRecovery> | null>(null);+ const lastCollections = useRef<{ binding: string; home: RemoteHomeCollection[] }>({ binding: '', home: [] });+ const failedHosts = useRef(new Set<string>());+ const lastCreateTargets = useRef<{ binding: string; targets: RemoteResourceHostTarget[] }>({ binding: '', targets: NO_TARGETS });// Hosts whose manifest advertises group chats (bot-group-chat.md §8); an older desktop never does.const lastGroupTargets = useRef<{ binding: string; targets: RemoteResourceHostTarget[] }>({ binding: '', targets: NO_TARGETS });const [discovery, setDiscovery] = useState<{binding: string; ready: boolean; loading: boolean; targets: RemoteResourceHostTarget[]; createTargets: RemoteResourceHostTarget[];groupTargets: RemoteResourceHostTarget[]; error: string | null;}>({ binding: '', ready: false, loading: true, targets: NO_TARGETS, createTargets: NO_TARGETS, groupTargets: NO_TARGETS, error: null });- const discover = useCallback(async () => {+ const discover = useCallback(async (run: RemoteSyncRun) => {const expected = ++generation.current;- const current = () => ownerRef.current === binding && generation.current === expected;+ const signal = focusController.current.signal;+ const current = () => !run.isStale() && !signal.aborted && active.current && AppState.currentState === 'active'+ && ownerRef.current === binding && generation.current === expected;setDiscovery((old) => ({ ...old, loading: true }));const { value: snapshot } = await startBoundedStartupRead(readRemoteResourceSnapshot(user?.id ?? ''), { home: [], items: {}, read: {} }).initial;if (!current()) return;- let collections: RemoteHomeCollection[] = snapshot.home;+ let collections: RemoteHomeCollection[] = lastCollections.current.binding === binding ? lastCollections.current.home : snapshot.home;+ if (lastCollections.current.binding !== binding) {+ const cachedItems = snapshot.items[TEAMMATE_COLLECTION_ID]?.length ? snapshot.items[TEAMMATE_COLLECTION_ID]+ : readRemoteCollectionCache(binding, TEAMMATE_COLLECTION_ID);+ const previous = collections.find(collection => collection.id === TEAMMATE_COLLECTION_ID && collection.resourceKind === 'bot');+ // Home capabilities and roster rows are saved independently. Until the+ // directory/manifest answers, both caches are navigation hints.+ const hosts = new Map([...(previous?.targets ?? []), ...cachedItems.map(row => row.host)]+ .map(host => [host.deviceId, host]));+ if (hosts.size) collections = previous+ ? collections.map(collection => collection === previous ? { ...collection, targets: [...hosts.values()] } : collection)+ : [...collections, { id: TEAMMATE_COLLECTION_ID, resourceKind: 'bot', placement: 'home-scope', title: '', targets: [...hosts.values()] }];+ }+ const publish = (home: RemoteHomeCollection[], loading: boolean) => {+ if (!current()) return;+ const targets = home.find(collection => collection.id === TEAMMATE_COLLECTION_ID && collection.resourceKind === 'bot')?.targets ?? NO_TARGETS;+ lastCollections.current = { binding, home };+ const filtered = targets.filter(host => !revoked.has(host.deviceId));+ setDiscovery(old => ({ ...old, binding, ready: true, loading,+ createTargets: old.binding === binding ? old.createTargets : NO_TARGETS,+ groupTargets: old.binding === binding ? old.groupTargets : NO_TARGETS,+ targets: old.binding === binding && JSON.stringify(old.targets) === JSON.stringify(filtered) ? old.targets : filtered }));+ };+ // Cached capabilities are navigation hints; authorization stays at the host.+ publish(collections, true);+ const failures: unknown[] = [];let error: string | null = null;const createTargets: RemoteResourceHostTarget[] = [];+ const retryHosts = new Set(failedHosts.current);+ const retryOnly = run.reasons.every(reason => reason === 'retry') && retryHosts.size > 0;+ if (!retryOnly) failedHosts.current.clear();const previousGroupTargets = lastGroupTargets.current.binding === binding ? lastGroupTargets.current.targets : NO_TARGETS;let groupTargets = previousGroupTargets;try {if (status !== 'online') throw new Error(t('devices.resources.hostOffline'));- const response = await readDeviceList();+ const response = await retryRemoteSyncRead({ signal, isStale: () => !current() }, readDeviceList);if (!current()) return;+ failedHosts.current.clear();const devices = toDeviceListItems(response.devices, Date.now(), revoked).map((row) => ({deviceId: row.device.deviceId, name: row.device.name, canOpen: row.canOpen, state: row.state,}));@@ -56,11 +96,32 @@ export function useTeammateRoster(enabled = true) {collections = collections.map((collection) => ({ ...collection,targets: collection.targets.filter((host) => targets.some((target) => target.deviceId === host.deviceId)),}));+ publish(collections, true);+ // Healthy shards keep their last capabilities. A failed peer must not+ // repeatedly reopen other computers or make their roster read start over.+ if (retryOnly && lastCreateTargets.current.binding === binding) {+ createTargets.push(...lastCreateTargets.current.targets.filter(host => !retryHosts.has(host.deviceId)+ && targets.some(target => target.deviceId === host.deviceId)));+ }+ const selected = targets.map(target => retryOnly && !retryHosts.has(target.deviceId)+ ? { ...target, offline: true } : target);const answered = new Set<string>();const advertisingGroups = new Set<string>();collections = await discoverRemoteHomeCollections(async <T,>(deviceId: string, channel: string, args?: unknown[]) => {- await openLink(deviceId);- const response = await invoke<T>(deviceId, channel, args);+ let response: T;+ try {+ response = await retryRemoteSyncRead({ signal, isStale: () => !current() }, async () => {+ await openLink(deviceId);+ return invoke<T>(deviceId, channel, args);+ });+ } catch (cause) {+ if (current()) {+ failures.push(cause);+ if (isAutoRecoveringRemoteError(cause)) failedHosts.current.add(deviceId);+ }+ throw cause;+ }+ if (!current()) throw new Error('Remote discovery superseded');if (channel === REMOTE_RESOURCE_MANIFEST_CHANNEL) {const manifest = response as RemoteResourceManifestResponse | null;answered.add(deviceId);@@ -72,29 +133,46 @@ export function useTeammateRoster(enabled = true) {}}return response;- }, targets, i18n.language, collections);+ }, selected, i18n.language, collections, home => publish(home, true));if (!current()) return;// A host that did not answer this time keeps its groups until it answers again.groupTargets = targets.filter((target) => advertisingGroups.has(target.deviceId)|| (!answered.has(target.deviceId) && previousGroupTargets.some((host) => host.deviceId === target.deviceId)));void cacheRemoteResourceHome(user?.id ?? '', collections);- } catch (cause) { error = formatRemoteError(cause); }+ } catch (cause) { error = formatRemoteError(cause); failures.push(cause); }if (!current()) return;+ lastCollections.current = { binding, home: collections };+ if (!failures.length) recovery.current?.succeeded();+ else failures.forEach(cause => recovery.current?.failed(cause));const targets = collections.find((collection) => collection.id === TEAMMATE_COLLECTION_ID && collection.resourceKind === 'bot')?.targets ?? NO_TARGETS;groupTargets = groupTargets.filter((host) => !revoked.has(host.deviceId));lastGroupTargets.current = { binding, targets: groupTargets };- setDiscovery({ binding, ready: true, loading: false, createTargets, targets: targets.filter((host) => !revoked.has(host.deviceId)), groupTargets, error });+ lastCreateTargets.current = { binding, targets: createTargets };+ const filtered = targets.filter(host => !revoked.has(host.deviceId));+ setDiscovery(old => ({ binding, ready: true, loading: false, createTargets,+ targets: old.binding === binding && JSON.stringify(old.targets) === JSON.stringify(filtered) ? old.targets : filtered,+ groupTargets, error: error ?? (failures.length ? formatRemoteError(failures[0]) : null) }));}, [binding, i18n.language, invoke, openLink, readDeviceList, revoked, status, t, user?.id]);+ const requestDiscover = useRemoteSyncCoordinator(discover, JSON.stringify([binding, connectionEpoch, presenceVersion, status, enabled]));useFocusEffect(useCallback(() => {if (!enabled) return;- void discover();- const foreground = AppState.addEventListener('change', (value) => { if (value === 'active') void discover(); });- return () => { generation.current += 1; foreground.remove(); };- }, [connectionEpoch, discover, enabled, presenceVersion]));+ const start = () => {+ active.current = AppState.currentState === 'active';+ focusController.current = new AbortController();+ recovery.current = createRemoteReadRecovery(() => { void requestDiscover({ reason: 'retry' }); },+ () => active.current && status === 'online' && AppState.currentState === 'active');+ if (active.current) void requestDiscover({ reason: 'focus' });+ };+ const stop = () => { active.current = false; generation.current += 1;+ focusController.current.abort(); recovery.current?.dispose(); };+ start();+ const foreground = AppState.addEventListener('change', (value) => { stop(); if (value === 'active') start(); });+ return () => { stop(); foreground.remove(); };+ }, [connectionEpoch, discover, enabled, presenceVersion, requestDiscover, status]));const ready = discovery.binding === binding && discovery.ready;const list = useRemoteResourceList(TEAMMATE_COLLECTION_ID, ready ? discovery.targets : NO_TARGETS, enabled && ready);// Discover refreshes targets too: newly online hosts and newly created rosters are not stranded.- const refresh = useCallback(async () => { await discover(); }, [discover]);+ const refresh = useCallback(async () => { await requestDiscover({ reason: 'visible' }); await list.refresh(); }, [requestDiscover, list.refresh]);const items = list.items.filter(row => row.item.ref.kind === 'bot' && !revoked.has(row.host.deviceId)&& (!ready || discovery.targets.some(host => host.deviceId === row.host.deviceId)));return { ...list, items,diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex acec93151e..420d416afd 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -298,9 +298,21 @@ enum 编译分支,也不接受任意 HTML、React 或无限 UI DSL。解析 `conversation` 等 link,不能把可能 rollover 的 Session id 当成永久资源身份。已有对话继续复用 canonical Session 的消息、输入、确认与恢复链路,不复制一套模块专属聊天协议。列表已有 conversation link 时,可直接展示聊天框架和同账号缓存,在聊天页内重读资源,-复用该页的 Session 元数据查询校验 ID、类型与设备归属;校验完成前不放开发送、控制和已读。+复用该页的 Session 元数据查询校验 ID、类型与设备归属;校验完成前不允许远端投递、控制和已读。列表返回与后台刷新应保留已有内容,仅首次无数据时显示整页加载,不用固定延迟掩盖切换。+手机伙伴列表的同步新鲜度不决定已缓存伙伴能否打开:连接圆点只消费实际连接与 presence,+列表失败保留之前成功的同连接代次证据,各电脑的成功分片立即更新。暂时读取失败复用既有+错误分类、读取重试与恢复退避;只在前台可见时补读,离开、后台、账号变更与永久错误不续读。+缓存仅供同账号展示,撤权设备仍过滤;无 conversation link 时仍由原资源路由解析,不猜身份。++已有 canonical link 的伙伴在断网时可读本机已缓存历史、编辑持久草稿;未缓存历史明确提示+连接电脑后同步。用户点发送才写入现有 durable outbox,纯草稿不自动发送。新伙伴待发送记录+额外保存资源身份,应用级队列在首次远端 enqueue 前重读资源、准备状态、canonical link 与+Session 类型,不能借页面关闭绕过校验。队列仍按原 clientId 对账和去重:接收不等于送达,+旧主机结果未知时不盲重放,已获宿主持久接收的记录只对账。恢复范围是单 host/read/outbox,+不拆共享 relay,不增加云端执行或 wire 协议;现有历史、草稿和 outbox 的账号清理规则不变。+协议按字段追加演进。未知字段、未知 collection 和未知 action 不得导致整个首页或会话崩溃;结构化 Session 内容必须携带可读 `fallbackMarkdown`,旧客户端至少能阅读并继续任务。只有新增移动端此前无法表达的内容或交互原语时,才要求客户端发版。