Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(device-link): 保留离线设备缓存入口并暂停远程读取

Dash750169130941
diff --git a/apps/desktop/src/renderer/__tests__/remoteContentRecoveryHook.test.ts b/apps/desktop/src/renderer/__tests__/remoteContentRecoveryHook.test.ts
index b41e4c4913..5f013db0eb 100644
--- a/apps/desktop/src/renderer/__tests__/remoteContentRecoveryHook.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteContentRecoveryHook.test.ts
@@ -17,7 +17,7 @@ vi.mock('@/lib/logger', () => ({
}));
vi.mock('@/lib/makerTransport', () => ({ isSessionTurnRunningFor: async () => true }));
vi.mock('@/features/device-link/remoteProjectsStore', () => ({
- remoteProjectsStore: { getDeviceIds: () => ['host'] },
+ remoteProjectsStore: { getDeviceIds: () => ['host', 'neighbor'], subscribe: () => () => {} },
}));
vi.mock('@/features/device-link/refreshRemoteSessions', () => ({
refreshRemoteDeviceSessions: vi.fn(),
diff --git a/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts b/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts
index 6d18a9921f..7d11ecf466 100644
--- a/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteHistoryOriginReconcile.test.ts
@@ -112,6 +112,32 @@ afterEach(() => {
});
describe('makerChatStore.reconcileOpenSessionOrigins (device-link 历史竞速)', () => {
+ it('keeps offline cached rows stable through store updates and starts first read when the host returns', async () => {
+ const s = sid();
+ const cached = dbMessage(s, 'cached', 'Saved answer');
+ const getMessages = vi.fn(async () => ({ accountCounter: 0, messages: [cached] }));
+ Object.assign(window.electronAPI.deviceLink, { mirrorCache: { getMessages } });
+ seedRemote(s);
+ remoteProjectsStore.markDeviceDisconnected(DEVICE_ID);
+ const leave = makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await flush();
+ const messages = makerChatStore.getSnapshot(s).messages;
+ expect(messages.map((message) => message.clientId)).toEqual([cached.clientId]);
+ makerChatStore.reconcileOpenSessionOrigins();
+ makerChatStore.reconcileOpenSessionOrigins();
+ await flush();
+ expect(makerChatStore.getSnapshot(s).messages).toBe(messages);
+ expect(getMessages).toHaveBeenCalledTimes(1);
+ expect(invoke).not.toHaveBeenCalled();
+ remoteHistory = [cached, dbMessage(s, 'new', 'New answer')];
+ seedRemote(s);
+ makerChatStore.reconcileOpenSessionOrigins();
+ await flush();
+ expect(invoke).toHaveBeenCalledWith(DEVICE_ID, 'local-db:messages:list', expect.anything());
+ expect(makerChatStore.getSnapshot(s).messages.map((message) => message.clientId)).toContain('client-new');
+ leave();
+ });
it('启动竞速:origin 解析后经隧道重载被控端真历史(不再停留本机空库)', async () => {
const s = sid();
// 1) 竞速:mapping 未注入,ensureInitialMessages 命中本机空库 → 空历史 historyLoaded=true。
diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionSyncEngine.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionSyncEngine.test.ts
index c2fa00f6fc..02b8afa927 100644
--- a/apps/desktop/src/renderer/__tests__/remoteSessionSyncEngine.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteSessionSyncEngine.test.ts
@@ -37,6 +37,26 @@ beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
describe('createRemoteSessionSyncEngine', () => {
+ it('keeps an offline running view quiet and resumes using the existing recovery path', async () => {
+ let available = false;
+ const deps = { canRead: () => available, subscribe: vi.fn(), unsubscribe: vi.fn(), reconcile: vi.fn(),
+ refreshList: vi.fn(), getLastEventAt: () => 0, isRunningNow: () => true,
+ queryTurnRunning: vi.fn(async () => true), finalize: vi.fn(), reconcileForce: vi.fn(),
+ onSuspectStall: vi.fn(), stallThresholdMs: 1, watchdogIntervalMs: 10 };
+ const engine = createRemoteSessionSyncEngine(() => ({ sessionId: SID, deviceId: DEV }), deps);
+ engine.subscribeHeavy(); engine.reconcileOnMount(); engine.startWatchdog();
+ engine.handleFocus(); engine.resync();
+ await vi.advanceTimersByTimeAsync(2_000);
+ for (const call of [deps.subscribe, deps.reconcile, deps.queryTurnRunning, deps.refreshList, deps.onSuspectStall]) {
+ expect(call).not.toHaveBeenCalled();
+ }
+ available = true;
+ engine.handleOnline();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(deps.subscribe).toHaveBeenCalled();
+ expect(deps.reconcile).toHaveBeenCalled();
+ engine.dispose();
+ });
it('subscribeHeavy 订阅正确重 topic;无 device/session → no-op', () => {
const { engine, deps } = setup();
engine.subscribeHeavy();
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts
index 4f5c4cdd37..85d9848b0c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts
@@ -40,6 +40,8 @@ export interface RemoteSyncTarget {
/** engine 的外部副作用依赖(测试注入 spy)。 */
export interface RemoteSyncEngineDeps {
+ /** Offline cached views must not start reads or turn-status probes. */
+ canRead?: () => boolean;
subscribe: (deviceId: string, topics: string[]) => void;
unsubscribe: (deviceId: string, topics: string[]) => void;
reconcile: (sessionId: string) => void;
@@ -117,6 +119,7 @@ export function createRemoteSessionSyncEngine(
let prevRunning = false;
const subscribeHeavy = (): void => {
+ if (deps.canRead?.() === false) return;
const { sessionId, deviceId } = getTarget();
if (!sessionId || !deviceId) return;
deps.subscribe(deviceId, [`session:${sessionId}`]);
@@ -129,7 +132,7 @@ export function createRemoteSessionSyncEngine(
timer = setTimeout(() => {
timer = null;
const t = getTarget();
- if (t.sessionId && t.deviceId) deps.reconcile(t.sessionId);
+ if (t.sessionId && t.deviceId && deps.canRead?.() !== false) deps.reconcile(t.sessionId);
}, debounceMs);
};
@@ -164,7 +167,7 @@ export function createRemoteSessionSyncEngine(
const watchdogTick = async (): Promise<void> => {
const { sessionId, deviceId } = getTarget();
// 目标无效 / 恢复进行中 → 跳过本拍。
- if (!sessionId || !deviceId || recovering) { scheduleTick(baseIntervalMs); return; }
+ if (!sessionId || !deviceId || recovering || deps.canRead?.() === false) { scheduleTick(baseIntervalMs); return; }
// turn 不在跑(可能已正常收尾)/ 还没静默够久 → 已恢复:清残留兜底态 + 复位 backoff,常规巡检。
if (!deps.isRunningNow!(sessionId) || now() - lastSeen(sessionId) < stallThresholdMs) {
deps.onRecovered?.(sessionId);
@@ -180,7 +183,7 @@ export function createRemoteSessionSyncEngine(
// await 期间可能已 dispose / stop(切会话 / 卸载)→ watchdogStopped 是真正的 abort token。
// (getTarget() 是本 effect 常量闭包,sessionId 恒等,不能用它判过期 —— 那是死代码。)
// 迟到结果一律丢弃,绝不在已停的看门狗上 finalize / 弹兜底(否则会把 stall 态错挂到新会话)。
- if (watchdogStopped) return;
+ if (watchdogStopped || deps.canRead?.() === false) return;
// 查询成功本身 = 连上了被控端 → 清掉之前查询失败残留的 suspectStall 兜底态。
deps.onRecovered?.(sessionId);
if (!stillRunning) {
@@ -196,7 +199,7 @@ export function createRemoteSessionSyncEngine(
} catch {
// 查询不可达 / 旧被控端无此 channel / 超时 / 离线 → 不 auto-finalize,弹兜底让用户处理。
// 同样:await 期间若已 dispose,迟到的失败不应把兜底态挂到新会话。
- if (watchdogStopped) return;
+ if (watchdogStopped || deps.canRead?.() === false) return;
deps.onSuspectStall?.(sessionId);
backoff = Math.min(backoff * 2, 4);
} finally {
@@ -249,7 +252,7 @@ export function createRemoteSessionSyncEngine(
mountReconcileTimer = setTimeout(() => {
mountReconcileTimer = null;
const { sessionId: sid } = getTarget();
- if (!sid || watchdogStopped) return;
+ if (!sid || watchdogStopped || deps.canRead?.() === false) return;
if (!deps.isRunningNow!(sid)) {
// 延迟期间已收到 done(正常 push 到达或边沿检测触发了 reconcile)→ 无需操作
return;
@@ -258,7 +261,7 @@ export function createRemoteSessionSyncEngine(
void (async () => {
try {
const stillRunning = await deps.queryTurnRunning!(sid);
- if (watchdogStopped) return;
+ if (watchdogStopped || deps.canRead?.() === false) return;
// 核实**成功**本身就是「被控端可达」的证据 → 收起 suspect-stall 兜底
// (与看门狗路径对齐)。否则此前因查询失败挂起的兜底横幅会在连接已恢复后
// 继续要求用户手动处理,直到下一次看门狗巡检(退避后可能约 60s)才消失
@@ -310,6 +313,7 @@ export function createRemoteSessionSyncEngine(
scheduleReconcile();
},
resync() {
+ if (deps.canRead?.() === false) return;
const { deviceId } = getTarget();
if (!deviceId) return;
subscribeHeavy();
@@ -373,6 +377,10 @@ export function useRemoteSessionSync(
return;
}
setContent({ sessionId, deviceId, state: 'syncing' });
+ let relayAvailable: boolean | undefined;
+ let peerAvailable = remoteProjectsStore.getDeviceIds().includes(deviceId);
+ let peerResponsive: boolean | undefined;
+ const canRead = () => relayAvailable !== false && peerAvailable && peerResponsive !== false;
const recovery = createRemoteContentRecovery({
subscribe: () => window.electronAPI.deviceLink.subscribe(deviceId, [`session:${sessionId}`]),
reconcile: () => makerChatStore.reconcileRemoteMessages(sessionId, { freshHistory: true }),
@@ -385,6 +393,7 @@ export function useRemoteSessionSync(
const engine = createRemoteSessionSyncEngine(
() => ({ sessionId, deviceId }),
{
+ canRead,
subscribe: (d, topics) => {
if (!recovery.isReady()) { recovery.request(); return; }
return window.electronAPI.deviceLink
@@ -392,6 +401,7 @@ export function useRemoteSessionSync(
.catch((err) => log.warn('device-link subscribe(session) failed', err));
},
unsubscribe: (d, topics) => {
+ if (!canRead()) return;
return window.electronAPI.deviceLink.unsubscribe(d, topics).catch(() => {});
},
reconcile: (s) => {
@@ -400,7 +410,7 @@ export function useRemoteSessionSync(
// (远程回执的新鲜度语义需要两者同代落地),这里不再单独调用。
void makerChatStore.reconcileRemoteMessages(s);
},
- refreshList: (d) => void refreshRemoteDeviceSessions(d, remoteProjectsStore.getDeviceName(d) ?? d),
+ refreshList: (d) => { if (canRead()) void refreshRemoteDeviceSessions(d, remoteProjectsStore.getDeviceName(d) ?? d); },
// ── stall 看门狗 deps(全套提供 → 启用)──
getLastEventAt: (s) => makerChatStore.getLastInboundEventAt(s),
isRunningNow: (s) => makerChatStore.getSnapshot(s).agentStatus.isRunning,
@@ -422,6 +432,7 @@ export function useRemoteSessionSync(
engineRef.current = engine;
// mount:订阅重 topic;首拉由 ensureInitialMessages 负责,这里不立即对账(避免与首拉竞争)。
+ recovery.invalidate(canRead());
engine.subscribeHeavy();
// 用当前 turn 态初始化边沿检测(mount-mid-run 时不误把第一次 false 当 turn 结束)。
engine.primeRunning(makerChatStore.getSnapshot(sessionId).agentStatus.isRunning);
@@ -429,9 +440,13 @@ export function useRemoteSessionSync(
// 切回时如果 isRunning=true → 可能是切走期间 done 丢了 → 延迟核实被控端
engine.reconcileOnMount();
- let relayAvailable: boolean | undefined;
- let peerAvailable: boolean | undefined = remoteProjectsStore.getDeviceIds().includes(deviceId);
- let peerResponsive: boolean | undefined;
+ const offDevices = remoteProjectsStore.subscribe(() => {
+ const available = remoteProjectsStore.getDeviceIds().includes(deviceId);
+ if (peerAvailable === available) return;
+ peerAvailable = available;
+ recovery.invalidate(canRead());
+ if (canRead()) engine.handleOnline();
+ });
const offPeerReset = window.electronAPI.deviceLink.onPeerLinkReset?.((p) => {
if (p.deviceId !== deviceId) return;
recovery.invalidate(relayAvailable !== false && peerAvailable !== false && peerResponsive !== false);
@@ -441,17 +456,18 @@ export function useRemoteSessionSync(
});
const offStatus = window.electronAPI.deviceLink.onStatusChanged((p) => {
const online = p.status === 'online';
- if (relayAvailable !== online) recovery.invalidate(online);
+ const changed = relayAvailable !== online;
relayAvailable = online;
- if (!online) peerAvailable = undefined;
+ if (changed) recovery.invalidate(canRead());
if (p.status !== 'online') return;
engine.handleOnline();
});
const offPresence = window.electronAPI.deviceLink.onPresenceChanged((snap) => {
if (snap.deviceId === deviceId) {
const available = snap.online && snap.remoteControlEnabled;
- if (peerAvailable !== available) recovery.invalidate(available && relayAvailable !== false);
+ const changed = peerAvailable !== available;
peerAvailable = available;
+ if (changed) recovery.invalidate(canRead());
}
engine.handlePresence(snap.deviceId, snap.online);
});
@@ -479,6 +495,7 @@ export function useRemoteSessionSync(
return () => {
recovery.dispose();
+ offDevices();
offStatus();
offPresence();
offResponsiveness();
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 20d6112ed9..471551e40a 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -115,6 +115,7 @@ import {
} from '@/lib/makerTransport';
import {
remoteProjectsStore,
+ isRemoteDeviceMarkedDisconnected,
requestRemoteReseed,
} from '@/features/device-link/remoteProjectsStore';
import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
@@ -3906,6 +3907,8 @@ function resolveGatewayRecoveryProviderId(
function enterView(sessionId: string): () => void {
const view = getRemoteHistoryView(sessionId);
+ const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
+ if (deviceId) view?.setNetworkAvailable(!isRemoteDeviceMarkedDisconnected(deviceId));
const resumingHistory = view && !view.isActive();
view?.setActive(true);
_activeViewSessions.set(sessionId, (_activeViewSessions.get(sessionId) ?? 0) + 1);
@@ -8615,6 +8618,10 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
// 纯来源漂移驱动,正常 patched 推送(current===loaded)不误重载。teardown 时随其它监听一并清。
{
const unsub = remoteProjectsStore.subscribe(() => {
+ for (const [sessionId, entry] of remoteHistoryViews) {
+ const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
+ if (deviceId) entry.view?.setNetworkAvailable(!isRemoteDeviceMarkedDisconnected(deviceId));
+ }
// Snapshot/reseed can be the first clear signal (the projection or patch
// may have been dropped). Reconcile boundaries before any subscriber or
// outbox pump can observe the new shard.
@@ -10720,6 +10727,7 @@ function createRemoteHistoryView(sessionId: string) {
entry.view = view;
entry.isCurrent = isCurrent;
remoteHistoryViews.set(sessionId, entry);
+ view.setNetworkAvailable(!isRemoteDeviceMarkedDisconnected(deviceId));
view.subscribe(() => {
if (!isCurrent() || !sessions.has(sessionId)) return;
const snapshot = view.getSnapshot();
@@ -10743,6 +10751,13 @@ function createRemoteHistoryView(sessionId: string) {
function ensureInitialMessages(sessionId: string): void {
const state = getOrCreateState(sessionId);
+ const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
+ if (deviceId && isRemoteDeviceMarkedDisconnected(deviceId)) {
+ _historyLoadOrigin.set(sessionId, deviceId);
+ noteInputProjectionOrigin(sessionId, deviceId);
+ hydrateRemoteMessagesFromCache(sessionId);
+ return;
+ }
requestInputProjection(sessionId);
// Prefetch and other non-mounted callers still create a cache entry. Give
// that entry the same bounded lifetime as a viewed session so a cancelled
@@ -11494,7 +11509,12 @@ function reconcileOpenSessionOrigins(): void {
}
if (current === undefined) continue;
const loaded = _historyLoadOrigin.get(sessionId);
- if (current === loaded && !originChange.changed) continue;
+ if (current === loaded && !originChange.changed) {
+ if (_activeViewSessions.has(sessionId) && !sessions.get(sessionId)?.historyLoaded && !isRemoteDeviceMarkedDisconnected(current)) {
+ ensureInitialMessages(sessionId);
+ }
+ continue;
+ }
// undefined → deviceId 是启动竞速的**首次解析**(上一次首拉命中的是本机空库),
// 缓存并未因此过期 → 放开 hydrate,让被控端离线时也能看到上次的最近一页。
// 设备之间真的换了 origin(string → 另一个 string)时不放开:那是另一台机器的历史。
@@ -11543,6 +11563,8 @@ const _remoteReconcileInFlight = new Map<
>();
function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean; freshHistory?: boolean }): Promise<boolean> {
+ const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
+ if (deviceId && isRemoteDeviceMarkedDisconnected(deviceId)) return Promise.resolve(false);
const view = getRemoteHistoryView(sessionId);
if (view && (view.getSnapshot().ready || opts?.freshHistory)) return Promise.all([view.refresh(false, opts?.freshHistory), reconcilePendingInteractions(sessionId)]).then(() => {
if (getRemoteHistoryView(sessionId) !== view || !view.isActive()) return false;
@@ -11865,6 +11887,8 @@ function loadOlderMessages(
automatic = false,
maxPages = MAX_LOAD_OLDER_PAGES,
): Promise<boolean> {
+ const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
+ if (deviceId && isRemoteDeviceMarkedDisconnected(deviceId)) return Promise.resolve(false);
const view = getRemoteHistoryView(sessionId);
if (view?.getSnapshot().ready) {
const before = view.getSnapshot().nextCursor;
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index fcd2b162fd..e977ac6cfd 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -1,4 +1,5 @@
import { cacheRemoteResourceHome, readRemoteResourceSnapshot } from '@/device-link/remoteResourceCache';
+import { canBrowseMobileHomeDevice } from '@/session/mobileHome';
import { useFocusEffect, useIsFocused } from 'expo-router';
import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MutableRefObject, type ReactNode } from 'react';
import {
@@ -51,7 +52,6 @@ import type { TFunction } from 'i18next';
import { useAuth } from '@/auth/AuthContext';
import { configureCollapseAnimation } from '@/utils/collapseAnimation';
import { useGuardedPush } from '@/utils/useGuardedPush';
-import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
import { MobileVendorIcon } from '@/components/MobileVendorIcon';
import {
MainWindowActionGroup,
@@ -242,7 +242,6 @@ import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';
const LIST_LIMIT = 200;
-const DEVICE_LIST_TIMEOUT_MS = 12_000;
const HOME_LIST_SUBSCRIPTION_OWNER = 'device-list';
// Keep the device-link channel responsive while All Sessions hydrates several
// computers. This does not change the 200-row server limit; it only bounds the
@@ -361,7 +360,7 @@ function HomeScreenContent() {
const guardedPush = useGuardedPush();
const { width: screenWidth, height: screenHeight } = useWindowDimensions();
const auth = useAuth();
- const { accountGeneration, apiFetch, deviceId: selfDeviceId, user } = auth;
+ const { accountGeneration, deviceId: selfDeviceId, user } = auth;
// 首页列表持久缓存按账号键控(401 掉线换号不串数据);首页仅登录后可达,user 理应非空。
const homeCacheUserId = user?.id ?? '';
const {
@@ -369,6 +368,7 @@ function HomeScreenContent() {
connectionIssue,
invoke,
lastPresenceSnapshot,
+ readDeviceList,
status,
subscribe,
unsubscribe,
@@ -927,10 +927,7 @@ function HomeScreenContent() {
if (homeAccountGenerationRef.current !== accountGenerationAtStart) {
throw new Error('Home account generation superseded');
}
- return apiFetch<{ devices: DeviceView[] }>('/api/device-link/devices', {
- baseUrl: DEVICE_LINK_API_BASE_URL,
- timeoutMs: DEVICE_LIST_TIMEOUT_MS,
- });
+ return readDeviceList();
},
{ maxAttempts: 3 },
);
@@ -1039,7 +1036,7 @@ function HomeScreenContent() {
return task.finally(() => {
if (visible && homeAccountGenerationRef.current === accountGenerationAtStart) setRefreshing(false);
});
- }, [accountGeneration, apiFetch, deviceIdentityCacheReady, homeCacheUserId, hydrateDeviceSessions, reconcileDeviceViews, reconcileHomeDeviceSyncScope, revokedDevices, softInvalidateDeviceMirror]);
+ }, [accountGeneration, readDeviceList, deviceIdentityCacheReady, homeCacheUserId, hydrateDeviceSessions, reconcileDeviceViews, reconcileHomeDeviceSyncScope, revokedDevices, softInvalidateDeviceMirror]);
loadHomeRef.current = loadHome;
// 冷启动先画缓存:上次 loadHome 成功的设备+会话快照种入 store,先把列表画出来(消除首屏强制
@@ -1067,7 +1064,6 @@ function HomeScreenContent() {
) return;
for (const device of snapshot) {
remoteSessionStore.hydrateDeviceSessionsIfEmpty(device.deviceId, device.deviceName, device.sessions);
- updateDeviceConnectionState(device.deviceId, 'syncing');
}
};
void read.initial
@@ -1828,7 +1824,7 @@ function HomeScreenContent() {
let restoredUnavailable = false;
if (!missing && restoredSelectionUnvalidatedRef.current) {
const filter = home.deviceFilters.find((item) => item.deviceId === selectedDeviceId);
- restoredUnavailable = !!filter && !filter.available;
+ restoredUnavailable = !!filter && !canBrowseMobileHomeDevice(filter);
restoredSelectionUnvalidatedRef.current = false;
}
if (!missing && !restoredUnavailable) return;
@@ -1838,16 +1834,20 @@ function HomeScreenContent() {
}, [home.deviceFilters, home.selectedDeviceId, initialHomeSettled, selectedDeviceId]);
// 连接层失败原因比请求级 error 更根因:unstable 在 online 时也需保持可见。
const activeConnectionIssue = status !== 'online' || connectionIssue?.kind === 'unstable' ? connectionIssue : null;
- const showConnectionRow = !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';
+ const selectedDeviceDisconnected = home.deviceFilters.some((item) => item.deviceId !== null
+ && (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.sessionCount > 0)
+ && !home.deviceFilters.some((item) => item.deviceId !== null
+ && (!selectedDeviceId || item.deviceId === selectedDeviceId) && item.available);
+ const showConnectionRow = selectedDeviceDisconnected || !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';
const connectionTone = activeConnectionIssue
? 'off'
- : connectionError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
+ : selectedDeviceDisconnected ? 'off' : connectionError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
const connectionTitle = activeConnectionIssue
? connectionIssueTitle(activeConnectionIssue.kind)
- : connectionError ? t('devices.list.syncFailed') : homeConnectionTitle(status, t);
+ : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.title') : connectionError ? t('devices.list.syncFailed') : homeConnectionTitle(status, t);
const connectionCopy = activeConnectionIssue
? connectionIssueHint(activeConnectionIssue.kind)
- : connectionError;
+ : selectedDeviceDisconnected ? t('deviceLink.cachedHistory.hint') : connectionError;
const emptyStateTitle = initialHomeError ? t('devices.list.syncFailed') : home.emptyTitle;
const emptyStateCopy = initialHomeError ? (connectionError ?? t('devices.list.requestFailed')) : home.emptyCopy;
// 无可控制电脑的引导态(landing)可见性,与 ListEmptyComponent 的分支同口径。
@@ -2895,9 +2895,8 @@ function DeviceMenuModal({
onClosed,
});
const allFilter = filters.find((item) => item.deviceId === null) ?? null;
- // 范围菜单只列当前能打开的电脑,对齐桌面机器切换器:离线 / 关远控 / 撤权的设备
- // 不占菜单(灰行点不进去只会吵);空态引导另走 RemoteAccessGuide。
- const deviceFilters = filters.filter((item) => item.deviceId !== null && item.available);
+ // 离线电脑保留缓存入口;关远控和撤权不由缓存恢复访问权限。
+ const deviceFilters = filters.filter((item) => item.deviceId !== null && canBrowseMobileHomeDevice(item));
return (
<HomeMenuScrim
backdropTestID="home.deviceMenu.backdrop"
@@ -2935,7 +2934,7 @@ function DeviceMenuModal({
{deviceFilters.map((item) => (
<DeviceMenuItem
connectionState={item.deviceId ? connectionStates[item.deviceId] ?? 'idle' : 'idle'}
- dimmed={!item.available && item.state !== 'access_revoked'}
+ dimmed={!canBrowseMobileHomeDevice(item)}
key={item.id}
label={item.label}
onPress={() => onSelect(item)}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 9c531d4e22..c94fd71afe 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1012,8 +1012,9 @@ export default function SessionScreen() {
const revokedDevices = useRevokedDevices();
const unresponsiveDevices = useUnresponsiveDevices();
const maker = useMobileMakerTransport(deviceId);
+ const remoteHistoryAvailable = status === 'online' && getPresenceAvailability(deviceId) === true;
const historyView = useRemoteHistoryView(deviceId, sessionId, maker,
- () => messageScreenFocusedRef.current && messageAppActiveRef.current);
+ () => messageScreenFocusedRef.current && messageAppActiveRef.current, remoteHistoryAvailable);
useEffect(() => {
if (messageScreenFocusedRef.current && messageAppActiveRef.current) historyView.view.setActive(true);
}, [connectionEpoch, messageReloadRevision, historyView.view]);
@@ -3204,6 +3205,7 @@ export default function SessionScreen() {
const snapshotStartedAt = Date.now();
const options = { replaceMessages: syncRun.replaceMessages };
if (!deviceId || !sessionId || syncRun.isStale()) return;
+ if (!remoteHistoryAvailable) { setLoading(false); return; }
const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);
const messageAuthorityCurrent = () =>
remoteSessionStore.isSessionMessageAuthorityCurrent(messageAuthority);
@@ -3452,7 +3454,7 @@ export default function SessionScreen() {
} finally {
if (!syncRun.isStale() && messageAuthorityCurrent()) setLoading(false);
}
- }, [deviceId, deviceName, getSubscriptionIdentity, latchOutboxTransportHold, maker, notificationResponse, openLink, reopenLink, sessionId, setError, subscribe]);
+ }, [deviceId, deviceName, getSubscriptionIdentity, latchOutboxTransportHold, maker, notificationResponse, openLink, reopenLink, remoteHistoryAvailable, sessionId, setError, subscribe]);
// 任一连接恢复身份变化都会让旧读取失去提交资格。否则断线前启动的同步可能在
// 新 hold 锁存后迟到,并从成功尾误清恢复屏障。
const remoteSyncContextKey = JSON.stringify([
@@ -4495,6 +4497,7 @@ export default function SessionScreen() {
const loadEarlierMessages = useCallback(async () => {
if (isScheduleDetail) return;
+ if (!remoteHistoryAvailable) return;
if (historyView.snapshot.ready) {
await historyView.view.refresh(true);
if (!historyView.view.isActive() || findRemoteHistoryView(deviceId, sessionId) !== historyView.view) return;
@@ -4549,7 +4552,7 @@ export default function SessionScreen() {
setLoadingEarlier(false);
}
}
- }, [historyView.snapshot.ready, historyView.view, requestSync, abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, oldestLoadedMessageCursor, sessionId]);
+ }, [remoteHistoryAvailable, historyView.snapshot.ready, historyView.view, requestSync, abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, oldestLoadedMessageCursor, sessionId]);
const loadToolInput = useCallback(async (
ref: MobileToolInputProjection,
@@ -8817,9 +8820,10 @@ export default function SessionScreen() {
|| (connectionError ? t('session.screen.sessionNotSynced') : (deviceName || t('session.screen.conversationFallback')))}
/>
- {showConnectionBanner ? (
+ {showConnectionBanner || !remoteHistoryAvailable ? (
<ConnectionBanner
density="compact"
+ cachedOnly={!remoteHistoryAvailable}
deviceUnresponsive={isDeviceUnresponsive}
error={bannerError}
requestErrorAutoRecovering={bannerRetriesHistory ? false : undefined}
diff --git a/apps/mobile/src/__tests__/deviceRosterEvidence.test.ts b/apps/mobile/src/__tests__/deviceRosterEvidence.test.ts
new file mode 100644
index 0000000000..61b458bd74
--- /dev/null
+++ b/apps/mobile/src/__tests__/deviceRosterEvidence.test.ts
@@ -0,0 +1,60 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { expect, it, vi } from 'vitest';
+
+// Execute the production adapter: a second copy of these ordering checks would
+// not catch a stale REST response being wired to the live presence handler.
+const source = ts.createSourceFile('context.tsx', readFileSync(resolve(process.cwd(), 'src/device-link/DeviceLinkContext.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+function fixture() {
+ let expression: ts.Expression | undefined;
+ const visit = (node: ts.Node) => {
+ if (ts.isBinaryExpression(node) && node.left.getText(source) === 'rosterConsumerRef.current'
+ && ts.isArrowFunction(node.right)) expression = node.right;
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ if (!expression) throw new Error('Missing roster consumer');
+ const client = { getStatus: () => 'online' };
+ const bindings = { client, clientRef: { current: client }, connectionEpochRef: { current: 1 },
+ presenceAvailabilityEpochsRef: { current: { next: 0, byDevice: new Map<string, number>() } },
+ remoteResponseEvidenceEpochs: { next: 0, byDevice: new Map<string, number>() },
+ presenceAvailableByDeviceRef: { current: new Map<string, boolean>() },
+ presenceUnavailableVerdictsRef: { current: new Map<string, { kind: string }>() },
+ applyPresence: vi.fn(),
+ };
+ const compiled = ts.transpileModule(`const create = ${expression.getText(source)};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const create = new Function(...Object.keys(bindings), `${compiled}\nreturn create;`)(...Object.values(bindings));
+ return { ...bindings, apply: create() as (devices: unknown[]) => void };
+}
+const device = { deviceId: 'host', name: 'Computer', online: false, remoteControlEnabled: true, isSelf: false };
+
+it('seeds an already offline host and does not reset unchanged online links', () => {
+ const f = fixture();
+ f.apply([device]);
+ expect(f.applyPresence).toHaveBeenCalledWith(expect.objectContaining({ deviceId: 'host', online: false }));
+ f.applyPresence.mockClear();
+ f.presenceAvailableByDeviceRef.current.set('host', true);
+ f.apply([{ ...device, online: true }]);
+ expect(f.applyPresence).not.toHaveBeenCalled();
+});
+
+it('keeps remote-disabled distinct from offline even after a recent response', () => {
+ const f = fixture();
+ f.presenceAvailableByDeviceRef.current.set('host', false);
+ f.presenceUnavailableVerdictsRef.current.set('host', { kind: 'presence' });
+ f.remoteResponseEvidenceEpochs.byDevice.set('host', 1);
+ f.apply([{ ...device, online: true, remoteControlEnabled: false }]);
+ expect(f.applyPresence).toHaveBeenCalledWith(expect.objectContaining({ online: true, remoteControlEnabled: false }));
+});
+
+it('rejects stale offline REST evidence after a response, presence update or connection change', () => {
+ for (const source of ['response', 'presence', 'connection']) {
+ const f = fixture();
+ if (source === 'response') f.remoteResponseEvidenceEpochs.byDevice.set('host', 1);
+ if (source === 'presence') f.presenceAvailabilityEpochsRef.current.byDevice.set('host', 1);
+ if (source === 'connection') f.connectionEpochRef.current++;
+ f.apply([device]);
+ expect(f.applyPresence).not.toHaveBeenCalled();
+ }
+});
diff --git a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
index e5038c0880..b4f926c5b0 100644
--- a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
+++ b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
@@ -136,7 +136,7 @@ describe('live stream interruption wiring', () => {
expect(sendSubscribe).toContain('await confirmTrackedSubscription({');
// 反向竞态同样要守住:快速释放后又切回时,旧 unsubscribe 在真正发帧前必须
// 剔除已经重新被 owner 持有的 topic,不能落在新 subscribe 后把实时流再关掉。
- expect(source).toContain('(topic) => !registryRef.current.hasTopic(deviceId, topic)');
+ expect(source).toContain('(topic) => presenceAvailableByDeviceRef.current.get(deviceId) !== false && !registryRef.current.hasTopic(deviceId, topic)');
expect(source).toMatch(
/const toSend = shouldSendTopic \? topics\.filter\(shouldSendTopic\) : topics;[\s\S]*client\.invoke\(deviceId, \{\s*channel: DL_UNSUBSCRIBE_CHANNEL,\s*args: \[\{ topics: toSend \}\]/,
);
diff --git a/apps/mobile/src/__tests__/homeChromeMenus.test.ts b/apps/mobile/src/__tests__/homeChromeMenus.test.ts
index 5ee5cbe2fc..dbd9eb3d1c 100644
--- a/apps/mobile/src/__tests__/homeChromeMenus.test.ts
+++ b/apps/mobile/src/__tests__/homeChromeMenus.test.ts
@@ -26,6 +26,12 @@ function filter(
}
describe("home chrome menus", () => {
+ it("keeps cached offline and unknown computers without granting revoked access", () => {
+ const filters = ["offline", "unknown", "access_revoked", "remote_disabled"].map((state) =>
+ filter({ id: state, label: state, deviceId: state, available: false, state, sessionCount: 2 }));
+ expect(buildHomeScopeMenuItems(filters, "All").map((item) => item.key)).toEqual(["offline", "unknown"]);
+ expect(buildHomeScopePullDownActions(filters, "All").map((item) => item.id)).toEqual(["offline", "unknown"]);
+ });
it("selects native device scopes directly without a management submenu", () => {
const actions = buildHomeScopePullDownActions([
filter({ id: "all", label: "全部任务" }),
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index 078738e595..c35e203eed 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -354,7 +354,7 @@ describe('mobile home desktop-first surface', () => {
const localSmokeSource = readSource('scripts/local-device-link-smoke.mjs');
const deviceDetailFlow = readSource('e2e/maestro/session_list_controls.yaml');
- expect(source).toContain('item.deviceId !== null && item.available');
+ expect(source).toContain('item.deviceId !== null && canBrowseMobileHomeDevice(item)');
expect(source).toContain('`home.deviceChip.${sanitizeDeviceChipTestId(item.deviceId)}`');
expect(source).toContain('function sanitizeDeviceChipTestId');
expect(source).toContain("return value.replace(/[^A-Za-z0-9_-]/g, '_');");
@@ -390,7 +390,7 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'failed');");
expect(source).toContain("updateDeviceConnectionState(device.deviceId, 'idle');");
expect(source).toContain(
- "const showConnectionRow = !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';",
+ "const showConnectionRow = selectedDeviceDisconnected || !!connectionError || status !== 'online' || connectionIssue?.kind === 'unstable';",
);
expect(source).toContain("connectionStates={deviceConnectionStates}");
expect(source).toContain('function DeviceMenuItem');
@@ -561,7 +561,8 @@ describe('mobile home desktop-first surface', () => {
// Home remains mounted across saved-account activation, so clearing the shared DeviceLink
// stores is insufficient: page-local refs/state must disappear before the next paint too.
- expect(source).toContain('const { accountGeneration, apiFetch, deviceId: selfDeviceId, user } = auth;');
+ expect(source).toContain('const { accountGeneration, deviceId: selfDeviceId, user } = auth;');
+ expect(source).toContain('return readDeviceList();');
expect(source).toContain('const homeAccountGenerationRef = useRef(accountGeneration);');
expect(source).toContain('useLayoutEffect(() => {');
expect(source).toContain('syncInFlightRef.current = null;');
diff --git a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
index 4510cc8182..2517943cdd 100644
--- a/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionMainLayerDesktopFirst.test.ts
@@ -44,7 +44,8 @@ describe('mobile session main layer desktop-first noise budget', () => {
// banner 渲染条件(useShowConnectionBanner):请求级 / transport hold error、可分类连接问题、
// 目标设备熔断 open(电脑端未响应)立即显示;普通弱网断线经防闪窗口后也显示,不再彻底静默。
- expect(routeSource).toContain('{showConnectionBanner ? (');
+ expect(routeSource).toContain('{showConnectionBanner || !remoteHistoryAvailable ? (');
+ expect(routeSource).toContain('cachedOnly={!remoteHistoryAvailable}');
expect(source.replace(/\r\n/g, '\n'))
.toContain('useShowConnectionBanner(\n status,\n bannerError,');
expect(routeSource).not.toContain('connectionError || (loading && !currentSession)');
diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
index bb3c6d47d8..3817314421 100644
--- a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
@@ -40,7 +40,7 @@ const tick = () => new Promise((done) => setTimeout(done, 0));
const session = { id: 's1', updatedAt: '2026-09-06T00:00:00Z', _count: { messages: 100 } };
const page = { messages: [{ id: 'm1' }], limit: 1, reducedByPayloadTooLarge: false };
-function fixture(reopen = false) {
+function fixture(reopen = false, remoteHistoryAvailable = true) {
const state = {
rows: reopen ? [{ id: 'cached', clientId: 'cached' }] : [] as { id: string; clientId?: string }[],
older: false, loading: false, historyLoading: false,
@@ -79,6 +79,7 @@ function fixture(reopen = false) {
listActiveSessions: vi.fn(async () => []),
};
const bindings = {
+ remoteHistoryAvailable,
deviceId: 'd1', deviceName: 'test', sessionId: 's1',
historyView: { snapshot: { ready: false }, view: { refresh: async (): Promise<void> => undefined, getSnapshot: (): { ready: boolean; error: unknown } => ({ ready: false, error: new Error('[CHANNEL_NOT_ALLOWED] legacy host') }) } },
remoteSessionStore: store, maker, isHistoryViewUnavailable, shouldBlockSessionSync: () => false,
@@ -126,6 +127,18 @@ function fixture(reopen = false) {
}
describe('production session recovery callbacks', () => {
+ it('keeps cached rows offline without fetching metadata, projection, history or earlier pages', async () => {
+ const f = fixture(true, false);
+ const rows = f.state.rows;
+ await f.sync();
+ await f.earlier();
+ expect(f.state.rows).toBe(rows);
+ expect(f.state.loading).toBe(false);
+ expect(f.maker.getSession).not.toHaveBeenCalled();
+ expect(f.maker.listMessages).not.toHaveBeenCalled();
+ expect(f.maker.input.getProjection).not.toHaveBeenCalled();
+ expect(f.state.readAck).toBeNull();
+ });
it('reads after ACK when restored history is ready but the captured snapshot is not', async () => {
const f = fixture(true);
f.store.isSessionMessageWindowSynced.mockReturnValue(true);
diff --git a/apps/mobile/src/components/ConnectionBanner.tsx b/apps/mobile/src/components/ConnectionBanner.tsx
index 18757753f6..1830b74392 100644
--- a/apps/mobile/src/components/ConnectionBanner.tsx
+++ b/apps/mobile/src/components/ConnectionBanner.tsx
@@ -77,6 +77,7 @@ export function ConnectionBanner({
onSync,
variant = 'bar',
recovery,
+ cachedOnly = false,
}: {
status: DeviceLinkStatus;
loading: boolean;
@@ -92,6 +93,7 @@ export function ConnectionBanner({
onSync(): void;
variant?: 'bar' | 'inline';
recovery?: 'syncing' | 'recovered';
+ cachedOnly?: boolean;
}) {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
@@ -102,29 +104,29 @@ export function ConnectionBanner({
const activeIssue = status !== 'online' || issue?.kind === 'unstable' ? issue : null;
// 熔断 open 优先于请求级 error:open 期间的请求失败绝大多数就是熔断快速失败本身,
// 状态级提示(未响应 + 自动重试中)比单次请求的错误原文更能解释现状。
- const showUnresponsive = !activeIssue && deviceUnresponsive;
+ const showUnresponsive = !cachedOnly && !activeIssue && deviceUnresponsive;
// 熔断已关后残留的 DEVICE_UNRESPONSIVE 错误是陈旧快照,按 null 处理(与
// useShowConnectionBanner 同一判定,否则会出现可见但无内容的空壳 banner)。
const effectiveError = resolveEffectiveConnectionError(error, deviceUnresponsive);
- const friendlyError = activeIssue || showUnresponsive ? null : describeRemoteError(effectiveError);
+ const friendlyError = cachedOnly || activeIssue || showUnresponsive ? null : describeRemoteError(effectiveError);
const autoRecoveringRequest = requestErrorAutoRecovering ?? isAutoRecoveringRemoteError(effectiveError);
- const showRecoveryProgress = (!activeIssue || activeIssue.kind === 'unstable' || activeIssue.kind === 'replaced')
+ const showRecoveryProgress = !cachedOnly && (!activeIssue || activeIssue.kind === 'unstable' || activeIssue.kind === 'replaced')
&& (status === 'connecting' || deviceUnresponsive || recovery === 'syncing'
|| (friendlyError !== null && autoRecoveringRequest));
- const showSyncAction = resolveConnectionBannerSyncActionVisibility({
+ const showSyncAction = !cachedOnly && resolveConnectionBannerSyncActionVisibility({
online: status === 'online',
hasActiveIssue: activeIssue !== null,
deviceUnresponsive: showUnresponsive,
hasRequestError: friendlyError !== null,
requestErrorAutoRecovering: autoRecoveringRequest,
});
- const tone = activeIssue
+ const tone = cachedOnly ? 'off' : activeIssue
? 'off'
: showUnresponsive
? 'busy'
: friendlyError ? 'muted' : recovery === 'syncing' ? 'busy' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
const compact = density === 'compact';
- const title = activeIssue
+ const title = cachedOnly && !activeIssue ? t('deviceLink.cachedHistory.title') : activeIssue
? activeIssue.kind === 'unstable'
? t('deviceLink.unstableTitle')
: connectionIssueTitle(activeIssue.kind)
@@ -132,7 +134,7 @@ export function ConnectionBanner({
? t('deviceLink.deviceUnresponsiveTitle')
: friendlyError ? t('deviceLink.syncFailed') : status === 'online' && recovery
? t(`deviceLink.recovery.${recovery}`) : relayStatusLabel(status);
- const copy = activeIssue
+ const copy = cachedOnly && !activeIssue ? t('deviceLink.cachedHistory.hint') : activeIssue
? activeIssue.kind === 'unstable'
? t('deviceLink.unstableHint')
: connectionIssueHint(activeIssue.kind)
@@ -150,7 +152,7 @@ export function ConnectionBanner({
]}
testID="connection.banner"
>
- <StatusDot tone={tone} pulsing={!activeIssue && (status === 'connecting' || showUnresponsive || recovery === 'syncing')} />
+ <StatusDot tone={tone} pulsing={!cachedOnly && !activeIssue && (status === 'connecting' || showUnresponsive || recovery === 'syncing')} />
<View style={[styles.textBlock, compact && styles.textBlockCompact]}>
<Text
ellipsizeMode="tail"
diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.ts
index 1c4a3f200a..6f824e452c 100644
--- a/apps/mobile/src/debug/visualMock.ts
+++ b/apps/mobile/src/debug/visualMock.ts
@@ -151,6 +151,7 @@ export function createVisualMockDeviceLinkContext(): DeviceLinkContextValue {
?? (MOBILE_VISUAL_MOCK_REALDATA_URL ? VISUAL_MOCK_REALDATA_DEVICE_NAME : VISUAL_MOCK_DEVICE_NAME);
return {
status: 'online',
+ readDeviceList: async () => ({ devices: visualMockDevices() }),
connectionIssue: null,
presenceVersion: 1,
connectionEpoch: 1,
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 6b9b4c365f..928aaca688 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -21,6 +21,7 @@ import {
parseRemoteResourceChangedPayload,
type DeviceLinkConnectionIssue,
type DeviceLinkStatus,
+ type DeviceView,
type Envelope,
type InvokeResultPayload,
type LinkAcceptPayload,
@@ -30,7 +31,7 @@ import {
type Topic,
} from '@cindy/device-link';
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
-import { deviceLinkWsUrl } from '@/config/env';
+import { deviceLinkWsUrl, DEVICE_LINK_API_BASE_URL } from '@/config/env';
import { MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';
import { useAuth } from '@/auth/AuthContext';
import {
@@ -159,6 +160,7 @@ export interface DeviceLinkContextValue {
lastPresenceSnapshot: PresenceSnapshot | null;
/** 当前 relay 连接代内的逐设备 availability;null = 本代尚无权威 verdict。 */
getPresenceAvailability(deviceId: string): boolean | null;
+ readDeviceList(): Promise<{ devices: DeviceView[] }>;
openLink(deviceId: string): Promise<LinkAcceptPayload>;
/** 丢弃已结算的开链缓存并真正重开;并发重开仍按设备单飞。 */
reopenLink(deviceId: string): Promise<LinkAcceptPayload>;
@@ -361,6 +363,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
openLinkInFlightRef.current.get(deviceId)?.pending === true,
}), []);
const presenceAvailableByDeviceRef = useRef(new Map<string, boolean>());
+ const rosterConsumerRef = useRef<(() => (devices: DeviceView[]) => void) | null>(null);
+ const rosterRequestRef = useRef<{ client: DeviceLinkClient | null; epoch: number; promise: Promise<{ devices: DeviceView[] }> } | null>(null);
const presenceAvailabilityEpochsRef = useRef(createPresenceAvailabilityEpochs());
const presencePendingRecoveryDeviceIdsRef = useRef(new Set<string>());
const presenceUnavailableVerdictsRef = useRef(
@@ -382,6 +386,24 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const [lastPresenceSnapshot, setLastPresenceSnapshot] = useState<PresenceSnapshot | null>(null);
const accountGenerationRef = useRef<number | null>(null);
+ // Home and direct task entry share the same in-flight roster read. Evidence
+ // belongs to the connection that started it, not whichever one finishes it.
+ const readDeviceList = useCallback((): Promise<{ devices: DeviceView[] }> => {
+ const client = clientRef.current;
+ const epoch = connectionEpochRef.current;
+ const pending = rosterRequestRef.current;
+ if (pending?.client === client && pending.epoch === epoch) return pending.promise;
+ const apply = rosterConsumerRef.current?.();
+ const promise = auth.apiFetch<{ devices: DeviceView[] }>('/api/device-link/devices', {
+ baseUrl: DEVICE_LINK_API_BASE_URL, timeoutMs: 12_000,
+ }).then((result) => { apply?.(result.devices); return result; });
+ rosterRequestRef.current = { client, epoch, promise };
+ void promise.finally(() => {
+ if (rosterRequestRef.current?.promise === promise) rosterRequestRef.current = null;
+ }).catch(() => undefined);
+ return promise;
+ }, [auth.apiFetch, auth.accountGeneration]);
+
const clearPerAccountDeviceLinkState = useCallback(() => {
remoteSessionStore.clear();
clearSessionScheduleIndexCache();
@@ -419,12 +441,18 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
allowProbe = false,
refreshSettled = false,
) => {
+ const checkAvailability = () => {
+ if (presenceAvailableByDeviceRef.current.get(deviceId) === false) {
+ const disabled = presenceUnavailableVerdictsRef.current.get(deviceId)?.kind === 'disabled';
+ throw new DeviceLinkError(disabled ? 'REMOTE_DISABLED' : 'DEVICE_OFFLINE', 'remote device is unavailable');
+ }
+ };
return getOrCreatePresenceTrackedRequest(
openLinkInFlightRef.current,
presenceAvailabilityEpochsRef.current,
remoteResponseEvidenceEpochs,
deviceId,
- () => sendOpenLinkWithAccessHandling(client, deviceId, allowProbe),
+ () => sendOpenLinkWithAccessHandling(client, deviceId, allowProbe, checkAvailability),
{ retainSuccessful: true, refreshSettled },
);
}, []);
@@ -437,7 +465,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const releaseGeneration = backgroundReleaseGenerationRef.current;
const record = recoveryDiagnostics.get(client)?.capture(deviceId, connectionEpochRef.current);
await confirmTrackedSubscription({
- isCurrent: () => !backgroundReleaseInFlightRef.current
+ isCurrent: () => presenceAvailableByDeviceRef.current.get(deviceId) !== false && !backgroundReleaseInFlightRef.current
&& backgroundReleaseGenerationRef.current === releaseGeneration && clientRef.current === client,
generation: () => `${connectionEpochRef.current}:${remoteSubscribedTopicsRef.current.generation(deviceId)}`,
missing: () => topicsMissingRemoteAck(remoteSubscribedTopicsRef.current, deviceId, topics)
@@ -447,7 +475,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
deviceId,
toSend,
() => (
- !backgroundReleaseInFlightRef.current
+ presenceAvailableByDeviceRef.current.get(deviceId) !== false
+ && !backgroundReleaseInFlightRef.current
&& toSend.every((topic) => registryRef.current.hasTopic(deviceId, topic))
),
),
@@ -854,6 +883,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
setConnectionEpoch(connectionEpochRef.current);
resetRemoteProjectOrderPushFence();
void rehydrateWithClient(client);
+ // A new controller receives only presence deltas. Read the roster once so
+ // an already-offline host is known even when opening directly into history.
+ void readDeviceList().catch(() => undefined);
});
const offPeerTransportReset = client.onPeerTransportReset(({ deviceId }) => {
// 这是本地 ACK 超时,不是对端可达证据:只失效该 peer 的建链缓存和
@@ -868,7 +900,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
);
if (shouldRecover) void rehydrateWithClient(client, deviceId);
});
- const offPresence = client.onPresenceChanged((snap) => {
+ const applyPresence = (snap: PresenceSnapshot) => {
markPresenceAvailabilityEpoch(presenceAvailabilityEpochsRef.current, snap.deviceId);
// presence 变化代表目标链路代际变化(offline / remote-disabled / 恢复都一样):
// 上一代成功 link 不能跨代复用,下一次请求必须重新 link-open 确认。
@@ -885,7 +917,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
} else {
// Relay presence 是权威 availability verdict,普通目标应答不能推翻。
presenceUnavailableVerdictsRef.current.set(snap.deviceId, {
- kind: 'presence',
+ kind: snap.online && !snap.remoteControlEnabled ? 'disabled' : 'presence',
responseEvidenceEpoch: capturePresenceAvailabilityEpoch(
remoteResponseEvidenceEpochs,
snap.deviceId,
@@ -936,7 +968,26 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// 解除点只有:transport-timeout / 新连接代际 / 显式 openLink 成功
// (见 linkClose.ts 的具名 lift 入口)。
if (presence.recovered) void rehydrateWithClient(client, snap.deviceId);
- });
+ };
+ const offPresence = client.onPresenceChanged(applyPresence);
+ rosterConsumerRef.current = () => {
+ const epoch = connectionEpochRef.current;
+ const presenceEpoch = presenceAvailabilityEpochsRef.current.next;
+ const responseEpoch = remoteResponseEvidenceEpochs.next;
+ return (devices) => {
+ if (clientRef.current !== client || connectionEpochRef.current !== epoch || client.getStatus() !== 'online') return;
+ for (const device of devices) {
+ const available = device.online && device.remoteControlEnabled;
+ const disabled = device.online && !device.remoteControlEnabled;
+ const wasDisabled = presenceUnavailableVerdictsRef.current.get(device.deviceId)?.kind === 'disabled';
+ if (device.isSelf || (presenceAvailableByDeviceRef.current.get(device.deviceId) === available && disabled === wasDisabled)
+ || (presenceAvailabilityEpochsRef.current.byDevice.get(device.deviceId) ?? 0) > presenceEpoch
+ || (!device.online && (remoteResponseEvidenceEpochs.byDevice.get(device.deviceId) ?? 0) > responseEpoch)) continue;
+ applyPresence({ ...device, deviceName: device.name, platform: device.platform ?? '',
+ appVersion: device.appVersion ?? '', lastSeenAt: Date.parse(device.lastSeenAt ?? '') || 0 });
+ }
+ };
+ };
const offFrame = client.onFrame((env) => routeFrame(env, {
currentDataOwnerId: currentDataOwnerIdRef.current,
onAccessRevoked: (deviceId) => {
@@ -1184,6 +1235,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
offStatus();
offIssue();
client.stop();
+ rosterConsumerRef.current = null;
+ rosterRequestRef.current = null;
peerRecoverySchedulerRef.current?.clear();
clearAllPresenceWipeTimers(presenceWipeTimersRef.current);
openLinkInFlightRef.current.clear();
@@ -1205,6 +1258,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
publishPresenceAvailabilityMutation,
rehydrateWithClient,
requestForcedPeerRecovery,
+ readDeviceList,
]);
const openLink = useCallback(
@@ -1241,7 +1295,15 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
args: unknown[] = [],
opts?: { preSend?: () => void },
) => {
- return sendInvokeWithAccessHandling<T>(requireClient(clientRef.current), deviceId, channel, args, opts);
+ const preSend = () => {
+ if (presenceAvailableByDeviceRef.current.get(deviceId) === false) {
+ const disabled = presenceUnavailableVerdictsRef.current.get(deviceId)?.kind === 'disabled';
+ throw new DeviceLinkError(disabled ? 'REMOTE_DISABLED' : 'DEVICE_OFFLINE', 'remote device is unavailable');
+ }
+ opts?.preSend?.();
+ };
+ preSend();
+ return sendInvokeWithAccessHandling<T>(requireClient(clientRef.current), deviceId, channel, args, { preSend });
}, []);
const subscribe = useCallback(async (owner: string, deviceId: string, topics: string[]) => {
@@ -1268,12 +1330,12 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const toSend = normalizeDeviceLinkTopics([...new Set([...released, ...staleUnheld])]);
markRemoteTopicsUnsubscribed(remoteSubscribedTopicsRef.current, deviceId, toSend);
noteSessionLiveStreamsInterrupted(toSend);
- if (toSend.length === 0) return;
+ if (toSend.length === 0 || presenceAvailableByDeviceRef.current.get(deviceId) === false) return;
await sendUnsubscribe(
requireClient(clientRef.current),
deviceId,
toSend,
- (topic) => !registryRef.current.hasTopic(deviceId, topic),
+ (topic) => presenceAvailableByDeviceRef.current.get(deviceId) !== false && !registryRef.current.hasTopic(deviceId, topic),
);
}, []);
@@ -1289,6 +1351,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
lastPresenceSnapshot,
getSubscriptionIdentity: (deviceId, topics) => remoteSubscribedTopicsRef.current.identity(deviceId, topics),
getPresenceAvailability,
+ readDeviceList,
openLink,
reopenLink,
closeLink,
@@ -1302,6 +1365,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
connectionEpoch,
connectionIssue,
getPresenceAvailability,
+ readDeviceList,
invoke,
lastPresenceSnapshot,
openLink,
@@ -1617,15 +1681,18 @@ function sendOpenLinkWithAccessHandling(
client: DeviceLinkClient,
deviceId: string,
allowProbe = false,
+ preSend?: () => void,
): Promise<LinkAcceptPayload> {
- return withAccessRevokedHandling(deviceId, () => sendOpenLink(client, deviceId, allowProbe));
+ return withAccessRevokedHandling(deviceId, () => sendOpenLink(client, deviceId, allowProbe, preSend));
}
async function sendOpenLink(
client: DeviceLinkClient,
deviceId: string,
allowProbe = false,
+ preSend?: () => void,
): Promise<LinkAcceptPayload> {
+ preSend?.();
// 熔断门禁放在连接等待之前:open 时快速失败,不消耗 1.5s 重连等待也不上管道。
const slot = acquireDeviceSendSlot(deviceId, undefined, { allowProbe });
try {
@@ -1635,6 +1702,7 @@ async function sendOpenLink(
throw err;
}
try {
+ preSend?.();
const accepted = await client.openLink(deviceId, {
controllerName: mobileDeviceName(),
protocolVersion: PROTOCOL_VERSION,
diff --git a/apps/mobile/src/i18n/locales/en/deviceLink.json b/apps/mobile/src/i18n/locales/en/deviceLink.json
index ce96d91ce3..3d96eb7986 100644
--- a/apps/mobile/src/i18n/locales/en/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/en/deviceLink.json
@@ -1,4 +1,8 @@
{
+ "cachedHistory": {
+ "title": "Computer not connected",
+ "hint": "Saved content is available. Connect your computer to load more."
+ },
"recovery": {
"syncing": "Syncing…",
"recovered": "Restored",
diff --git a/apps/mobile/src/i18n/locales/ja/deviceLink.json b/apps/mobile/src/i18n/locales/ja/deviceLink.json
index e127b01a3a..7339b0fa49 100644
--- a/apps/mobile/src/i18n/locales/ja/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/ja/deviceLink.json
@@ -1,4 +1,8 @@
{
+ "cachedHistory": {
+ "title": "コンピューター未接続",
+ "hint": "保存済みの内容を表示できます。続きを読み込むには接続が必要です。"
+ },
"recovery": {
"syncing": "同期中…",
"recovered": "復旧しました",
diff --git a/apps/mobile/src/i18n/locales/ko/deviceLink.json b/apps/mobile/src/i18n/locales/ko/deviceLink.json
index 9b3feff7b6..c547aedb3f 100644
--- a/apps/mobile/src/i18n/locales/ko/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/ko/deviceLink.json
@@ -1,4 +1,8 @@
{
+ "cachedHistory": {
+ "title": "컴퓨터 연결 안 됨",
+ "hint": "저장된 내용을 볼 수 있습니다. 더 불러오려면 컴퓨터를 연결하세요."
+ },
"recovery": {
"syncing": "동기화 중…",
"recovered": "복구됨",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json b/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json
index bca686786c..e11eba824d 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json
@@ -1,4 +1,8 @@
{
+ "cachedHistory": {
+ "title": "电脑未连接",
+ "hint": "可查看已缓存内容,更多内容需电脑在线后加载。"
+ },
"recovery": {
"syncing": "正在同步…",
"recovered": "已恢复",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json b/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json
index 8c44c3633a..69e0f226ef 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json
@@ -1,4 +1,8 @@
{
+ "cachedHistory": {
+ "title": "電腦未連線",
+ "hint": "可查看已快取內容,更多內容需電腦上線後載入。"
+ },
"recovery": {
"syncing": "正在同步…",
"recovered": "已恢復",
diff --git a/apps/mobile/src/session/homeChromeMenus.ts b/apps/mobile/src/session/homeChromeMenus.ts
index 12176dba64..89481ccf26 100644
--- a/apps/mobile/src/session/homeChromeMenus.ts
+++ b/apps/mobile/src/session/homeChromeMenus.ts
@@ -7,7 +7,7 @@ import type {
HomeStatusFilter,
} from "@/session/homeListPriority";
import type { HomeProjectOrder } from "@/session/homeProjectOrder";
-import type { MobileHomeDeviceFilterItem } from "@/session/mobileHome";
+import { canBrowseMobileHomeDevice, type MobileHomeDeviceFilterItem } from "@/session/mobileHome";
export type { HomeListSortBy, HomeProjectOrder, HomeStatusFilter };
@@ -32,7 +32,7 @@ export function buildHomeScopeMenuItems(
): ChromeActionMenuItem[] {
const allFilter = filters.find((item) => item.deviceId === null) ?? null;
const deviceFilters = filters.filter(
- (item) => item.deviceId !== null && item.available,
+ (item) => item.deviceId !== null && canBrowseMobileHomeDevice(item),
);
const items: ChromeActionMenuItem[] = [];
if (allFilter) {
@@ -210,7 +210,7 @@ export function buildHomeScopePullDownActions(
): NativePullDownAction[] {
const allFilter = filters.find((item) => item.deviceId === null) ?? null;
const deviceFilters = filters.filter(
- (item) => item.deviceId !== null && item.available,
+ (item) => item.deviceId !== null && canBrowseMobileHomeDevice(item),
);
const items: NativePullDownAction[] = [];
if (allFilter) {
diff --git a/apps/mobile/src/session/remoteHistoryView.ts b/apps/mobile/src/session/remoteHistoryView.ts
index d45be766da..b1da29b6ef 100644
--- a/apps/mobile/src/session/remoteHistoryView.ts
+++ b/apps/mobile/src/session/remoteHistoryView.ts
@@ -3,12 +3,13 @@ import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { getRemoteHistoryView, mountRemoteHistoryView } from './remoteHistoryViews';
export { findRemoteHistoryView } from './remoteHistoryViews';
-export function useRemoteHistoryView(deviceId: string | null | undefined, sessionId: string, maker: MobileMakerTransport, isActive: () => boolean) {
+export function useRemoteHistoryView(deviceId: string | null | undefined, sessionId: string, maker: MobileMakerTransport, isActive: () => boolean, networkAvailable = true) {
const activeRef = useRef(isActive);
activeRef.current = isActive;
const entry = useMemo(() => getRemoteHistoryView(deviceId ?? '', sessionId, maker), [deviceId, sessionId, maker]);
const view = entry.view;
const snapshot = useSyncExternalStore(view.subscribe, view.getSnapshot, view.getSnapshot);
+ useEffect(() => { view.setNetworkAvailable(networkAvailable); }, [view, networkAvailable]);
useEffect(() => {
if (!deviceId) return;
return mountRemoteHistoryView(entry, maker, activeRef.current());
diff --git a/packages/maker-shared/src/__tests__/historyViewOffline.test.ts b/packages/maker-shared/src/__tests__/historyViewOffline.test.ts
new file mode 100644
index 0000000000..73f5e42c19
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/historyViewOffline.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from 'vitest';
+import { HistoryViewController } from '../historyViewController.js';
+import { projectHistoryView } from '../historyViewProjection.js';
+import type { HistoryMessageSource, HistoryViewPage } from '../historyView.js';
+
+const message: HistoryMessageSource = { id: '1', clientId: 'c1', role: 'assistant', content: 'Saved answer', createdAt: '2026-09-09T00:00:00Z' };
+const page: HistoryViewPage<HistoryMessageSource> = { version: 1, items: projectHistoryView([message], false), hasMore: true, nextCursor: 'older' };
+
+describe('offline history reading', () => {
+ it('restores cached content without page, detail or interest requests and reconnects in place', async () => {
+ const transport = { page: vi.fn(async () => page), details: vi.fn(), expanded: vi.fn(async () => undefined) };
+ const view = new HistoryViewController<HistoryMessageSource>(transport);
+ view.setNetworkAvailable(false);
+ await view.restoreCachedView(async () => ({ ...view.getSnapshot(), ...page, ready: true }));
+ const items = view.getSnapshot().items;
+ view.setActive(false); view.setActive(true);
+ view.setExpanded('missing', true);
+ view.invalidate();
+ await view.refresh(true);
+ expect(await view.locate('c1', message.createdAt)).toEqual(message);
+ expect(await view.locate('absent', message.createdAt)).toBeNull();
+ expect(transport.page).not.toHaveBeenCalled();
+ expect(transport.details).not.toHaveBeenCalled();
+ expect(transport.expanded).not.toHaveBeenCalled();
+ expect(view.getSnapshot().items).toBe(items);
+ view.setNetworkAvailable(true);
+ await view.refresh();
+ expect(transport.page).toHaveBeenCalledTimes(1);
+ expect(view.getSnapshot().items).toBe(items);
+ view.setActive(false);
+ });
+
+ it('keeps a pending disk restore when the computer goes offline', async () => {
+ const transport = { page: vi.fn(async () => page), details: vi.fn(), expanded: vi.fn(async () => undefined) };
+ const view = new HistoryViewController<HistoryMessageSource>(transport);
+ const cached = { ...view.getSnapshot(), ...page, ready: true };
+ let finish!: (value: typeof cached) => void;
+ const pending = view.restoreCachedView(() => new Promise((resolve) => { finish = resolve; }));
+ view.setNetworkAvailable(false);
+ finish(cached);
+ await pending;
+ expect(view.getSnapshot().items).toEqual(page.items);
+ expect(view.getSnapshot().ready).toBe(true);
+ expect(transport.page).not.toHaveBeenCalled();
+ });
+
+ it('ignores an in-flight online response after going offline', async () => {
+ let finish!: (value: HistoryViewPage<HistoryMessageSource>) => void;
+ const expanded = vi.fn(async () => undefined);
+ const view = new HistoryViewController<HistoryMessageSource>({ page: () => new Promise((resolve) => { finish = resolve; }), details: vi.fn(), expanded });
+ const pending = view.refresh();
+ view.setNetworkAvailable(false);
+ finish(page); await pending;
+ expect(view.getSnapshot()).toMatchObject({ items: [], ready: false, loading: false });
+ expect(expanded).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.ts
index 5363ec7602..5f3d02edce 100644
--- a/packages/maker-shared/src/historyViewController.ts
+++ b/packages/maker-shared/src/historyViewController.ts
@@ -41,8 +41,11 @@ export class HistoryViewController<T extends HistoryMessageSource> {
};
private listeners = new Set<() => void>();
private generation = 0;
+ // Transport changes invalidate remote reads, not local disk restoration.
+ private cacheGeneration = 0;
private detailRuns = new Map<string, object>();
private active = true;
+ private networkAvailable = true;
private pagePromise: Promise<void> | null = null;
private pageOlder = false;
private pageGeneration = 0;
@@ -54,7 +57,19 @@ export class HistoryViewController<T extends HistoryMessageSource> {
// for the old source's page/detail requests.
private readonly intentQueue = { tail: Promise.resolve() as Promise<void> },
) {}
- isActive = (): boolean => this.active;
+ isActive = (): boolean => this.active && this.networkAvailable;
+ /** Offline reading retains the view, but never sends page/detail/interest requests. */
+ setNetworkAvailable(available: boolean): void {
+ if (this.networkAvailable === available) return;
+ this.networkAvailable = available;
+ this.generation++;
+ this.detailRuns.clear();
+ if (this.refreshTimer) clearTimeout(this.refreshTimer);
+ this.refreshTimer = null;
+ this.publish({ loading: false, details: new Map([...this.state.details].map(([key, detail]) =>
+ [key, detail.loading ? { ...detail, loading: false } : detail])) });
+ if (available && this.active) void this.refresh();
+ }
getSnapshot = (): HistoryViewSnapshot<T> => this.state;
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
@@ -68,9 +83,9 @@ export class HistoryViewController<T extends HistoryMessageSource> {
/** Optimistic local display only. A fresh response or reset always wins over disk IO. */
async restoreCachedView(read: () => Promise<HistoryViewSnapshot<T> | null>): Promise<void> {
if (this.state.ready || isHistoryViewUnavailable(this.state.error)) return;
- const generation = this.generation;
+ const generation = this.cacheGeneration;
const cached = await read().catch(() => null);
- if (!cached || this.state.ready || isHistoryViewUnavailable(this.state.error) || generation !== this.generation) return;
+ if (!cached || this.state.ready || isHistoryViewUnavailable(this.state.error) || generation !== this.cacheGeneration) return;
this.publish({ ...cached, loading: this.state.loading, error: this.state.error });
}
@@ -86,7 +101,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
if (!fresh && older === this.pageOlder && this.pageGeneration === this.generation) return this.pagePromise;
const generation = this.generation;
return this.pagePromise.then(() => {
- if (this.active && generation === this.generation && (fresh || !this.state.error)) return this.refresh(older);
+ if (this.isActive() && generation === this.generation && (fresh || !this.state.error)) return this.refresh(older);
});
}
this.pageOlder = older;
@@ -99,7 +114,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
/** Coalesce activity notices; full assistant streaming continues on its existing path. */
invalidate(): void {
- if (!this.active || this.refreshTimer) return;
+ if (!this.isActive() || this.refreshTimer) return;
this.refreshTimer = setTimeout(() => {
this.refreshTimer = null;
if (this.pagePromise) {
@@ -109,7 +124,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
}
private async readPage(older: boolean): Promise<void> {
- if (!this.active || this.state.loading || (older && !this.state.hasMore)) return;
+ if (!this.isActive() || this.state.loading || (older && !this.state.hasMore)) return;
const generation = this.generation;
const before = older ? this.state.nextCursor ?? undefined : undefined;
this.publish({ loading: true, error: null });
@@ -156,6 +171,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
// A downgraded Host must not leave a ready projection masking the raw
// fallback. Invalidate in-flight details and every cached source row.
this.generation++;
+ this.cacheGeneration++;
this.detailRuns.clear();
if (this.refreshTimer) clearTimeout(this.refreshTimer);
this.refreshTimer = null;
@@ -178,10 +194,11 @@ export class HistoryViewController<T extends HistoryMessageSource> {
}
private sendIntent(): void {
+ if (!this.networkAvailable) return;
// Serialize replacement intents: a late expand ACK can never win over collapse.
const generation = this.generation;
this.intentQueue.tail = this.intentQueue.tail.catch(() => undefined).then(async () => {
- if (generation !== this.generation) return;
+ if (generation !== this.generation || !this.networkAvailable) return;
// Empty replacement intents must release old interest even before a reset view is ready.
const summaries = this.active ? historyWorkSummaries(this.state.items).filter((item) => this.state.expanded.has(item.key)) : [];
await this.transport.expanded(summaries);
@@ -192,7 +209,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
}
async loadDetails(summary: HistoryWorkSummary): Promise<void> {
- if (!this.active || !this.state.expanded.has(summary.key) || this.detailRuns.has(summary.key)) return;
+ if (!this.isActive() || !this.state.expanded.has(summary.key) || this.detailRuns.has(summary.key)) return;
const existing = this.state.details.get(summary.key);
if (existing?.complete && existing.revision === summary.revision) return;
const token = {};
@@ -253,7 +270,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
&& value.firstMessageId === summary.firstMessageId && value.lastMessageId === summary.lastMessageId);
const cached = this.state.details.get(item.key);
let messages = cached?.complete && cached.revision === summary.revision ? [...cached.messages] : [];
- if (!messages.length) {
+ if (!messages.length && this.networkAvailable) {
// Search reads the bounded range without changing user expansion memory
// or subscribing to hidden activity. Mount/collapse cannot cancel it.
try {
@@ -277,7 +294,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
if (found) return found;
}
}
- if (!this.state.hasMore) return null;
+ if (!this.networkAvailable || !this.state.hasMore) return null;
await this.refresh(true);
if (this.state.error) throw this.state.error;
}
@@ -291,6 +308,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
this.refreshTimer = null;
this.active = active;
this.generation++;
+ this.cacheGeneration++;
this.detailRuns.clear();
this.publish({ loading: false });
this.sendIntent();
@@ -298,6 +316,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
}
reset(): void {
this.generation++;
+ this.cacheGeneration++;
this.detailRuns.clear();
this.publish({ items: [], details: new Map(), expanded: new Set(), ready: false,
nextCursor: null, hasMore: false, loading: false, error: null });
diff --git a/packages/maker-shared/src/mobileHome.ts b/packages/maker-shared/src/mobileHome.ts
index c6cb76a048..ef207cfa31 100644
--- a/packages/maker-shared/src/mobileHome.ts
+++ b/packages/maker-shared/src/mobileHome.ts
@@ -45,6 +45,11 @@ export interface MobileHomeDeviceFilterItem {
waitingCount: number;
}
+/** Cached history is readable offline; it never grants permission to control a device. */
+export function canBrowseMobileHomeDevice(item: MobileHomeDeviceFilterItem): boolean {
+ return item.available || (item.sessionCount > 0 && (item.state === 'offline' || item.state === 'unknown'));
+}
+
export interface MobileHomeProjectGroup {
deviceId: string | null;
deviceName: string;
@@ -278,14 +283,14 @@ function buildDeviceFilters(
if (!deviceId || deviceById.has(deviceId) || filters.some((item) => item.deviceId === deviceId)) continue;
const stats = statsByDevice.get(deviceId) ?? { sessionCount: 0, waitingCount: 0 };
filters.push({
- available: true,
+ available: false,
deviceId,
id: deviceId,
label: session.deviceLinkDeviceName || deviceId,
selected: selectedDeviceId === deviceId,
sessionCount: stats.sessionCount,
- state: 'ready',
- statusLabel: stats.waitingCount > 0 ? `${stats.waitingCount} 待处理` : '已同步',
+ state: 'unknown',
+ statusLabel: '',
waitingCount: stats.waitingCount,
});
}