Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 保留伙伴聊天与返回列表,移除多余加载中转 (#5067)
Chris Zhanga4b5d720d490
diff --git a/apps/mobile/app/resources/[collectionId].tsx b/apps/mobile/app/resources/[collectionId].tsxindex 80d11eec53..e4e8f6ef72 100644--- a/apps/mobile/app/resources/[collectionId].tsx+++ b/apps/mobile/app/resources/[collectionId].tsx@@ -1,9 +1,9 @@-import { cacheRemoteResourceItems, readRemoteResourceSnapshot, isRemoteResourceUnread, subscribeRemoteResourceCache, remoteResourceCacheRevision } from '@/device-link/remoteResourceCache';-import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';-import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';+import { useRemoteResourceList } from '@/session/useRemoteResourceList';+import { isRemoteResourceUnread } from '@/device-link/remoteResourceCache';+import { useLocalSearchParams, useRouter } from 'expo-router';+import { useCallback, useMemo } from 'react';import {ActivityIndicator,- AppState,FlatList,Pressable,RefreshControl,@@ -18,23 +18,16 @@ import {} from '@cindy/device-link';import { Text } from '@/components/AppText';+import { useTeammateNavigation } from '@/session/useTeammateNavigation';import { TeammateList } from '@/session/TeammateList';import { RemoteCompanionAvatar } from '@/components/RemoteCompanionAvatar';import { MainWindowEmptyState, StatusDot } from '@/components/MobilePrimitives';import { SimpleStackHeader, simpleScreenSafeAreaEdges } from '@/platform/chrome';import { useAuth } from '@/auth/AuthContext';-import { remoteResourceConnectionState, isRemoteResourceHostOnline, readRemoteCollectionCache, writeRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';-import { useDeviceLink } from '@/device-link/DeviceLinkContext';import {type HostedRemoteCollectionItem,- listRemoteCollection,- mergeRemoteCollectionHostShards,- normalizeRemoteCollectionItems,parseRemoteResourceTargets,} from '@/device-link/remoteResources';-import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';-import { formatRemoteError } from '@/device-link/remoteStatus';-import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';import { goBackGuarded } from '@/utils/backGuard';import { useGuardedPush } from '@/utils/useGuardedPush';import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';@@ -58,6 +51,7 @@ export default function RemoteCollectionScreen() {const { t, i18n } = useTranslation();const router = useRouter();const guardedPush = useGuardedPush();+ const teammates = useTeammateNavigation();const params = useLocalSearchParams<{collectionId?: string;title?: string;@@ -68,137 +62,14 @@ export default function RemoteCollectionScreen() {: params.collectionId ?? '';const title = Array.isArray(params.title) ? params.title[0] : params.title;const targets = useMemo(() => parseRemoteResourceTargets(params.targets), [params.targets]);- const {- connectionEpoch,- status: relayStatus,- presenceVersion,- getPresenceAvailability,- invoke,- onRemoteResourceChanged,- subscribe,- unsubscribe,- } = useDeviceLink();- const { accountGeneration, user } = useAuth();- useSyncExternalStore(subscribeRemoteResourceCache, remoteResourceCacheRevision);- const [hydratedOwner, setHydratedOwner] = useState('');- const cacheOwner = `${user?.id ?? ''}:${accountGeneration}`;- const accountRef = useRef(accountGeneration);- accountRef.current = accountGeneration;- const [replyEpochs, setReplyEpochs] = useState<Record<string, number>>({});- const presenceKey = targets.map((host) => `${host.deviceId}:${getPresenceAvailability(host.deviceId)}`).join('|');- // Reading presenceVersion makes the authoritative availability projection reactive.- void presenceVersion;- const [itemsAccount, setItemsAccount] = useState(accountGeneration);- const [items, setItems] = useState<HostedResourceItem[]>(() => readRemoteCollectionCache(cacheOwner, collectionId));- const loadGenerationRef = useRef(0);- const active = useRef(false);- const [loading, setLoading] = useState(true);- const [refreshing, setRefreshing] = useState(false);- const [error, setError] = useState<string | null>(null);-- const read = useCallback(async (visible: boolean, isStale: () => boolean) => {- if (!active.current || hydratedOwner !== cacheOwner) return;- const generation = ++loadGenerationRef.current;- const expectedAccount = accountGeneration;- if (!collectionId || targets.length === 0) {- setItems([]);- setError(t('devices.resources.noHosts'));- setLoading(false);- return;- }- if (visible) setRefreshing(true);- else setLoading(true);- const results = await Promise.allSettled(targets.map(async (host) => {- if (relayStatus !== 'online' || getPresenceAvailability(host.deviceId) === false) throw new Error(t('devices.resources.hostOffline'));- return { host, response: await listRemoteCollection(invoke, host, collectionId, i18n.language) };- }));- if (isStale() || !active.current || loadGenerationRef.current !== generation || accountRef.current !== expectedAccount) return;- const next: HostedResourceItem[] = [];- const failures: string[] = [];- const successfulDeviceIds = new Set<string>();- for (const result of results) {- if (result.status === 'rejected') {- failures.push(formatRemoteError(result.reason));- continue;- }- successfulDeviceIds.add(result.value.host.deviceId);- const rawItems = normalizeRemoteCollectionItems(result.value.response, collectionId);- for (const item of rawItems) {- next.push({- key: `${result.value.host.deviceId}:${item.ref.kind}:${item.ref.id}`,- host: result.value.host,- item,- });- }- }- setReplyEpochs(Object.fromEntries([...successfulDeviceIds].map((id) => [id, connectionEpoch])));- const allHostsFailed = failures.length === targets.length;- setItemsAccount(expectedAccount);- setItems((current) => {- const merged = mergeRemoteCollectionHostShards(current, next, successfulDeviceIds, targets);- writeRemoteCollectionCache(cacheOwner, collectionId, merged);- void cacheRemoteResourceItems(user?.id ?? '', collectionId, merged);- return merged;- });- setError(allHostsFailed ? failures.slice(0, 2).join('\n') : null);- setLoading(false);- setRefreshing(false);- }, [accountGeneration, cacheOwner, collectionId, connectionEpoch, getPresenceAvailability, hydratedOwner, i18n.language, invoke, relayStatus, t, targets, presenceKey, user?.id]);-- const requestRefresh = useRemoteSyncCoordinator(- (run) => read(run.reasons.includes('visible'), run.isStale), JSON.stringify([cacheOwner, collectionId]),- );- const load = useCallback((visible: boolean) => requestRefresh({ reason: visible ? 'visible' : 'changed' }), [read, requestRefresh]);-- useEffect(() => {- loadGenerationRef.current += 1;- setItems(readRemoteCollectionCache(cacheOwner, collectionId));- setItemsAccount(accountGeneration);- setReplyEpochs({});- let cancelled = false;- void readRemoteResourceSnapshot(user?.id ?? '').then((snapshot) => {- if (cancelled) return;- setItems((current) => current.length ? current : snapshot.items[collectionId] ?? []);- setHydratedOwner(cacheOwner);- });- return () => { cancelled = true; };- }, [accountGeneration, cacheOwner, collectionId, user?.id]);-- useFocusEffect(useCallback(() => {- active.current = true;- void load(false);- return () => { active.current = false; loadGenerationRef.current += 1; };- }, [connectionEpoch, load]));- useFocusEffect(useCallback(() => {- const subscription = AppState.addEventListener('change', (state) => {- if (state === 'active') void load(false);- });- return () => subscription.remove();- }, [load]));- useFocusEffect(useCallback(() => {- if (!collectionId) return undefined;- const cleanups = targets.map((target) => startFocusedTopicSubscription({- deviceId: target.deviceId,- owner: `remote-collection:${collectionId}:${target.deviceId}`,- subscribe,- topic: 'sessions',- unsubscribe,- }));- return () => {- for (const cleanup of cleanups) cleanup();- };- }, [collectionId, subscribe, targets, unsubscribe]));- useEffect(() => onRemoteResourceChanged((deviceId, payload) => {- if (- payload.collectionId === collectionId- && targets.some((target) => target.deviceId === deviceId)- ) {- void load(false);- }- }), [collectionId, load, onRemoteResourceChanged, targets]);+ const list = useRemoteResourceList(collectionId, targets);+ const { items, loading, refreshing, error, isOnline, connectionState } = list;+ const load = list.refresh;+ const { user } = useAuth();const openItem = useCallback((hosted: HostedResourceItem) => {- if (!isRemoteResourceHostOnline(relayStatus, getPresenceAvailability(hosted.host.deviceId), replyEpochs[hosted.host.deviceId], connectionEpoch)) return;+ if (!isOnline(hosted.host)) return;+ if (hosted.item.ref.kind === 'bot') { void teammates.openTeammate(hosted); return; }guardedPush({pathname: '/resources/[collectionId]/[resourceId]',params: {@@ -210,7 +81,7 @@ export default function RemoteCollectionScreen() {title: resolveRemoteText(hosted.item.display.title, i18n.language),},});- }, [collectionId, connectionEpoch, getPresenceAvailability, guardedPush, i18n.language, relayStatus, replyEpochs]);+ }, [collectionId, guardedPush, i18n.language, isOnline, teammates.openTeammate]);return (<SafeAreaView@@ -226,9 +97,9 @@ export default function RemoteCollectionScreen() {titleTestID="remoteResources.title"/>{collectionId === 'teammates' ? <TeammateList- items={itemsAccount === accountGeneration ? items : []} loading={loading} refreshing={refreshing} error={error}- connectionState={host => remoteResourceConnectionState(relayStatus, getPresenceAvailability(host.deviceId))}- isOnline={host => isRemoteResourceHostOnline(relayStatus, getPresenceAvailability(host.deviceId), replyEpochs[host.deviceId], connectionEpoch)}+ items={items} loading={loading} refreshing={refreshing} error={error}+ connectionState={connectionState}+ isOnline={isOnline}onRefresh={() => void load(true)} onSelect={openItem} /> : loading && items.length === 0 ? (<View style={styles.center}><ActivityIndicator color={colors.textSecondary} />@@ -237,7 +108,7 @@ export default function RemoteCollectionScreen() {) : (<FlatListcontentContainerStyle={items.length === 0 ? styles.emptyContent : styles.listContent}- data={itemsAccount === accountGeneration ? items : []}+ data={items}keyExtractor={(item) => item.key}refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => void load(true)} />}renderItem={({ item: hosted }) => {@@ -248,7 +119,7 @@ export default function RemoteCollectionScreen() {: display.subtitle? resolveRemoteText(display.subtitle, i18n.language): '';- const online = isRemoteResourceHostOnline(relayStatus, getPresenceAvailability(hosted.host.deviceId), replyEpochs[hosted.host.deviceId], connectionEpoch);+ const online = isOnline(hosted.host);const status = !online ? t('devices.resources.hostOffline') : display.status? resolveRemoteText(display.status.label, i18n.language): '';diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex b29779cf7b..315a6a0bbf 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -937,6 +937,7 @@ export default function SessionScreen() {const params = useLocalSearchParams<{sessionId: string;notificationResponse?: string;+ resourceKind?: string;deviceId?: string;deviceName?: string;draft?: string;@@ -2121,18 +2122,29 @@ export default function SessionScreen() {const outboxRecoverySyncHeld = hasLatchedOutboxTransportHold|| connectionEpochRecoverySyncPending|| presenceRecoverySyncPending;+ const hasRenderedMessages = historyView.snapshot.ready ? historyView.snapshot.items.length > 0 : messages.length > 0;+ const companionEntry = useRemoteResourceSession(deviceId, deviceName, sessionId,+ currentSession?.id === sessionId && hasRenderedMessages+ && readAckSyncedKey === `${sessionId}:${connectionEpoch}`+ // A pre-ACK snapshot may omit replies sent before the subscription took effect.+ && contentRecoveryKey !== null && contentSyncedKey === contentRecoveryKey+ && !outboxRecoverySyncHeld && !loading,+ sessionMetadataSyncedKey === `${sessionId}:${connectionEpoch}`+ && (readRouteParam(params.resourceKind) !== 'bot' || currentSession?.source === 'bot'));+ const companionResource = companionEntry.resource;+// 对齐 Desktop:输入与发送仍可排队,但模型、权限、Plan、停止等需要即时访问// 被控端的操作在明确断线时禁用。presence unknown 仍允许,避免旧缓存永久锁死入口。const remoteRealtimeControlsUnavailable = status !== 'online'|| targetAvailableForDispatch === false|| isDeviceUnresponsive- || outboxRecoverySyncHeld;+ || outboxRecoverySyncHeld || !companionEntry.ready;const remoteStopUnavailable = remoteRealtimeControlsUnavailable;const outboxConnectionState: MobileOutboxConnectionState = {relayOnline: status === 'online',targetAvailable: targetAvailableForDispatch,deviceUnresponsive: isDeviceUnresponsive,- autoRecoveringError: outboxRecoverySyncHeld,+ autoRecoveringError: outboxRecoverySyncHeld || !companionEntry.ready,syncInProgress: loading,};// pumpOutbox 是跨 render 的 async 循环,每轮必须读最新连接态;只捕获某一帧会在@@ -2143,7 +2155,7 @@ export default function SessionScreen() {outboxConnectionState,);// 弱网普通断线也要有可见信号(消息流静默停更没有任何提示),经防闪延迟后显示- const connectionRecoveryError = activeOutboxTransportError ?? connectionError;+ const connectionRecoveryError = companionEntry.error ?? activeOutboxTransportError ?? connectionError;const bannerError = connectionRecoveryError ?? historyError;const bannerRetriesHistory = connectionRecoveryError === null && historyError !== null;const contentRecoveryState = contentRecoveryKey !== null@@ -2198,13 +2210,6 @@ export default function SessionScreen() {remoteSessionStore.subscribe,() => remoteSessionStore.getSessionLiveActivity(sessionId)?.attention === true,);- const hasRenderedMessages = historyView.snapshot.ready ? historyView.snapshot.items.length > 0 : messages.length > 0;- const companionResource = useRemoteResourceSession(deviceId, deviceName, sessionId,- currentSession?.id === sessionId && hasRenderedMessages- && readAckSyncedKey === `${sessionId}:${connectionEpoch}`- // A pre-ACK snapshot may omit replies sent before the subscription took effect.- && contentRecoveryKey !== null && contentSyncedKey === contentRecoveryKey- && !outboxRecoverySyncHeld && !loading);const companionChat = useHostManagedSession(JSON.stringify([auth.accountGeneration, deviceId, sessionId]),companionResource?.ref.kind === 'bot' ? { source: 'bot' } : currentSession,@@ -2401,7 +2406,7 @@ export default function SessionScreen() {setPendingPlanViewerState('half');}}, [activePendingKind, activePendingRequestId, sessionOperationLayout.composerSlot]);- const canUseComposer = sessionOperationLayout.canUseComposer && !sessionResourceCards.blocked;+ const canUseComposer = sessionOperationLayout.canUseComposer && !sessionResourceCards.blocked && companionEntry.ready;const canUseRemoteSessionControls = canUseComposer&& !sessionSettingsLocked&& !remoteRealtimeControlsUnavailable;@@ -2412,7 +2417,7 @@ export default function SessionScreen() {const composerDisabledReasonKey = composerDisabledReasonI18nKey(sessionOperationLayout.composerDisabledReasonSource,);- const composerDisabledReason = composerDisabledReasonKey+ const composerDisabledReason = !companionEntry.ready ? t('shared.syncing') : composerDisabledReasonKey? t(composerDisabledReasonKey): sessionOperationLayout.composerDisabledReason?? (sessionResourceCards.blocked@@ -3371,6 +3376,14 @@ export default function SessionScreen() {&& readAckGateGenRef.current === readAckGateGenAtStart),(sessionMeta) => {+ // A roster link only selects the initial page. Preserve the resolver's+ // task/host checks before publishing authoritative entry metadata.+ if (readRouteParam(params.resourceKind)) {+ const origin = remoteSessionStore.getSessionDeviceId(sessionId);+ if (!sessionMeta || sessionMeta.id !== sessionId+ || (readRouteParam(params.resourceKind) === 'bot' && sessionMeta.source !== 'bot')+ || (origin && origin !== deviceId)) throw new Error(t('devices.resources.noConversation'));+ }remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);setSessionMetadataSyncedKey(`${sessionId}:${readAckEpochAtStart}`);},@@ -3593,7 +3606,7 @@ export default function SessionScreen() {} finally {if (!syncRun.isStale() && messageAuthorityCurrent()) setLoading(false);}- }, [deviceId, deviceName, getSubscriptionIdentity, latchOutboxTransportHold, maker, notificationResponse, openLink, reopenLink, remoteHistoryAvailable, sessionId, setError, subscribe]);+ }, [deviceId, deviceName, getSubscriptionIdentity, latchOutboxTransportHold, maker, notificationResponse, openLink, params.resourceKind, reopenLink, remoteHistoryAvailable, sessionId, setError, subscribe, t]);// 任一连接恢复身份变化都会让旧读取失去提交资格。否则断线前启动的同步可能在// 新 hold 锁存后迟到,并从成功尾误清恢复屏障。const remoteSyncContextKey = JSON.stringify([@@ -8735,7 +8748,7 @@ export default function SessionScreen() {{companionChat && companionResource && !shareSelectionActive ? <><SystemNavigationBack label={t('shared.back')} onPress={goBackToHome} /><CompanionHeader key={`${auth.accountGeneration}:${deviceId}:${companionResource.ref.id}`}- resource={companionResource} deviceId={deviceId} deviceName={deviceName} online={!remoteUnavailableReason}+ resource={companionResource} deviceId={deviceId} deviceName={deviceName} online={!remoteUnavailableReason} controlsReady={companionEntry.ready}onSearch={() => setSearchOpen(true)}onOpenNavigation={() => setCompanionNavigation({ scope: companionNavigationScope, open: true })} /></> : <SessionHeaderBar@@ -8824,9 +8837,11 @@ export default function SessionScreen() {issue={connectionIssue}lastSyncedAt={lastSyncedAt}loading={loading || loadingEarlier}- onSync={() => bannerRetriesHistory- ? void loadEarlierMessages()- : void requestSync({ reason: 'manual', replaceMessages: false })}+ onSync={() => {+ if (companionEntry.error) companionEntry.retry();+ if (bannerRetriesHistory) void loadEarlierMessages();+ else void requestSync({ reason: 'manual', replaceMessages: false });+ }}status={status}recovery={contentRecoveryState}variant="inline"@@ -9172,7 +9187,7 @@ export default function SessionScreen() {contentBottomInset={companionInlineInteraction && !shareSelectionActive? spacing.md: nativeComposerFrameAvailable && sessionOperationLayout.composerSlot === 'editable' && !shareSelectionActive- ? MOBILE_MESSAGE_LIST_BOTTOM_PADDING+ ? (bottomOverlayHeight > 0 ? bottomOverlayHeight : MOBILE_MESSAGE_LIST_BOTTOM_PADDING): undefined}topOverlayHeight={topOverlayHeight}busyAction={messageActionBusy?.kind ?? null}diff --git a/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx b/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsxindex 5963cc4609..c3aca34bab 100644--- a/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx+++ b/apps/mobile/src/__tests__/CompanionHeaderNavigation.test.tsx@@ -36,8 +36,8 @@ vi.mock('@/theme', async () => {return { ...tokens, useTheme: () => ({ colors: tokens.lightColors }), useThemedStyles: (fn: any) => fn(tokens.lightColors) };});vi.mock('lucide-react-native', () => ({ ChevronDown: () => null, PanelLeft: () => null, Settings2: () => null }));-vi.mock('@/session/HomeHeaderGlassButton', () => ({ HomeHeaderGlassButton: ({ onPress, testID, children }: any) =>- createElement('button', { onClick: onPress, 'data-testid': testID }, children) }));+vi.mock('@/session/HomeHeaderGlassButton', () => ({ HomeHeaderGlassButton: ({ onPress, testID, children, disabled }: any) =>+ createElement('button', { onClick: onPress, disabled, 'data-testid': testID }, children) }));vi.mock('@/session/TeammatePicker', () => ({ TeammatePicker: () => null }));vi.mock('@/session/CompanionProfileSheet', () => ({ CompanionCreateSheet: () => null,CompanionProfileSheet: (props: unknown) => { h.profile = props; return null; } }));@@ -166,7 +166,7 @@ function relevantJsx(node: ts.Node): string {result.dispose(); return text;}const compiled = ts.transpileModule(`function PageHost({ bindings }) {- const { auth, deviceId, sessionId, companionResource, shareSelectionActive, setSearchOpen } = bindings;+ const { auth, deviceId, sessionId, companionResource, companionEntry, shareSelectionActive, setSearchOpen } = bindings;const currentSession = null;const deviceName = 'PC', remoteUnavailableReason = null, sessionListDrawerOverlayMounted = false;${statements.slice(stateStart, stateEnd).map(n => n.getText(source)).join('\n')}@@ -176,6 +176,7 @@ const compiled = ts.transpileModule(`function PageHost({ bindings }) {const PageHost = new Function('React', 'useState', 'useHostManagedSession', 'CompanionHeader', 'CompanionNavigationDrawer', 'MessageHistoryOverlay',`${compiled}; return PageHost;`)({ createElement, Fragment }, useState, useHostManagedSession, CompanionHeader, CompanionNavigationDrawer, MessageHistoryOverlay);const pageBindings = () => ({ auth: h.auth, deviceId: 'pc', sessionId: 'session-a', shareSelectionActive: false,+ companionEntry: { ready: true },companionResource: { ref: { kind: 'bot', collectionId: 'bots', id: 'bot-a' }, display: { title: 'Cindy' } } as RemoteResource | null,setSearchOpen: vi.fn() });const showPage = (bindings: ReturnType<typeof pageBindings>) => act(async () => {@@ -183,6 +184,17 @@ const showPage = (bindings: ReturnType<typeof pageBindings>) => act(async () =>});const openPageDrawer = () => act(async () => host.querySelector<HTMLButtonElement>('[data-testid="companion.navigation"]')!.click());+it('shows the companion title while profile controls wait for entry validation', async () => {+ const bindings = pageBindings(); bindings.companionEntry.ready = false;+ await showPage(bindings);+ expect(host.textContent).toContain('Cindy');+ expect(host.querySelector<HTMLButtonElement>('[data-testid="companion.settings"]')!.disabled).toBe(true);+ expect(h.profile.online).toBe(true); // Synchronizing is not an offline connection.+ bindings.companionEntry.ready = true;+ await showPage(bindings);+ expect(host.querySelector<HTMLButtonElement>('[data-testid="companion.settings"]')!.disabled).toBe(false);+});+it('opens the page-owned drawer in the real Android history overlay and closes before searching', async () => {const bindings = pageBindings();await showPage(bindings); await openPageDrawer();diff --git a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsxindex 84e0bd8e05..ebeae12c16 100644--- a/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx+++ b/apps/mobile/src/__tests__/TeammateHomeScreen.test.tsx@@ -18,7 +18,7 @@ vi.mock('react-native', async () => {return { View: ({ children }: any) => el('div', {}, children), ActivityIndicator: () => null,Keyboard: { dismiss() {} }, Alert: { alert: vi.fn() }, StyleSheet: { create: (value: unknown) => value } };});-vi.mock('expo-router', () => ({ Stack: { Screen: () => null }, useIsFocused: () => h.focused, useRouter: () => ({ dismissTo: h.dismissTo }) }));+vi.mock('expo-router', () => ({ Stack: { Screen: () => null }, useIsFocused: () => h.focused, useNavigation: () => ({ getState: () => ({ routes: [] }) }), useRouter: () => ({ dismissTo: h.dismissTo }) }));vi.mock('react-native-safe-area-context', () => ({ SafeAreaView: 'div' }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }) }));vi.mock('lucide-react-native', () => ({ Menu: () => null }));diff --git a/apps/mobile/src/__tests__/messageEntryPositioning.test.ts b/apps/mobile/src/__tests__/messageEntryPositioning.test.tsnew file mode 100644index 0000000000..d8c608e689--- /dev/null+++ b/apps/mobile/src/__tests__/messageEntryPositioning.test.ts@@ -0,0 +1,146 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import ts from 'typescript';+import { describe, expect, it, vi } from 'vitest';++// Execute the production component's layout/passive callbacks in their real+// order. Only native list/animation APIs are injected; no positioning logic is+// copied into this fixture and no reveal deadline is advanced.+const source = ts.createSourceFile('MessageRenderer.tsx', readFileSync(+ resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8',+), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+function callback(marker: string, bindings: Record<string, unknown>) {+ let expression: ts.Expression | undefined;+ const visit = (node: ts.Node) => {+ if (ts.isCallExpression(node) && ['useCallback', 'useLayoutEffect', 'useEffect'].includes(node.expression.getText(source))+ && node.arguments[0]?.getText(source).includes(marker)) expression = node.arguments[0];+ ts.forEachChild(node, visit);+ };+ visit(source);+ if (!expression) throw new Error(`Missing production callback: ${marker}`);+ const compiled = ts.transpileModule(`const callback = ${expression.getText(source)};`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022 },+ }).outputText;+ return new Function(...Object.keys(bindings), `${compiled}; return callback;`)(...Object.values(bindings));+}+const ref = <T>(current: T) => ({ current });+function fixture(focused: string | null = null, saved?: object) {+ const state = { revealed: false, away: false };+ const bindings: Record<string, any> = {+ initialAnchorDoneRef: ref(false), initialRevealGenerationRef: ref(0),+ initialRevealAnimationRef: ref(null), initialRevealProgress: { setValue: vi.fn() },+ setListRevealed: (value: boolean) => { state.revealed = value; },+ setIsAwayFromBottom: (value: boolean) => { state.away = value; },+ Animated: { timing: () => ({ start: vi.fn(), stop: vi.fn() }) },+ Easing: { step1: 'step1' }, MOBILE_INITIAL_REVEAL_MAX_MS: 300,+ focusedItemKeyRef: ref(focused), reopeningPosition: saved, reopeningAnchorRef: ref(null),+ listData: [{ key: 'older' }, { key: 'latest' }], nearBottomRef: ref(true),+ markProgrammaticScroll: vi.fn(), dragStartOffsetYRef: ref(null),+ listRef: ref({ scrollToIndex: vi.fn(() => Promise.resolve()) }),+ scrollToEndProgrammatically: vi.fn(), reconcileReopeningAnchor: vi.fn(),+ mobileMessageHistoryRowKeyByIdentity: vi.fn(),+ lastAppliedFocusKeyRef: ref(null), userScrollForOlderRef: ref(false), lastAutoLoadEarlierKeyRef: ref(null),+ focusRunKey: focused ? `request:${focused}` : null, focusedItemKey: focused,+ };+ bindings.revealPositionedHistory = callback('if (!initialAnchorDoneRef.current || !animation)', bindings);+ bindings.scrollToIndexProgrammatically = callback('return listRef.current?.scrollToIndex', bindings);+ const layout = () => callback('if (initialAnchorDoneRef.current) return', bindings)();+ const focus = () => callback('if (!focusedItemKey || !focusRunKey)', { ...bindings, listRevealed: state.revealed })();+ return { state, bindings, layout, focus };+}++describe('message entry lifecycle', () => {+ it('positions explicit navigation first and reveals on seek completion without visiting the tail', async () => {+ const h = fixture('older');+ let finish!: () => void;+ h.bindings.listRef.current.scrollToIndex.mockReturnValueOnce(new Promise<void>(resolve => { finish = resolve; }));+ h.layout(); h.focus();+ expect(h.bindings.scrollToEndProgrammatically).not.toHaveBeenCalled();+ expect(h.bindings.listRef.current.scrollToIndex).toHaveBeenCalledExactlyOnceWith({ index: 0, viewPosition: 0.45, animated: false });+ expect(h.state.revealed).toBe(false);+ finish(); await Promise.resolve();+ expect(h.state.revealed).toBe(true);+ h.focus();+ expect(h.bindings.listRef.current.scrollToIndex).toHaveBeenCalledTimes(1);+ expect(h.bindings.nearBottomRef.current).toBe(false);+ });+ it('waits for a missing linked row without first scrolling to the latest row', async () => {+ const h = fixture('not-loaded'); h.layout(); h.focus();+ expect(h.bindings.listRef.current.scrollToIndex).not.toHaveBeenCalled();+ expect(h.bindings.scrollToEndProgrammatically).not.toHaveBeenCalled();+ h.bindings.listData.unshift({ key: 'not-loaded' });+ h.focus(); await Promise.resolve();+ expect(h.state.revealed).toBe(true);+ expect(h.bindings.listRef.current.scrollToIndex).toHaveBeenCalledTimes(1);+ });+ it('does not reveal another teammate from an old asynchronous positioning completion', async () => {+ const h = fixture('older');+ let finish!: () => void;+ h.bindings.listRef.current.scrollToIndex.mockReturnValueOnce(new Promise<void>(resolve => { finish = resolve; }));+ h.layout(); h.focus();+ h.bindings.initialRevealGenerationRef.current++;+ finish(); await Promise.resolve();+ expect(h.state.revealed).toBe(false);+ });+ it('opens normal histories at the latest row once, including a previously empty cache', () => {+ const h = fixture();+ h.bindings.listData = []; h.layout();+ expect(h.state.revealed).toBe(true);+ h.bindings.listData = [{ key: 'latest' }]; h.layout(); h.layout();+ expect(h.bindings.scrollToEndProgrammatically).toHaveBeenCalledExactlyOnceWith(false);+ expect(h.bindings.nearBottomRef.current).toBe(true);+ });+ it('restores deliberate history reading and lets an explicit link override the bookmark', () => {+ const saved = { atEnd: false, anchor: { key: 'older', viewportOffset: 24 } };+ const h = fixture(null, saved); h.layout();+ expect(h.bindings.listRef.current.scrollToIndex).toHaveBeenCalledExactlyOnceWith({ index: 0, viewPosition: 0, viewOffset: 24, animated: false });+ expect(h.bindings.scrollToEndProgrammatically).not.toHaveBeenCalled();+ const linked = fixture('latest', saved); linked.layout(); linked.focus();+ expect(linked.bindings.listRef.current.scrollToIndex).toHaveBeenCalledExactlyOnceWith({ index: 1, viewPosition: 0.45, animated: false });+ });+});++it('reconciles late attachment, composer and keyboard measurements through the production list callbacks without stealing history reading', async () => {+ const { createMobileTailFollower } = await import('@/session/messageTailFollower');+ vi.useFakeTimers();+ vi.stubGlobal('requestAnimationFrame', (fn: () => void) => setTimeout(fn, 16));+ vi.stubGlobal('cancelAnimationFrame', clearTimeout);+ try {+ const metrics = ref({ contentHeight: 1200, offsetY: 356, viewportHeight: 844 });+ const nearBottom = ref(true), readingOlder = ref(false);+ const correct = vi.fn((offset: number) => { metrics.current.offsetY = offset; });+ const follower = createMobileTailFollower({+ read: () => ({ metrics: metrics.current, stickToLatest: nearBottom.current,+ preservingHistory: readingOlder.current, userControllingScroll: false,+ layoutSettleAt: 0, animatedScrollUntil: 0 }),+ seekEnd: vi.fn(), correctOffset: correct,+ });+ const bindings = {+ scrollMetricsRef: metrics, nearBottomRef: nearBottom, readingOlderRef: readingOlder,+ historyPrependTransactionRef: ref(null),+ reconcileReopeningAnchor: vi.fn(), markMobileMvcpSettle: vi.fn(),+ getTailFollower: () => follower, runStickToLatestVerify: () => follower.reconcile(),+ };+ const resize = callback('contentHeight: height', bindings);+ const layout = callback('const viewportHeight = event.nativeEvent.layout.height', bindings);+ resize(390, 1800); // Attachment acquired dimensions after first display.+ expect(correct).toHaveBeenLastCalledWith(956);+ layout({ nativeEvent: { layout: { height: 534 } } }); // Keyboard appears.+ await vi.advanceTimersByTimeAsync(200);+ expect(correct).toHaveBeenLastCalledWith(1266);+ resize(390, 1980); // Expanded composer adds measured space to the same list.+ expect(correct).toHaveBeenLastCalledWith(1446);+ layout({ nativeEvent: { layout: { height: 844 } } });+ await vi.advanceTimersByTimeAsync(200);+ expect(correct).toHaveBeenLastCalledWith(1136);+ nearBottom.current = false;+ correct.mockClear();+ resize(390, 2280); // Later media measurement while deliberately reading older rows.+ readingOlder.current = true;+ resize(390, 3280); // History page prepend.+ layout({ nativeEvent: { layout: { height: 534 } } });+ await vi.advanceTimersByTimeAsync(200);+ expect(correct).not.toHaveBeenCalled();+ follower.reset();+ } finally { vi.useRealTimers(); vi.unstubAllGlobals(); }+});diff --git a/apps/mobile/src/__tests__/messageListVirtualization.test.ts b/apps/mobile/src/__tests__/messageListVirtualization.test.tsindex 02c7a9cf70..29f313b90c 100644--- a/apps/mobile/src/__tests__/messageListVirtualization.test.ts+++ b/apps/mobile/src/__tests__/messageListVirtualization.test.ts@@ -212,7 +212,8 @@ describe('mobile message list container', () => {const focusEffectStart = source.indexOf('// 深链/搜索:滚到指定消息');const focusEffectEnd = source.indexOf('// 新消息红点', focusEffectStart);const focusEffectSource = source.slice(focusEffectStart, focusEffectEnd);- expect(focusEffectSource).toContain('if (!listRevealed) return;');+ // Entry/focus ordering is executed in messageEntryPositioning.test.ts:+ // a linked row now positions before reveal, without a preceding tail seek.expect(focusEffectSource).toContain('userScrollForOlderRef.current = true');expect(focusEffectSource).toContain('lastAutoLoadEarlierKeyRef.current = null');});diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.tsindex c5bb8c8a46..e9f5bdbe7d 100644--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts@@ -79,7 +79,7 @@ describe('mobile optimistic composer while session is not ready', () => {expect(source).toContain('error: string | null;');expect(source).toContain('const latchOutboxTransportHold = useCallback(');expect(source).toContain('const outboxRecoverySyncHeld = hasLatchedOutboxTransportHold');- expect(source).toContain('autoRecoveringError: outboxRecoverySyncHeld,');+ expect(source).toContain('autoRecoveringError: outboxRecoverySyncHeld || !companionEntry.ready,');expect(source).toContain('setOutboxTransportHold((current) => current?.deviceId === deviceId ? null : current);');expect(source).not.toContain('autoRecoveringError: isAutoRecoveringRemoteError(connectionError),');// Desktop 断线时仍允许尝试队列编辑类动作,不把整行切成只读。diff --git a/apps/mobile/src/__tests__/remoteCollectionRead.test.tsx b/apps/mobile/src/__tests__/remoteCollectionRead.test.tsxindex f86e43aa11..6ee0f98b6a 100644--- a/apps/mobile/src/__tests__/remoteCollectionRead.test.tsx+++ b/apps/mobile/src/__tests__/remoteCollectionRead.test.tsx@@ -7,24 +7,25 @@ const h = vi.hoisted(() => ({push: vi.fn(), markRead: vi.fn(), list: vi.fn(),params: { collectionId: 'teammates', targets: JSON.stringify([{ deviceId: 'mac', deviceName: 'My Mac' }]) },translation: { t: (key: string) => key, i18n: { language: 'en' } },- link: { connectionEpoch: 1, status: 'online', presenceVersion: 1, getPresenceAvailability: () => true, invoke: vi.fn(), onRemoteResourceChanged: vi.fn((_listener: (deviceId: string, payload: { collectionId: string }) => void) => () => {}), subscribe: vi.fn(), unsubscribe: vi.fn() },- item: { ref: { collectionId: 'teammates', kind: 'bot', id: 'bot-1' }, revision: '1', display: { title: 'Writer', preview: 'Unread reply', lastReplyAt: 200 } },+ link: { connectionEpoch: 1, status: 'online', presenceVersion: 1, getPresenceAvailability: () => true, openLink: vi.fn(async () => {}), invoke: vi.fn(), onRemoteResourceChanged: vi.fn((_listener: (deviceId: string, payload: { collectionId: string }) => void) => () => {}), subscribe: vi.fn(), unsubscribe: vi.fn() },+ item: { ref: { collectionId: 'teammates', kind: 'bot', id: 'bot-1' }, revision: '1', display: { title: 'Writer', preview: 'Unread reply', lastReplyAt: 200 }, links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'chat-1' } }] },}));vi.mock('react-native', async () => {const { createElement: el, Fragment } = await import('react');const view = ({ children, testID }: any) => el('div', { 'data-testid': testID }, children);return {- View: view, ActivityIndicator: view, RefreshControl: () => null,+ View: view, ActivityIndicator: view, RefreshControl: () => null, Keyboard: { dismiss() {} },Pressable: ({ children, testID, onPress, disabled }: any) => el('button', { 'data-testid': testID, onClick: onPress, disabled }, children),- FlatList: ({ data, renderItem, ListEmptyComponent }: any) => data.length ? el(Fragment, {}, ...data.map((item: any) => el(Fragment, { key: item.key }, renderItem({ item })))) : ListEmptyComponent,+ FlatList: ({ data, renderItem, ListEmptyComponent }: any) => el('div', { 'data-list': true }, data.length ? data.map((item: any) => el(Fragment, { key: item.key }, renderItem({ item }))) : ListEmptyComponent),StyleSheet: { create: (styles: unknown) => styles },AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },};});vi.mock('expo-router', async () => {const { useEffect } = await import('react');- return { useFocusEffect: (effect: () => void | (() => void)) => useEffect(effect, [effect]), useLocalSearchParams: () => h.params, useRouter: () => ({}) };+ return { useFocusEffect: (effect: () => void | (() => void)) => useEffect(effect, [effect]), useLocalSearchParams: () => h.params, useRouter: () => ({}), useNavigation: () => ({ getState: () => ({ index: 0, routes: [] }) }) };});+vi.mock('@/session/useHomeMode', () => ({ useHomeMode: () => ({ selectTeammate: async () => {}, setMode: async () => {} }) }));vi.mock('react-i18next', () => ({ useTranslation: () => h.translation }));vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));vi.mock('react-native-safe-area-context', () => ({ SafeAreaView: 'div' }));@@ -63,7 +64,7 @@ it('opening a companion only navigates; unread survives until the destination coconst button = container.querySelector<HTMLButtonElement>('[data-testid="teammates.item.mac.bot-1"]');expect(button).not.toBeNull();await act(async () => button!.click());- expect(h.push).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/resources/[collectionId]/[resourceId]' }));+ expect(h.push).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/sessions/[sessionId]', params: expect.objectContaining({ sessionId: 'chat-1', resourceId: 'bot-1' }) }));expect(h.markRead).not.toHaveBeenCalled();} finally { act(() => root.unmount()); }});@@ -84,9 +85,13 @@ it('serializes bursts of generation pushes on the resource route and preserves tawait act(async () => settle({ items: [] }));expect(h.list).toHaveBeenCalledTimes(2);expect(container.querySelector('[data-testid="teammates.item.mac.bot-1"]')).not.toBeNull();+ const list = container.querySelector<HTMLDivElement>('[data-list]')!; list.scrollTop = 120;// A queued refresh must not issue another RPC after leaving the route.h.list.mockReturnValue(new Promise(resolve => { settle = resolve; }));await act(async () => { notify('mac', { collectionId: 'teammates' }); notify('mac', { collectionId: 'teammates' }); });+ expect(container.querySelector('[data-list]')).toBe(list);+ expect(list.scrollTop).toBe(120);+ expect(container.querySelector('[data-testid="teammates.item.mac.bot-1"]')).not.toBeNull();act(() => root.unmount());await act(async () => settle({ items: [] }));expect(h.list).toHaveBeenCalledTimes(3);diff --git a/apps/mobile/src/__tests__/sessionBottomViewport.test.ts b/apps/mobile/src/__tests__/sessionBottomViewport.test.tsindex 69b474685a..26d6b336ed 100644--- a/apps/mobile/src/__tests__/sessionBottomViewport.test.ts+++ b/apps/mobile/src/__tests__/sessionBottomViewport.test.ts@@ -61,3 +61,35 @@ it('clips the input and held card at the selected region while measuring only thexpect(viewport.getText(source)).toContain('<SessionComposerInput');}});++it('keeps the newest row above the measured phone composer, including expanded input and safe area', async () => {+ const { mobileMessageListBottomPadding, mobileMessageListEndOffset } = await import('@/session/messageScroll');+ let inset: ts.Expression | undefined;+ function visit(node: ts.Node) {+ if (ts.isJsxAttribute(node) && node.name.getText(source) === 'contentBottomInset') {+ inset = (node.initializer as ts.JsxExpression).expression;+ }+ ts.forEachChild(node, visit);+ }+ visit(source);+ expect(inset).toBeDefined();+ // Execute the actual SessionScreen prop and MessageRenderer padding helper.+ const contentInset = new Function('bottomOverlayHeight', `+ const companionInlineInteraction = false, shareSelectionActive = false,+ nativeComposerFrameAvailable = true, sessionOperationLayout = { composerSlot: 'editable' },+ MOBILE_MESSAGE_LIST_BOTTOM_PADDING = 132;+ return (${inset!.getText(source)});+ `);+ for (const keyboard of [0, 310]) for (const composer of [96, 132, 280]) for (const body of [64, 2400, 3000]) {+ const viewport = 844 - keyboard;+ const padding = mobileMessageListBottomPadding(composer, contentInset(composer));+ // LegendList alignItemsAtEnd aligns short histories; long histories use the+ // same end offset that the production tail follower verifies after resize.+ const height = Math.max(viewport, body + padding);+ const offset = mobileMessageListEndOffset({ contentHeight: height, viewportHeight: viewport, offsetY: 0 });+ const newestRowBottom = height - padding - offset;+ expect(newestRowBottom).toBe(viewport - composer);+ expect(padding).toBe(composer); // No extra gap from a fixed minimum on small inputs.+ }+ expect(contentInset(0)).toBe(132); // Only the as-yet unmeasured first layout uses the fallback.+});diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.tsindex f784c209e1..100f5e3565 100644--- a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts@@ -58,6 +58,7 @@ function fixture(reopen = false, remoteHistoryAvailable = true) {captureSessionMessageAuthority: () => ({ generation: 1 }),isSessionMessageAuthorityCurrent: () => true,upsertDeviceSession: vi.fn(),+ getSessionDeviceId: vi.fn((): string | undefined => undefined),getMessages: () => state.rows,getSessions: () => reopen ? [session] : [],captureActiveSessionSnapshotEpoch: () => 0,@@ -79,6 +80,7 @@ function fixture(reopen = false, remoteHistoryAvailable = true) {listActiveSessions: vi.fn(async () => []),};const bindings = {+ params: { resourceKind: '' }, readRouteParam: (value: string) => value, t: (key: string) => key,mobileDebugLog: vi.fn(),remoteHistoryAvailable,deviceId: 'd1', deviceName: 'test', sessionId: 's1',@@ -128,6 +130,15 @@ function fixture(reopen = false, remoteHistoryAvailable = true) {}describe('production session recovery callbacks', () => {+ it.each(['id', 'source', 'host'])('rejects a roster-linked task with the wrong %s before authorizing controls', async (mismatch) => {+ const f = fixture(); f.bindings.params.resourceKind = 'bot';+ f.maker.getSession.mockResolvedValue({ ...session, id: mismatch === 'id' ? 'other' : 's1', source: mismatch === 'source' ? 'manual' : 'bot' } as typeof session);+ if (mismatch === 'host') f.store.getSessionDeviceId.mockReturnValue('another-device');+ await expect(f.sync()).rejects.toThrow('devices.resources.noConversation');+ expect(f.store.upsertDeviceSession).not.toHaveBeenCalled();+ expect(f.bindings.setSessionMetadataSyncedKey).not.toHaveBeenCalled();+ expect(f.state.syncError).toContain('devices.resources.noConversation');+ });it('keeps cached rows offline without fetching metadata, projection, history or earlier pages', async () => {const f = fixture(true, false);const rows = f.state.rows;@@ -214,7 +225,21 @@ describe('production session recovery callbacks', () => {expect(screen).toContain('const bannerRetriesHistory = connectionRecoveryError === null && historyError !== null;');expect(screen).toContain('requestErrorAutoRecovering={bannerRetriesHistory ? false : undefined}');expect(screen).toContain('loading={loading || loadingEarlier}');- expect(screen).toMatch(/onSync=\{\(\) => bannerRetriesHistory\s+\? void loadEarlierMessages\(\)\s+: void requestSync\(/);+ let onSync: ts.Expression | undefined;+ const find = (node: ts.Node) => {+ if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(source) === 'ConnectionBanner') {+ const prop = node.attributes.properties.find(p => ts.isJsxAttribute(p) && p.name.getText(source) === 'onSync') as ts.JsxAttribute;+ onSync = (prop.initializer as ts.JsxExpression).expression;+ }+ ts.forEachChild(node, find);+ };+ find(source); if (!onSync) throw new Error('Missing banner retry');+ const loadEarlierMessages = vi.fn(), requestSync = vi.fn(), retry = vi.fn();+ const run = new Function('bannerRetriesHistory', 'companionEntry', 'loadEarlierMessages', 'requestSync', `return (${onSync.getText(source)})();`);+ run(true, { error: null, retry }, loadEarlierMessages, requestSync);+ expect(loadEarlierMessages).toHaveBeenCalledOnce(); expect(requestSync).not.toHaveBeenCalled(); expect(retry).not.toHaveBeenCalled();+ run(false, { error: 'lookup failed', retry }, loadEarlierMessages, requestSync);+ expect(retry).toHaveBeenCalledOnce(); expect(requestSync).toHaveBeenCalledExactlyOnceWith({ reason: 'manual', replaceMessages: false });const errorSources = screen.slice(screen.indexOf('const connectionError ='), screen.indexOf('const bannerError ='));expect(errorSources).not.toContain('historyError');});diff --git a/apps/mobile/src/__tests__/teammateNavigation.test.ts b/apps/mobile/src/__tests__/teammateNavigation.test.tsindex 2bf4db079e..dcca065aaf 100644--- a/apps/mobile/src/__tests__/teammateNavigation.test.ts+++ b/apps/mobile/src/__tests__/teammateNavigation.test.ts@@ -8,7 +8,8 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: {} }));import AsyncStorage from '@react-native-async-storage/async-storage';import { __testing, normalizeHomeNavigationPreferences, readHomeNavigationPreferences, saveHomeNavigationPreferences } from '@/session/homeViewPreferenceStore';-import { findLastTeammate, orderedTeammates, teammateIdentity, teammateResourceRoute } from '@/session/teammateNavigation';+import { findLastTeammate, homeDismissCount, orderedTeammates, teammateIdentity, teammateResourceRoute } from '@/session/teammateNavigation';+import { StackRouter, StackActions } from 'expo-router/build/react-navigation/routers/StackRouter';const row = (deviceId = 'mac', id = 'writer', title = 'Writer', timestamp = 100): HostedRemoteCollectionItem => ({key: `${deviceId}:${id}`, host: { deviceId, deviceName: deviceId },item: { ref: { collectionId: 'teammates', kind: 'bot', id }, revision: '1',@@ -51,9 +52,23 @@ describe('account-scoped home navigation overrides', () => {});});describe('teammate identity navigation', () => {- it('resolves every selection through a resource route, not its stale conversation link', () => {- expect(teammateResourceRoute(row(), 'en')).toEqual({ pathname: '/resources/[collectionId]/[resourceId]', params: {- collectionId: 'teammates', resourceId: 'writer', resourceKind: 'bot', deviceId: 'mac', deviceName: 'mac', title: 'Writer',+ it.each(['index', 'devices/index', 'resources/[collectionId]'])('preserves the actual %s stack entry and collection targets across repeated teammate opens', (name) => {+ const router = StackRouter({ initialRouteName: name });+ const options = { routeNames: [name, 'sessions/[sessionId]'], routeParamList: { [name]: { collectionId: 'teammates', targets: 'fixture-hosts', title: 'Teammates' } }, routeGetIdList: {}, routeKeyChanges: [] };+ let state = router.getInitialState(options);+ const home = state.routes[0];+ for (let turn = 0; turn < 3; turn++) {+ for (const sessionId of ['a', 'b']) state = router.getRehydratedState(router.getStateForAction(state, StackActions.push('sessions/[sessionId]', { sessionId }), options)!, options);+ const count = homeDismissCount(state.routes, 'teammates');+ expect(count).toBe(2);+ state = router.getRehydratedState(router.getStateForAction(state, StackActions.pop(count!), options)!, options);+ expect(state.routes).toEqual([home]);+ expect(state.routes[0]).toBe(home); // Same key and params: React retains the mounted list.+ }+ });+ it('uses the conversation as a navigation hint and retains the resource identity for revalidation', () => {+ expect(teammateResourceRoute(row(), 'en')).toEqual({ pathname: '/sessions/[sessionId]', params: {+ resourceCollectionId: 'teammates', resourceId: 'writer', resourceKind: 'bot', deviceId: 'mac', deviceName: 'mac', sessionId: 'obsolete-session',} });});it('never substitutes Cindy or another same-named host for a deleted or missing remembered teammate', () => {diff --git a/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceList.test.tsxindex 53050125e8..5f60815f06 100644--- a/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx+++ b/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx@@ -4,14 +4,14 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { HostedRemoteCollectionItem, RemoteResourceHostTarget } from '@/device-link/remoteResources';const h = vi.hoisted(() => ({- auth: { user: { id: 'owner' }, accountGeneration: 1 },+ 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() },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('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (effect: () => void | (() => void)) => useEffect(effect, [effect]) }; });+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('react-i18next', () => ({ useTranslation: () => h.translation }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));@@ -37,7 +37,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 = [];+ vi.clearAllMocks(); 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: {} }));@@ -152,3 +152,29 @@ it('drops queued invalidations when the picker closes', async () => {expect(h.list).toHaveBeenCalledTimes(2);expect(result.items).toEqual([]);});++it('retains loaded rows and an empty result on return while refreshing in the background', async () => {+ h.list.mockResolvedValue({ items: [item('visible')] });+ await render();+ const previous = result.items;+ h.focused = false; await render();+ let finish!: (value: unknown) => void;+ h.list.mockReturnValue(new Promise(resolve => { finish = resolve; }));+ h.focused = true; await render();+ expect(result.items).toBe(previous); expect(result.loading).toBe(false); expect(result.syncing).toBe(true);+ expect(result.refreshing).toBe(false);+ await act(async () => finish({ items: [] }));+ expect(result.items).toEqual([]); expect(result.loading).toBe(false);+ h.focused = false; await render();+ h.list.mockReturnValue(new Promise(() => {}));+ h.focused = true; await render();+ expect(result.items).toEqual([]); expect(result.loading).toBe(false); expect(result.syncing).toBe(true);+});+it('shows disk-cached rows during the first slow network read without claiming authority', async () => {+ h.cached = [cached(targets[0], 'cached-visible')];+ h.list.mockReturnValue(new Promise(() => {}));+ await render();+ expect(result.items[0].item.ref.id).toBe('cached-visible');+ expect(result.loading).toBe(false); expect(result.syncing).toBe(true);+ expect(result.isOnline(targets[0])).toBe(false);+});diff --git a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsxindex 961476d364..095e0b6537 100644--- a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx+++ b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx@@ -8,25 +8,29 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const h = vi.hoisted(() => ({get: vi.fn(),- language: "en",+ language: "en", focused: true,+ t: (key: string) => key, metadataVerified: true,+ resourceId: 'bot-1', sessionId: 'task-1',markRead: vi.fn(),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() },}));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: h.language } }) }));+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 () => {const { useEffect } = await import('react');return {- useFocusEffect: (effect: () => void | (() => void)) => useEffect(effect, [effect]),- useLocalSearchParams: () => ({ resourceCollectionId: 'teammates', resourceId: 'bot-1', resourceKind: 'bot' }),+ useIsFocused: () => h.focused,+ useFocusEffect: (effect: () => void | (() => void)) => useEffect(() => h.focused ? effect() : undefined, [effect, h.focused]),+ useLocalSearchParams: () => ({ resourceCollectionId: 'teammates', resourceId: h.resourceId, resourceKind: 'bot' }),useRouter: () => h.router,};});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/remoteResources', () => ({ getRemoteResource: h.get }));vi.mock('@/device-link/remoteResourceCache', () => ({ markRemoteResourceRead: h.markRead }));vi.mock('@/device-link/focusedTopicSubscription', () => ({ startFocusedTopicSubscription: () => () => {} }));@@ -56,17 +60,19 @@ function screenReadGate(contentRecoveryKey: string | null, contentSyncedKey: str`)(contentRecoveryKey, contentSyncedKey);}Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+let result: ReturnType<typeof useRemoteResourceSession>;let root: Root | undefined;let container: HTMLDivElement;function Probe({ canMarkRead }: { canMarkRead: boolean }) {- const resource = useRemoteResourceSession('mac', 'My Mac', 'task-1', canMarkRead);+ result = useRemoteResourceSession('mac', 'My Mac', h.sessionId, canMarkRead, h.metadataVerified);+ const { resource } = result;return typeof resource?.display.title === 'string' ? resource.display.title : null;}async function render(canMarkRead = false) {if (!root) { container = document.createElement('div'); root = createRoot(container); }await act(async () => root!.render(createElement(Probe, { canMarkRead })));}-beforeEach(() => { vi.clearAllMocks(); h.auth.accountGeneration = 1; h.language = "en"; h.store.getSessionDeviceId.mockReturnValue(undefined); });+beforeEach(() => { vi.clearAllMocks(); 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; });describe('companion task visibility refresh', () => {@@ -140,3 +146,131 @@ it.each(['zh-CN', 'zh-TW', 'en', 'ja', 'ko'])('sends the viewing locale %s and rexpect(h.get.mock.calls.at(-1)?.[3]).toBe(h.language);expect(container.textContent).toBe(h.language);});++it('shows the clicked identity immediately but waits for resource and session validation before read/control readiness', async () => {+ const { readRemoteCollectionCache, writeRemoteCollectionCache } = await import('@/device-link/remoteResourceAvailability');+ const owner = 'owner:1';+ readRemoteCollectionCache(owner, 'teammates');+ writeRemoteCollectionCache(owner, 'teammates', [{ key: 'fixture', host: { deviceId: 'mac', deviceName: 'My Mac' }, item: {+ ref: { collectionId: 'teammates', id: 'bot-1', kind: 'bot' }, revision: 'cached', display: { title: 'Cached teammate' },+ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }],+ } }]);+ let finish!: (value: unknown) => void;+ h.metadataVerified = false;+ h.get.mockReturnValue(new Promise(resolve => { finish = resolve; }));+ await render(true);+ expect(container.textContent).toBe('Cached teammate');+ expect(result.ready).toBe(false);+ expect(h.markRead).not.toHaveBeenCalled();+ await act(async () => finish({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }], display: { title: 'Cached teammate', lastReplyAt: 42 } }));+ expect(result.ready).toBe(false);+ h.metadataVerified = true; await render(true);+ expect(result.ready).toBe(true);+ expect(h.markRead).toHaveBeenCalledExactlyOnceWith('owner', 'mac', 'bot-1', 42);+ expect(h.get).toHaveBeenCalledTimes(1);+ expect(h.link.invoke).not.toHaveBeenCalled(); // Session metadata is the screen's existing read.+});+it('does not refetch the profile when history becomes readable', async () => {+ h.get.mockResolvedValue({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }], display: { title: 'Teammate', lastReplyAt: 12 } });+ 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'));+ await render(true);+ 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());+ expect(result.ready).toBe(true); expect(result.error).toBe(null);+ expect(h.router.replace).not.toHaveBeenCalled();+});+it('does not allow a changed canonical link to authorize the old conversation', async () => {+ h.get.mockResolvedValue({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-2' } }], display: { title: 'Teammate' } });+ h.link.invoke.mockResolvedValue({ id: 'task-2', source: 'bot' });+ await render(true);+ expect(result.ready).toBe(false);+ expect(h.router.setParams).toHaveBeenCalledWith({ sessionId: 'task-2' });+ expect(h.markRead).not.toHaveBeenCalled();+});++it('revalidates on refocus without blanking the identity and keeps controls closed during the read', async () => {+ h.get.mockResolvedValue({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }], display: { title: 'Teammate' } });+ await render(false); expect(result.ready).toBe(true);+ h.focused = false; await render(false); expect(result.ready).toBe(false);+ h.get.mockReturnValue(new Promise(() => {}));+ h.focused = true; await render(false);+ expect(container.textContent).toBe('Teammate'); expect(result.ready).toBe(false);+ expect(h.get).toHaveBeenCalledTimes(2);+});+it('never exposes a cached prior-account identity while the new account lookup is pending', async () => {+ h.get.mockResolvedValue({ links: [], display: { title: 'Old account' } });+ await render(false);+ h.auth.accountGeneration++; h.get.mockReturnValue(new Promise(() => {}));+ await render(false);+ expect(container.textContent).toBe(''); expect(result.ready).toBe(false);+});+it('keeps invitation preparation in its existing recovery screen, with no controls or read receipt', async () => {+ h.get.mockResolvedValue({ links: [], display: { title: 'Preparing' }, blocks: [{ id: 'invitation', primitive: 'status', data: { stage: 'skills' } }] });+ await render(true);+ expect(result.ready).toBe(false); expect(h.markRead).not.toHaveBeenCalled();+ expect(h.router.replace).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/resources/[collectionId]/[resourceId]' }));+});++it('drops a late response when switching companions and fences a disconnected/reconnected entry', async () => {+ let finish!: (value: unknown) => void;+ h.get.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));+ await render(true);+ h.resourceId = 'bot-2'; h.sessionId = 'task-2';+ h.get.mockResolvedValue({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-2' } }], display: { title: 'Second' } });+ await render(true); expect(container.textContent).toBe('Second'); expect(result.ready).toBe(true);+ await act(async () => finish({ links: [], display: { title: 'First' } }));+ expect(container.textContent).toBe('Second'); expect(h.router.replace).not.toHaveBeenCalled();+ h.link.status = 'offline'; await render(true);+ expect(container.textContent).toBe('Second'); expect(result.ready).toBe(false);+ h.link.status = 'online'; h.link.connectionEpoch++; h.get.mockReturnValue(new Promise(() => {}));+ await render(true); expect(result.ready).toBe(false);+});++it.each([false, true])('wires entry readiness=%s to production composer, realtime controls and outbox gates', 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));+ ts.forEachChild(node, visit);+ };+ visit(screen);+ const 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 status = 'online', targetAvailableForDispatch = true, isDeviceUnresponsive = false, outboxRecoverySyncHeld = false, loading = false;+ ${code}+ return { canUseComposer, remoteRealtimeControlsUnavailable, outboxConnectionState };+ `)(ready);+ expect(gates.canUseComposer).toBe(ready);+ expect(gates.remoteRealtimeControlsUnavailable).toBe(!ready);+ expect(gates.outboxConnectionState.autoRecoveringError).toBe(!ready);+});++it('closes controls immediately on a resource push, keeps the title, and coalesces revalidation', async () => {+ vi.useFakeTimers();+ try {+ h.get.mockResolvedValue({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }], display: { title: 'Teammate' } });+ await render();+ expect(result.ready).toBe(true);+ const changed = (h.link.onRemoteResourceChanged.mock.calls as unknown as Array<[(device: string, payload: object) => void]>)[0][0];+ let finish!: (resource: unknown) => void;+ h.get.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));+ act(() => {+ changed('mac', { collectionId: 'teammates' });+ changed('mac', { collectionId: 'teammates' });+ });+ expect(result.ready).toBe(false);+ expect(container.textContent).toBe('Teammate');+ expect(h.get).toHaveBeenCalledTimes(1);+ await act(async () => vi.advanceTimersByTime(300));+ expect(h.get).toHaveBeenCalledTimes(2);+ expect(result.ready).toBe(false);+ await act(async () => finish({ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'task-1' } }], display: { title: 'Teammate' } }));+ expect(result.ready).toBe(true);+ } finally { vi.useRealTimers(); }+});diff --git a/apps/mobile/src/__tests__/useTeammateNavigation.test.tsx b/apps/mobile/src/__tests__/useTeammateNavigation.test.tsxindex 4dc855ce5f..4762deb2c8 100644--- a/apps/mobile/src/__tests__/useTeammateNavigation.test.tsx+++ b/apps/mobile/src/__tests__/useTeammateNavigation.test.tsx@@ -4,11 +4,11 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { MobileUser } from '@/auth/AuthContext';const h = vi.hoisted(() => ({- disk: new Map<string, string>(), push: vi.fn(), dismissTo: vi.fn(), accountGeneration: 1,+ disk: new Map<string, string>(), push: vi.fn(), dismissTo: vi.fn(), dismiss: vi.fn(), accountGeneration: 1,user: { id: 'account', passportId: 'passport', membershipKind: 'personal', orgId: null } as MobileUser,- get: vi.fn(), set: vi.fn(),+ get: vi.fn(), set: vi.fn(), routes: [] as Array<{ name: string; params?: unknown }>,}));-vi.mock('expo-router', () => ({ useRouter: () => ({ dismissTo: h.dismissTo }) }));+vi.mock('expo-router', () => ({ useRouter: () => ({ dismissTo: h.dismissTo, dismiss: h.dismiss }), useNavigation: () => ({ getState: () => ({ routes: h.routes, index: h.routes.length - 1 }) }) }));vi.mock('react-native', () => ({ Keyboard: { dismiss() {} } }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'en' } }) }));vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: h.user, accountGeneration: h.accountGeneration }) }));@@ -28,7 +28,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.disk.clear(); h.accountGeneration = ++serial;+ vi.clearAllMocks(); 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); });@@ -135,3 +135,25 @@ describe('header/home shared navigation', () => {expect(result.saveFailed).toBe(true); expect(h.push).not.toHaveBeenCalled();});});++it.each([+ { routes: [{ name: 'index' }, { name: 'sessions/[sessionId]' }], href: '/' },+ { routes: [{ name: 'devices/index' }, { name: 'sessions/[sessionId]' }], href: '/devices' },+ { routes: [{ name: 'resources/[collectionId]', params: { collectionId: 'teammates' } }, { name: 'sessions/[sessionId]' }], href: '/resources/teammates' },+])('returns to the mounted list at $href instead of replacing the chat with a new home', async ({ routes, href }) => {+ h.routes = routes;+ await render();+ await act(async () => result.chooseMode('teammates'));+ expect(h.dismiss).toHaveBeenCalledExactlyOnceWith(1);+ expect(h.dismissTo).not.toHaveBeenCalled();+});+it('opens a known conversation directly and seeds its first-frame identity', async () => {+ const { readRemoteCollectionCache } = await import('@/device-link/remoteResourceAvailability');+ const linked = { ...teammate, item: { ...teammate.item, links: [{ rel: 'conversation', target: { kind: 'session' as const, sessionId: 'chat' } }] } };+ await render();+ await act(async () => result.openTeammate(linked));+ expect(h.push).toHaveBeenCalledExactlyOnceWith({ pathname: '/sessions/[sessionId]', params: {+ sessionId: 'chat', deviceId: 'mac', deviceName: 'My Mac', resourceCollectionId: 'teammates', resourceId: 'writer', resourceKind: 'bot',+ } });+ expect(readRemoteCollectionCache(`${h.user.id}:${h.accountGeneration}`, 'teammates')[0]).toBe(linked);+});diff --git a/apps/mobile/src/__tests__/useTeammateRoster.test.tsx b/apps/mobile/src/__tests__/useTeammateRoster.test.tsxindex 5172e4e9d8..8863ce1108 100644--- a/apps/mobile/src/__tests__/useTeammateRoster.test.tsx+++ b/apps/mobile/src/__tests__/useTeammateRoster.test.tsx@@ -6,7 +6,7 @@ const h = vi.hoisted(() => ({auth: { user: { id: 'owner' }, accountGeneration: 1 }, revoked: new Set<string>(),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: [], loading: false, refreshing: false, error: null, isOnline: vi.fn(() => true), refresh: 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('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (effect: any) => useEffect(effect, [effect]) }; });@@ -25,7 +25,7 @@ let result: ReturnType<typeof useTeammateRoster>;function Probe() { result = useTeammateRoster(); return null; }async function render() { root ??= createRoot(document.createElement('div')); await act(async () => root!.render(createElement(Probe))); }beforeEach(() => {- vi.clearAllMocks(); h.link.openLink.mockResolvedValue(undefined); h.link.status = 'online'; h.link.connectionEpoch = 1; h.auth.accountGeneration = 1;+ 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.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' }] } : {}) }] }));@@ -60,3 +60,15 @@ it('does not request the manifest until the host link is established', async ()expect(result.targets.map(host => host.deviceId)).toEqual(['old', 'new']);expect(result.createTargets.map(host => host.deviceId)).toEqual(['new']);});++it('shows cached teammates while host discovery is pending, then removes revoked hosts', async () => {+ h.list.items = [{ key: 'old:bot', host: { deviceId: 'old', deviceName: 'Old' }, item: {+ ref: { collectionId: 'teammates', kind: 'bot', id: 'bot' }, revision: '1', display: { title: 'Cached' }, links: [],+ } }];+ h.link.readDeviceList.mockReturnValue(new Promise(() => {}));+ 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);+ h.revoked = new Set(['old']); await render();+ expect(result.items).toEqual([]);+});diff --git a/apps/mobile/src/device-link/remoteResourceAvailability.ts b/apps/mobile/src/device-link/remoteResourceAvailability.tsindex 12b5e89776..3c678245c6 100644--- a/apps/mobile/src/device-link/remoteResourceAvailability.ts+++ b/apps/mobile/src/device-link/remoteResourceAvailability.ts@@ -19,6 +19,10 @@ export function readRemoteCollectionCache(owner: string, collectionId: string):return collections.get(collectionId) ?? [];}+export function hasRemoteCollectionCache(owner: string, collectionId: string): boolean {+ return owner === cacheOwner && collections.has(collectionId);+}+export function writeRemoteCollectionCache(owner: string, collectionId: string, items: HostedRemoteCollectionItem[]): void {if (owner !== cacheOwner) return;collections.set(collectionId, items);diff --git a/apps/mobile/src/session/CompanionHeader.tsx b/apps/mobile/src/session/CompanionHeader.tsxindex 3a402647fe..f6c54484a7 100644--- a/apps/mobile/src/session/CompanionHeader.tsx+++ b/apps/mobile/src/session/CompanionHeader.tsx@@ -16,12 +16,12 @@ import { useTeammateNavigation } from './useTeammateNavigation';const AVATAR_SIZE = 32;export function CompanionHeader(props: {- resource: RemoteResource; deviceId: string; deviceName: string; online: boolean; onSearch(): void; onOpenNavigation(): void;+ resource: RemoteResource; deviceId: string; deviceName: string; online: boolean; controlsReady?: boolean; onSearch(): void; onOpenNavigation(): void;}) {const { accountGeneration } = useAuth();return <CompanionHeaderContent key={accountGeneration} {...props} />;}-function CompanionHeaderContent({ resource, deviceId, deviceName, online, onSearch, onOpenNavigation }: Parameters<typeof CompanionHeader>[0]) {+function CompanionHeaderContent({ resource, deviceId, deviceName, online, controlsReady = true, onSearch, onOpenNavigation }: Parameters<typeof CompanionHeader>[0]) {const { t, i18n } = useTranslation();const { colors } = useTheme();const styles = useThemedStyles(makeStyles);@@ -44,7 +44,7 @@ function CompanionHeaderContent({ resource, deviceId, deviceName, online, onSear<Text numberOfLines={1} style={styles.name}>{name}</Text><ChevronDown size={iconSize.sm} color={colors.textSecondary} /></Pressable>- <HomeHeaderGlassButton testID="companion.settings" accessibilityLabel={t('devices.companionProfile.settingsTitle')} onPress={() => setProfile(true)}>+ <HomeHeaderGlassButton testID="companion.settings" disabled={!controlsReady} accessibilityLabel={t('devices.companionProfile.settingsTitle')} onPress={() => setProfile(true)}><Settings2 size={iconSize.lg} strokeWidth={iconStroke.regular} color={colors.textPrimary} /></HomeHeaderGlassButton></View>diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 97f84311b6..d51cefb440 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -1113,10 +1113,10 @@ export function MessageRenderer({void listRef.current?.scrollToOffset({ animated, offset });}, [markProgrammaticScroll]);- const scrollToIndexProgrammatically = useCallback((index: number, viewPosition: number) => {+ const scrollToIndexProgrammatically = useCallback((index: number, viewPosition: number, animated = true) => {dragStartOffsetYRef.current = null;- markProgrammaticScroll(true);- void listRef.current?.scrollToIndex({ animated: true, index, viewPosition });+ markProgrammaticScroll(animated);+ return listRef.current?.scrollToIndex({ animated, index, viewPosition });}, [markProgrammaticScroll]);const getCurrentHistoryTopOffsetAdjustment = useCallback(() => {@@ -2495,7 +2495,12 @@ export function MessageRenderer({? mobileMessageHistoryRowKeyByIdentity(listData, saved.anchor.identityKey) ?? saved.anchor.key: saved?.anchor?.key;const savedIndex = savedKey ? listData.findIndex(item => item.key === savedKey) : -1;- if (saved && !saved.atEnd && savedIndex >= 0) {+ if (focusedItemKeyRef.current) {+ // Explicit message navigation owns the first position, even if its row is+ // still being fetched. Do not seek the tail and then jump back to history.+ nearBottomRef.current = false;+ setIsAwayFromBottom(true);+ } else if (saved && !saved.atEnd && savedIndex >= 0) {reopeningAnchorRef.current = { anchor: saved.anchor!, expires: Date.now() + 1500, corrections: 0 };nearBottomRef.current = false;setIsAwayFromBottom(true);@@ -2574,7 +2579,6 @@ export function MessageRenderer({lastAppliedFocusKeyRef.current = null;return;}- if (!listRevealed) return;if (lastAppliedFocusKeyRef.current === focusRunKey) return;const index = listData.findIndex((item) => item.key === focusedItemKey);if (index < 0) return;@@ -2586,12 +2590,20 @@ export function MessageRenderer({lastAutoLoadEarlierKeyRef.current = null;nearBottomRef.current = false;setIsAwayFromBottom(true);- scrollToIndexProgrammatically(index, 0.45);+ const generation = initialRevealGenerationRef.current;+ // Initial navigation lands without an animated trip across unrelated rows.+ // Reveal on the list's positioning completion, not a fixed waiting period.+ void Promise.resolve(scrollToIndexProgrammatically(index, 0.45, listRevealed && !initialRevealAnimationRef.current)).then(() => {+ if (initialRevealGenerationRef.current === generation && lastAppliedFocusKeyRef.current === focusRunKey) {+ revealPositionedHistory();+ }+ }, () => { /* The existing bounded reveal fallback handles a failed native seek. */ });}, [focusRunKey,focusedItemKey,listData,listRevealed,+ revealPositionedHistory,scrollToIndexProgrammatically,]);diff --git a/apps/mobile/src/session/TeammateHomeScreen.tsx b/apps/mobile/src/session/TeammateHomeScreen.tsxindex ecb98daa3c..18b667d32b 100644--- a/apps/mobile/src/session/TeammateHomeScreen.tsx+++ b/apps/mobile/src/session/TeammateHomeScreen.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';-import { ActivityIndicator, Alert, Keyboard, StyleSheet, View } from 'react-native';+import { Alert, Keyboard, StyleSheet, View } from 'react-native';import { Stack, useIsFocused } from 'expo-router';import { Menu } from 'lucide-react-native';import { SafeAreaView } from 'react-native-safe-area-context';@@ -82,7 +82,6 @@ export function TeammateHomeScreen({ active = true }: { active?: boolean }) {onInteract={() => { resumed.current = true; }} onCreated={(host, ref) => { void navigation.openCreatedTeammate(host, ref); }} /> : null}</View></View>- {roster.loading ? <ActivityIndicator color={colors.textSecondary} /> : null}{navigation.saveFailed ? <Text accessibilityRole="alert" style={styles.notice}>{t('devices.companions.preferenceSaveFailed')}</Text> : null}<TeammateList key={searchEpoch} {...roster} current={navigation.lastTeammate} autoFocusSearch={searchEpoch > 0}onInteract={() => { resumed.current = true; }}diff --git a/apps/mobile/src/session/teammateNavigation.ts b/apps/mobile/src/session/teammateNavigation.tsindex d20112b8c7..d236ebdb02 100644--- a/apps/mobile/src/session/teammateNavigation.ts+++ b/apps/mobile/src/session/teammateNavigation.ts@@ -17,6 +17,18 @@ export function findLastTeammate(last: LastTeammateIdentity | null, items: readoreturn items.find((item) => sameTeammate(last, teammateIdentity(item))) ?? null;}export function teammateResourceRoute(hosted: HostedRemoteCollectionItem, locale: string) {+ const conversation = hosted.item.links.find(link => link.rel === 'conversation')?.target;+ // The link is a display/navigation hint only. The destination revalidates the+ // permanent resource before allowing sends, controls or read receipts.+ if (hosted.item.ref.kind === 'bot' && conversation?.kind === 'session') return {+ pathname: '/sessions/[sessionId]' as const,+ params: {+ sessionId: conversation.sessionId,+ deviceId: hosted.host.deviceId, deviceName: hosted.host.deviceName,+ resourceCollectionId: hosted.item.ref.collectionId,+ resourceId: hosted.item.ref.id, resourceKind: hosted.item.ref.kind,+ },+ };return {pathname: '/resources/[collectionId]/[resourceId]' as const,params: {@@ -27,6 +39,17 @@ export function teammateResourceRoute(hosted: HostedRemoteCollectionItem, locale},};}++/** Reuse the actual home route, including legacy collection entry points. */+export function homeDismissCount(routes: readonly { name: string; params?: unknown }[], mode: string): number | null {+ for (let index = routes.length - 1; index >= 0; index--) {+ const route = routes[index];+ if (route.name === 'devices/index' || route.name === 'index'+ || (mode === 'teammates' && route.name === 'resources/[collectionId]'+ && (route.params as { collectionId?: string } | undefined)?.collectionId === 'teammates')) return routes.length - 1 - index;+ }+ return null;+}export function orderedTeammates(items: readonly HostedRemoteCollectionItem[], query: string, locale: string) {const needle = query.normalize('NFKC').trim().toLocaleLowerCase(locale);const unique = new Map<string, HostedRemoteCollectionItem>();diff --git a/apps/mobile/src/session/useRemoteResourceList.ts b/apps/mobile/src/session/useRemoteResourceList.tsindex 0d593a0c8a..177e236cf7 100644--- a/apps/mobile/src/session/useRemoteResourceList.ts+++ b/apps/mobile/src/session/useRemoteResourceList.ts@@ -9,7 +9,7 @@ import {cacheRemoteResourceItems, readRemoteResourceSnapshot,remoteResourceCacheRevision, subscribeRemoteResourceCache,} from '@/device-link/remoteResourceCache';-import { remoteResourceConnectionState, isRemoteResourceHostOnline, readRemoteCollectionCache, writeRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';+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';@@ -29,8 +29,8 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Reconst [hydrated, setHydrated] = useState('');const [state, setState] = useState<{binding: string; items: HostedRemoteCollectionItem[]; replies: Record<string, number>;- loading: boolean; refreshing: boolean; error: string | null;- }>(() => ({ binding, items: readRemoteCollectionCache(owner, collectionId), replies: {}, loading: true, refreshing: false, error: null }));+ settled: boolean; loading: boolean; refreshing: boolean; error: string | null;+ }>(() => ({ 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 presenceKey = targets.map((target) => `${target.deviceId}:${getPresenceAvailability(target.deviceId)}`).join('|');@@ -39,7 +39,7 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Regeneration.current += 1;let cancelled = false;const cached = readRemoteCollectionCache(owner, collectionId);- setState({ binding, items: cached, replies: {}, loading: true, refreshing: false, error: null });+ setState({ binding, items: cached, replies: {}, settled: hasRemoteCollectionCache(owner, collectionId), loading: true, refreshing: false, error: null });const cacheRead = startBoundedStartupRead(readRemoteResourceSnapshot(user?.id ?? ''), { home: [], items: {}, read: {} });// A slow local cache must not hold up live reads. A late cache never replaces a fresh roster.void cacheRead.initial.then(({ value: snapshot }) => {@@ -80,7 +80,7 @@ export function useRemoteResourceList(collectionId: string, targets: readonly ResetState((old) => {const items = mergeRemoteCollectionHostShards(old.items, next, succeeded, targets);return { binding, items, replies: Object.fromEntries([...succeeded].map((id) => [id, connectionEpoch])),- loading: false, refreshing: false,+ settled: true, loading: false, refreshing: false,error: failures.length ? failures.slice(0, 2).join('\n') : targets.length ? null : t('devices.resources.noHosts') };});}, [binding, collectionId, connectionEpoch, enabled, getPresenceAvailability, hydrated, i18n.language, invoke, openLink, presenceKey, status, t, targets]);@@ -118,7 +118,8 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Re), [connectionEpoch, getPresenceAvailability, ownState, presenceKey, state.replies, status]);return {items: ownState ? state.items : [],- loading: !ownState || state.loading || hydrated !== binding,+ loading: !ownState || (!state.settled && state.items.length === 0 && (state.loading || hydrated !== binding)),+ syncing: !ownState || state.loading || hydrated !== binding,refreshing: ownState && state.refreshing,error: ownState ? state.error : null,isOnline, refresh,diff --git a/apps/mobile/src/session/useRemoteResourceSession.ts b/apps/mobile/src/session/useRemoteResourceSession.tsindex 7e27181425..9ec0107c1b 100644--- a/apps/mobile/src/session/useRemoteResourceSession.ts+++ b/apps/mobile/src/session/useRemoteResourceSession.ts@@ -1,32 +1,50 @@-import { useCallback, useRef, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import type { RemoteResource } from '@cindy/device-link';import { AppState } from 'react-native';-import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';+import { useFocusEffect, useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';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 { markRemoteResourceRead } from '@/device-link/remoteResourceCache';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';import { remoteSessionStore } from './remoteSessionStore';import type { RemoteSession } from './types';/** Follow a companion's current host-owned task on focus/reconnect, retaining its permanent identity. */-export function useRemoteResourceSession(deviceId: string, deviceName: string, sessionId: string, canMarkRead: boolean): RemoteResource | null {+export function useRemoteResourceSession(deviceId: string, deviceName: string, sessionId: string, canMarkRead: boolean, metadataVerified = false) {const params = useLocalSearchParams<{ resourceCollectionId?: string; resourceId?: string; resourceKind?: string }>();const collectionId = typeof params.resourceCollectionId === 'string' ? params.resourceCollectionId : '';const resourceId = typeof params.resourceId === 'string' ? params.resourceId : '';const resourceKind = typeof params.resourceKind === 'string' ? params.resourceKind : '';const { invoke, connectionEpoch, status, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();const { user, accountGeneration } = useAuth();- const { i18n } = useTranslation();+ const { t, i18n } = useTranslation();const router = useRouter();+ const focused = useIsFocused();const identity = JSON.stringify([accountGeneration, deviceId, sessionId, collectionId, resourceKind, resourceId]);const [display, setDisplay] = useState<{ identity: string; resource: RemoteResource } | null>(null);- const binding = JSON.stringify([identity, connectionEpoch, canMarkRead, i18n.language]);+ const binding = JSON.stringify([identity, connectionEpoch, i18n.language]);const current = useRef(binding); current.current = binding;+ const required = !!(collectionId && resourceId && resourceKind && deviceId);+ const [verified, setVerified] = useState<string | null>(null);+ const [failure, setFailure] = useState<{ binding: string; message: string } | null>(null);+ const [attempt, setAttempt] = useState(0);+ const retry = useCallback(() => setAttempt(value => value + 1), []);+ const 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 ready = !required || (focused && AppState.currentState === 'active' && status === 'online' && verified === binding && metadataVerified);+ useEffect(() => {+ if (ready && canMarkRead && resourceKind === 'bot' && resource) {+ void markRemoteResourceRead(user?.id ?? '', deviceId, resourceId, resource.display.lastReplyAt ?? 0);+ }+ }, [canMarkRead, deviceId, ready, resource, resourceId, resourceKind, user?.id]);useFocusEffect(useCallback(() => {if (!collectionId || !resourceId || !resourceKind || !deviceId || status !== 'online') return;+ setVerified(null);let disposed = false;let generation = 0;let timer: ReturnType<typeof setTimeout> | undefined;@@ -39,20 +57,33 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, sif (!valid()) return;// Reuse this existing read rather than issuing a second profile request per turn.setDisplay({ identity, resource });+ setFailure(null);+ const stage = (resource.blocks?.find(block => block.id === 'invitation' && block.primitive === 'status')?.data as { stage?: string } | undefined)?.stage;+ if (stage && stage !== 'ready') {+ setVerified(null);+ router.replace({ pathname: '/resources/[collectionId]/[resourceId]', params: {+ collectionId, resourceId, resourceKind, deviceId, deviceName,+ } });+ return;+ }const target = resource.links.find((link) => link.rel === 'conversation')?.target;- if (target?.kind !== 'session') return;+ if (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]);- if (!valid() || !session || session.id !== target.sessionId || (resourceKind === 'bot' && session.source !== 'bot')) return;+ 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);- if (prior && prior !== deviceId) return;+ if (prior && prior !== deviceId) throw new Error(t('devices.resources.noConversation'));remoteSessionStore.upsertDeviceSession(deviceId, deviceName, session);router.setParams({ sessionId: session.id });return; // The replacement task must mount and finish its own message sync first.}- if (canMarkRead && resourceKind === 'bot') void markRemoteResourceRead(user?.id ?? '', deviceId, resourceId, resource.display.lastReplyAt ?? 0);+ setVerified(binding);} catch (error) {if (!valid()) return;+ setVerified(null);+ setFailure({ binding, message: formatRemoteError(error) });const code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;if (code === 'NOT_FOUND' || /\[NOT_FOUND\]/.test(String(error))) {setDisplay(null);@@ -68,12 +99,14 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, sconst 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);});const offTopic = startFocusedTopicSubscription({ deviceId, owner: `resource-session:${sessionId}`, topic: 'sessions', subscribe, unsubscribe });- const appState = AppState.addEventListener('change', (state) => { generation += 1; if (state === 'active') void load(); });+ const appState = AppState.addEventListener('change', (state) => { generation += 1; setVerified(null); if (state === 'active') void load(); });void load();- return () => { disposed = true; offPush(); offTopic(); appState.remove(); if (timer) clearTimeout(timer); };- }, [binding, canMarkRead, collectionId, deviceId, deviceName, identity, invoke, i18n.language, onRemoteResourceChanged, resourceId, resourceKind, router, sessionId, status, subscribe, unsubscribe, user?.id]));- return display?.identity === identity ? display.resource : null;+ return () => { disposed = true; setVerified(null); offPush(); offTopic(); appState.remove(); if (timer) clearTimeout(timer); };+ }, [attempt, binding, collectionId, deviceId, deviceName, identity, invoke, i18n.language, onRemoteResourceChanged, resourceId, resourceKind, router, sessionId, status, subscribe, t, unsubscribe, user?.id]));+ return { resource, ready, error: failure?.binding === binding ? failure.message : null, retry };}diff --git a/apps/mobile/src/session/useTeammateNavigation.ts b/apps/mobile/src/session/useTeammateNavigation.tsindex c59a93931e..a672f3905c 100644--- a/apps/mobile/src/session/useTeammateNavigation.ts+++ b/apps/mobile/src/session/useTeammateNavigation.ts@@ -1,5 +1,5 @@import { useCallback, useEffect, useRef } from 'react';-import { useRouter } from 'expo-router';+import { useNavigation, useRouter } from 'expo-router';import { Keyboard } from 'react-native';import { useTranslation } from 'react-i18next';import { useAuth } from '@/auth/AuthContext';@@ -8,15 +8,17 @@ import type { HostedRemoteCollectionItem, RemoteResourceHostTarget } from '@/devimport { useGuardedPush } from '@/utils/useGuardedPush';import { useHomeMode } from './useHomeMode';import type { HomeMode } from './homeViewPreferenceStore';-import { teammateIdentity, teammateResourceRoute } from './teammateNavigation';+import { homeDismissCount, teammateIdentity, teammateResourceRoute } from './teammateNavigation';+import { readRemoteCollectionCache, writeRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';-/** Public header integration. Push keeps the current chat/composer mounted; resolver replaces only its own route. */+/** Push keeps the current chat/composer mounted; known teammates validate in the destination. */export function useTeammateNavigation() {const preferences = useHomeMode();- const { accountGeneration } = useAuth();+ const { user, accountGeneration } = useAuth();const { i18n } = useTranslation();const push = useGuardedPush();const router = useRouter();+ const navigation = useNavigation();const current = useRef(accountGeneration); current.current = accountGeneration;const pendingAccount = useRef<number | null>(null);const mounted = useRef(true);@@ -27,9 +29,15 @@ export function useTeammateNavigation() {Keyboard.dismiss();try {await preferences.setMode(mode);- if (mounted.current && current.current === accountGeneration) router.dismissTo('/devices');+ if (mounted.current && current.current === accountGeneration) {+ const state = navigation.getState();+ const count = homeDismissCount(state?.routes.slice(0, state.index + 1) ?? [], mode);+ // Pop by position: dismissTo would overwrite a legacy collection's target params.+ if (count === null) router.dismissTo('/devices');+ else if (count > 0) router.dismiss(count);+ }} finally { if (pendingAccount.current === accountGeneration) pendingAccount.current = null; }- }, [accountGeneration, preferences.setMode, router]);+ }, [accountGeneration, navigation, preferences.setMode, router]);const openTeammate = useCallback(async (hosted: HostedRemoteCollectionItem) => {const identity = teammateIdentity(hosted);if (!identity || pendingAccount.current === accountGeneration) return;@@ -38,9 +46,15 @@ export function useTeammateNavigation() {Keyboard.dismiss();try {await preferences.selectTeammate(identity);- if (mounted.current && current.current === accountGeneration) push(teammateResourceRoute(hosted, i18n.language));+ if (mounted.current && current.current === accountGeneration) {+ const owner = `${user?.id ?? ''}:${accountGeneration}`;+ 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));+ push(teammateResourceRoute(hosted, i18n.language));+ }} finally { if (pendingAccount.current === accountGeneration) pendingAccount.current = null; }- }, [accountGeneration, i18n.language, preferences.selectTeammate, push]);+ }, [accountGeneration, i18n.language, preferences.selectTeammate, push, user?.id]);const openCreatedTeammate = useCallback(async (host: RemoteResourceHostTarget, ref: RemoteResourceRef) => {if (!mounted.current || current.current !== accountGeneration || !host.deviceId || !ref.id || !ref.collectionId|| ref.kind !== 'bot' || pendingAccount.current === accountGeneration) return;diff --git a/apps/mobile/src/session/useTeammateRoster.ts b/apps/mobile/src/session/useTeammateRoster.tsindex b73f3cb1ed..4c08696dcd 100644--- a/apps/mobile/src/session/useTeammateRoster.ts+++ b/apps/mobile/src/session/useTeammateRoster.ts@@ -80,11 +80,14 @@ export function useTeammateRoster(enabled = true) {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]);- return { ...list, items: ready ? list.items.filter((row) => row.item.ref.kind === 'bot') : [],+ 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,+ isOnline: (host: RemoteResourceHostTarget) => ready && !revoked.has(host.deviceId) && list.isOnline(host),targets: ready ? discovery.targets : NO_TARGETS,createTargets: ready && status === 'online' ? discovery.createTargets.filter((host) => !revoked.has(host.deviceId) && list.isOnline(host)) : NO_TARGETS,- authoritative: ready && !discovery.loading && !list.loading && status === 'online' && !discovery.error && (!discovery.targets.length || !list.error),- loading: !ready || discovery.loading || list.loading,- refreshing: discovery.binding === binding && (discovery.loading || list.refreshing),+ authoritative: ready && !discovery.loading && !list.loading && !list.syncing && status === 'online' && !discovery.error && (!discovery.targets.length || !list.error),+ loading: items.length === 0 && (!ready || list.loading),+ refreshing: list.refreshing,error: ready ? discovery.error ?? list.error : null, refresh };}diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex b2af67bf09..7e08f3ec09 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -109,6 +109,9 @@ enum 编译分支,也不接受任意 HTML、React 或无限 UI DSL。资源身份必须包含 `deviceId + collectionId + kind + id`。资源路由打开时应重新调用 `resource:get`解析 `conversation` 等 link,不能把可能 rollover 的 Session id 当成永久资源身份。已有对话继续复用 canonical Session 的消息、输入、确认与恢复链路,不复制一套模块专属聊天协议。+列表已有 conversation link 时,可直接展示聊天框架和同账号缓存,在聊天页内重读资源,+复用该页的 Session 元数据查询校验 ID、类型与设备归属;校验完成前不放开发送、控制和已读。+列表返回与后台刷新应保留已有内容,仅首次无数据时显示整页加载,不用固定延迟掩盖切换。协议按字段追加演进。未知字段、未知 collection 和未知 action 不得导致整个首页或会话崩溃;结构化 Session 内容必须携带可读 `fallbackMarkdown`,旧客户端至少能阅读并继续任务。只有新增