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): 减少重复远程查询并补齐同步诊断 (#4205)

Dash16a414bb7404
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
index e2c7a36254..f2bcca46aa 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
@@ -1412,7 +1412,7 @@ describe('远程交互接线不变式', () => {
it('F8: 周期对账从实际 link status 启动,且状态 push 不被迟到快照覆盖', () => {
const src = read('features/device-link/useDeviceLinkRemoteProjects.ts');
- expect(src).toContain('let linkOnline = false');
+ expect(src).toContain('let linkOnline: boolean | null = null');
expect(src).toContain("if (!linkStatusPushSeen) linkOnline = state.linkStatus === 'online'");
expect(src).toContain('linkStatusPushSeen = true');
// debounce 排队后 relay 可能已进入 connecting;执行时必须重查实时状态,不能离线重试。
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts
index 48f62ade18..71c5c8a5bc 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts
@@ -82,6 +82,70 @@ describe('archived session retry backoff', () => {
});
describe('startRemoteSessionsReconciler', () => {
+ it('preserves failure backoff while a window is hidden', async () => {
+ vi.useFakeTimers();
+ let visible = true;
+ const refresh = vi.fn(async () => 'gave-up');
+ const backoff = createReconcileBackoff({ baseMs: 10_000, jitter: (ms) => ms });
+ const stop = startRemoteSessionsReconciler(
+ () => new Map([['dev-a', 'Mac A']]),
+ refresh,
+ 1_000,
+ backoff,
+ () => visible,
+ );
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ visible = false;
+ await vi.advanceTimersByTimeAsync(2_000);
+ visible = true;
+ await vi.advanceTimersByTimeAsync(7_000);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(19_000);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(refresh).toHaveBeenCalledTimes(3);
+ stop();
+ });
+
+ it('pauses hidden window polling without duplicating pending requests on resume', async () => {
+ vi.useFakeTimers();
+ let visible = false;
+ let finish!: (result: string) => void;
+ const refresh = vi.fn(
+ () =>
+ new Promise<string>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const stop = startRemoteSessionsReconciler(
+ () => new Map([['dev-a', 'Mac A']]),
+ refresh,
+ 1_000,
+ undefined,
+ () => visible,
+ );
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(refresh).not.toHaveBeenCalled();
+ visible = true;
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ visible = false;
+ await vi.advanceTimersByTimeAsync(10_000);
+ visible = true;
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ finish('ok');
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ stop();
+ finish('ok');
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
it('periodically refreshes every eligible device and stops cleanly', async () => {
vi.useFakeTimers();
const eligible = new Map([
@@ -142,9 +206,7 @@ describe('startRemoteSessionsReconciler', () => {
['dev-good', 'Mac Good'],
]);
let badResult: string = 'gave-up';
- const refresh = vi.fn(async (deviceId: string) =>
- deviceId === 'dev-bad' ? badResult : 'ok',
- );
+ const refresh = vi.fn(async (deviceId: string) => (deviceId === 'dev-bad' ? badResult : 'ok'));
// 无抖动 + 假时钟,退避序列确定:失败 1 次后推迟 1s(=base),2 次后 2s,3 次后 4s…
const backoff = createReconcileBackoff({
baseMs: 1_000,
@@ -190,9 +252,10 @@ describe('startRemoteSessionsReconciler', () => {
const eligible = new Map([['dev-slow', 'Mac Slow']]);
let settle: ((r: string) => void) | null = null;
const refresh = vi.fn(
- () => new Promise<string>((resolve) => {
- settle = resolve;
- }),
+ () =>
+ new Promise<string>((resolve) => {
+ settle = resolve;
+ }),
);
const failures: string[] = [];
const backoff = createReconcileBackoff({ baseMs: 1_000, maxMs: 8_000, jitter: (d) => d });
diff --git a/apps/desktop/src/renderer/__tests__/orcaRemoteRoutingInvariants.test.ts b/apps/desktop/src/renderer/__tests__/orcaRemoteRoutingInvariants.test.ts
index d005e46c98..b2748535ff 100644
--- a/apps/desktop/src/renderer/__tests__/orcaRemoteRoutingInvariants.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaRemoteRoutingInvariants.test.ts
@@ -138,7 +138,7 @@ describe('orca 远程路由接线不变式', () => {
expect(src).toContain(
"import { useDeviceLinkRemoteProjects } from '@/features/device-link/useDeviceLinkRemoteProjects'",
);
- expect(src).toContain('useDeviceLinkRemoteProjects();');
+ expect(src).toContain("useDeviceLinkRemoteProjects(windowVisible, 'sidebar');");
});
it('右侧栏协同 tab close 不带路由副作用,避免 detached 窗口跳回 MainLayout', () => {
diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectsStartup.test.tsx b/apps/desktop/src/renderer/__tests__/remoteProjectsStartup.test.tsx
new file mode 100644
index 0000000000..8898ce1afb
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteProjectsStartup.test.tsx
@@ -0,0 +1,138 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({ refresh: vi.fn(async () => 'ok') }));
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ isAuthenticated: true, deviceId: 'self', dataOwnerId: 'owner' }),
+}));
+vi.mock('@/features/device-link/refreshRemoteSessions', () => ({
+ refreshRemoteDeviceSessions: state.refresh,
+ collectSessionListSnapshot: vi.fn(),
+}));
+vi.mock('@/features/device-link/mirrorCacheClient', () => ({
+ clearMirrorCacheAccountState: vi.fn(),
+ readCachedSessionList: async () => [],
+ sessionListOwnerTokensReady: () => true,
+ cancelSessionListPersist: vi.fn(),
+ scheduleSessionListPersist: vi.fn(),
+ clearCachedDevice: vi.fn(),
+}));
+vi.mock('@/hooks/useAgentCapabilities', () => ({
+ prefetchDeviceCapabilities: vi.fn(),
+ evictDeviceCapabilities: vi.fn(),
+}));
+vi.mock('@/hooks/useDeviceProviders', () => ({
+ prefetchDeviceProviders: vi.fn(),
+ evictDeviceProviders: vi.fn(),
+}));
+vi.mock('@/hooks/useGitSafetySettings', () => ({
+ prefetchDeviceGitSafetySettings: vi.fn(),
+ evictDeviceGitSafetySettings: vi.fn(),
+}));
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { useDeviceLinkRemoteProjects } from '@/features/device-link/useDeviceLinkRemoteProjects';
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ state.refresh.mockClear();
+ Reflect.deleteProperty(window, 'electronAPI');
+});
+
+it.each(['connecting', 'unknown', 'late-subscribe', 'late-snapshot'])('handles initial %s state without redundant bootstrap', async (initialStatus) => {
+ vi.useFakeTimers();
+ const listeners: Record<string, (...args: any[]) => void> = {};
+ let release!: () => void;
+ const subscribe = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ }),
+ );
+ let finishState!: (value: { linkStatus: string }) => void;
+ const initialState = new Promise<{ linkStatus: string }>((resolve) => { finishState = resolve; });
+ const api = {
+ getState: async () => {
+ if (initialStatus.startsWith('late-')) return initialState;
+ if (initialStatus === 'unknown') throw new Error('temporary IPC failure');
+ return { linkStatus: initialStatus };
+ },
+ listDevices: async () => ({
+ devices: [
+ { deviceId: 'peer', name: 'Peer', online: true, remoteControlEnabled: true, isSelf: false },
+ ],
+ }),
+ subscribe,
+ unsubscribe: vi.fn(async () => {}),
+ ...Object.fromEntries(
+ ['Responsiveness', 'Presence', 'Status', 'AccessRevoked', 'ControlTarget'].map((name) => [
+ `on${name}Changed`,
+ (callback: (...args: any[]) => void) => {
+ listeners[name] = callback;
+ return () => {};
+ },
+ ]),
+ ),
+ onAccessRevoked: () => () => {},
+ onRemotePush: () => () => {},
+ };
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { deviceLink: api } });
+ const { unmount } = renderHook(() => useDeviceLinkRemoteProjects());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ if (initialStatus.startsWith('late-')) {
+ await act(async () => {
+ listeners.Presence({ deviceId: 'peer', deviceName: 'Peer', online: true, remoteControlEnabled: true });
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ let finishRead: (() => void) | undefined;
+ if (initialStatus === 'late-snapshot') {
+ state.refresh.mockImplementationOnce(() => new Promise<string>((resolve) => { finishRead = () => resolve('ok'); }));
+ await act(async () => { release(); await vi.advanceTimersByTimeAsync(0); });
+ }
+ expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().has('peer')).toBe(true);
+ await act(async () => { finishState({ linkStatus: 'connecting' }); await vi.advanceTimersByTimeAsync(0); });
+ expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().has('peer')).toBe(false);
+ await act(async () => { finishRead?.(); release(); await vi.advanceTimersByTimeAsync(0); });
+ expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().has('peer')).toBe(false);
+ expect(state.refresh).toHaveBeenCalledTimes(initialStatus === 'late-snapshot' ? 1 : 0);
+ unmount();
+ return;
+ }
+ if (initialStatus === 'unknown') {
+ expect(subscribe).toHaveBeenCalledTimes(1);
+ await act(async () => { release(); await vi.advanceTimersByTimeAsync(0); });
+ expect(state.refresh).toHaveBeenCalledTimes(1);
+ unmount();
+ return;
+ }
+ expect(subscribe).not.toHaveBeenCalled();
+ await act(async () => {
+ listeners.Status({ status: 'online' });
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(subscribe).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ listeners.Status({ status: 'online' });
+ release();
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(subscribe).toHaveBeenCalledTimes(1);
+ expect(state.refresh).toHaveBeenCalledTimes(1);
+ await act(async () => {
+ listeners.Status({ status: 'connecting' });
+ listeners.Status({ status: 'online' });
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(subscribe).toHaveBeenCalledTimes(2);
+ await act(async () => {
+ listeners.Status({ status: 'connecting' });
+ expect(remoteProjectsStore.getBootstrapLoadingDeviceIds().has('peer')).toBe(false);
+ release();
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(state.refresh).toHaveBeenCalledTimes(1);
+ unmount();
+});
diff --git a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
index fad4dd375c..63520c8836 100644
--- a/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx
@@ -68,7 +68,6 @@ interface SidebarWindowContext {
export function SidebarWindowLayout() {
const { t } = useTranslation();
const { effectiveLocale, setLocale } = useLocale();
- useDeviceLinkRemoteProjects();
// 意识面板注册:子窗口没有 LayoutRoot,必须自行初始化 ghost 面板注册表
// 并订阅 ghosts:changed(停靠形态所需;历史持久化的 ghost 页签也靠它识别 kind)。
ensureGhostPanelsRegistered();
@@ -82,6 +81,7 @@ export function SidebarWindowLayout() {
const [ctx, setCtx] = useState<SidebarWindowContext | null>(null);
// 预热窗口初始隐藏;由 main 的 visibility push 驱动 Shell 内各子面板暂停/恢复。
const [windowVisible, setWindowVisible] = useState(false);
+ useDeviceLinkRemoteProjects(windowVisible, 'sidebar');
const visibilityRevisionRef = useRef(0);
const contextRevisionRef = useRef(0);
const presentationReadySentRef = useRef(false);
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
index c9136b8c54..08f899f515 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
@@ -31,7 +31,7 @@
* 边界(main 的 teardownAuthAccountBoundary),这里只负责作废未落盘的回写。
*/
-import { useEffect } from 'react';
+import { useEffect, useRef } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
import { createLogger } from '@/lib/logger';
@@ -196,12 +196,15 @@ export function startRemoteSessionsReconciler(
refresh: RemoteSessionsRefresh = refreshRemoteDeviceSessions,
intervalMs = RECONCILE_INTERVAL_MS,
backoff: ReconcileBackoff = createReconcileBackoff({ baseMs: intervalMs }),
+ isActive: () => boolean = () => true,
): () => void {
// 单次刷新可能横跨多个 tick(弱网下超时链 >10s);weak coalescing 会让后续 tick 拿到
// 同一个在途 Promise,若每个 tick 都挂 then,一次 gave-up 会被重复记账、退避直接跳档
// (review P2)。per-device 在途标记保证一次合并请求只记一次。
const inFlight = new Set<string>();
const timer = setInterval(() => {
+ // Hidden auxiliary windows retain their push mirror and failure backoff, but do no polling.
+ if (!isActive()) return;
const seen = new Set<string>();
for (const [deviceId, name] of getEligibleDevices()) {
seen.add(deviceId);
@@ -249,8 +252,10 @@ export function resolveIneligibleRemoteProjectAction(input: {
return 'remove';
}
-export function useDeviceLinkRemoteProjects(): void {
+export function useDeviceLinkRemoteProjects(periodicReconcileActive = true, windowRole: 'main' | 'sidebar' = 'main'): void {
const { isAuthenticated, deviceId: selfDeviceId, dataOwnerId } = useAuth();
+ const periodicReconcileActiveRef = useRef(periodicReconcileActive);
+ periodicReconcileActiveRef.current = periodicReconcileActive;
// 账号边界真正由 dataOwnerId 界定:登出 / 切账号都必然改变它。**不能只靠 !isAuthenticated** ——
// 运行时替换刷新路径可以在不经过 signed-out 的情况下直接把新 owner 发布出来,那时本 effect
@@ -291,7 +296,7 @@ export function useDeviceLinkRemoteProjects(): void {
*/
const cacheHydrationBlocked = new Set<string>();
/** relay 在线时才跑 anti-entropy;初始状态未知时保守暂停,避免离线失败重试。 */
- let linkOnline = false;
+ let linkOnline: boolean | null = null;
/** push 一旦到达即权威:迟到的 getState 快照不得覆盖更新的 link status。 */
let linkStatusPushSeen = false;
/** 当前合格设备:deviceId → 友好名 */
@@ -363,7 +368,11 @@ export function useDeviceLinkRemoteProjects(): void {
* bootstrap(退化为「快照可见、live 更新缺失」;被控端/控制端同版本时不会发生)。
* 任一步返回 ACCESS_REVOKED → 标记已撤销并移除该设备;全程无撤销 → 清掉残留标记(恢复收尾)。
*/
+ const canBootstrap = (deviceId: string): boolean =>
+ !disposed && linkOnline !== false && eligible.has(deviceId);
const runSubscribeAndBootstrap = async (deviceId: string, name: string): Promise<void> => {
+ if (!canBootstrap(deviceId)) return;
+ log.debug(`sessions refresh trigger=bootstrap window=${windowRole} peer=${deviceId.slice(0, 8)} visible=${periodicReconcileActiveRef.current}`);
// 新一轮 bootstrap 是有意义的重试:即使还保留旧 shard 也要显式进入
// loading,直到本轮落下 snapshot 或再次终态失败。
remoteProjectsStore.markBootstrapLoading(deviceId);
@@ -373,12 +382,12 @@ export function useDeviceLinkRemoteProjects(): void {
if (isAccessRevoked(err)) return void handleRevoked(deviceId);
if (!disposed) log.debug(`subscribe(sessions) failed for ${deviceId.slice(0, 8)}`, err);
}
- if (disposed || !eligible.has(deviceId)) return;
+ if (!canBootstrap(deviceId)) return;
// bootstrap 期间被撤销(subscribe 成功、list 被拒)→ refreshRemoteDeviceSessions 返 'revoked'
// (而非静默 give-up)→ 这里 handleRevoked,而不是继续预取能力 / 清撤销标记无视拒绝。
const result = await refreshRemoteDeviceSessions(deviceId, name, { scope: 'both' });
if (result === 'revoked') return void handleRevoked(deviceId);
- if (disposed || !eligible.has(deviceId)) return;
+ if (!canBootstrap(deviceId)) return;
if (result === 'gave-up') {
// 永久错误(如旧被控端 CHANNEL_NOT_ALLOWED)或瞬态重试耗尽:不是权威空列表,
// 即使还有旧 shard 也必须标明本轮读取失败,不能把缓存伪装成刚返回的结果。
@@ -434,6 +443,9 @@ export function useDeviceLinkRemoteProjects(): void {
d.remoteControlEnabled &&
!disabledControlDeviceIds.has(d.deviceId);
if (ok) {
+ // Confirmed offline waits for the online reseed. Unknown retains the existing
+ // bootstrap fallback when getState fails and no subsequent status push arrives.
+ if (linkOnline === false) return;
const prevName = eligible.get(d.deviceId);
const wasEligible = prevName !== undefined;
eligible.set(d.deviceId, d.name);
@@ -588,6 +600,7 @@ export function useDeviceLinkRemoteProjects(): void {
const stopPeriodicReconcile = startRemoteSessionsReconciler(
() => (linkOnline ? eligible : []),
async (deviceId, name) => {
+ log.debug(`sessions refresh trigger=periodic window=${windowRole} peer=${deviceId.slice(0, 8)} visible=${periodicReconcileActiveRef.current}`);
// sessions:list 是 200 条有界窗口;refresh 层会保留窗口外 active 行,并有界补查
// 缺席缓存 id 的终态,不能直接把响应缺席解释成删除。
const result = await refreshRemoteDeviceSessions(deviceId, name, {
@@ -598,6 +611,9 @@ export function useDeviceLinkRemoteProjects(): void {
// 回传结果供 reconciler 的失败退避记账('gave-up' 加深退避,'ok' 复位)。
return result;
},
+ RECONCILE_INTERVAL_MS,
+ undefined,
+ () => periodicReconcileActiveRef.current,
);
// 目标设备「无响应」熔断翻转(main 权威):镜像给 UI;恢复时重跑 subscribe+bootstrap
@@ -621,6 +637,9 @@ export function useDeviceLinkRemoteProjects(): void {
.then((state) => {
if (disposed) return;
if (!linkStatusPushSeen) linkOnline = state.linkStatus === 'online';
+ // Presence can start bootstrap before this initial snapshot settles.
+ // Reuse disconnect cleanup to clear loading and invalidate in-flight snapshots.
+ if (!linkStatusPushSeen && !linkOnline) remoteProjectsStore.markAllDisconnected();
disabledControlDeviceIds = new Set(state.disabledControlDeviceIds ?? []);
// 「无响应」熔断镜像的初值:按设备合并,已被 push 覆盖的设备以 push 为准
// (store 初始为空,快照只需补写 unresponsive 的未覆盖设备)。
@@ -667,6 +686,7 @@ export function useDeviceLinkRemoteProjects(): void {
// WS 重连后:presence 重新对齐 + 对每个已合格设备重新 subscribe + 重新 bootstrap
// (被控端可能重启过、订阅 registry 清空,这步重建订阅;reseed 补新设备)。
const offStatus = window.electronAPI.deviceLink.onStatusChanged((p) => {
+ const wasOnline = linkOnline;
linkStatusPushSeen = true;
linkOnline = p.status === 'online';
if (p.status !== 'online') {
@@ -692,6 +712,7 @@ export function useDeviceLinkRemoteProjects(): void {
if (p.status === 'stopped') revokedDevicesStore.clearAll();
return;
}
+ if (wasOnline) return;
for (const [deviceId, name] of eligible) void subscribeAndBootstrap(deviceId, name);
reseed();
});
@@ -777,5 +798,5 @@ export function useDeviceLinkRemoteProjects(): void {
clearRemoteSessionActivity();
revokedDevicesStore.clearAll();
};
- }, [isAuthenticated, selfDeviceId]);
+ }, [isAuthenticated, selfDeviceId, windowRole]);
}
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index 3f2c6c58b2..96bc85a8bc 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -41,7 +41,6 @@ import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { useRemoteSyncTask } from '@/device-link/remoteSyncTask';
import {
automationGroupKey,
- buildSessionMessagePreviewIndex,
buildRemoteSessionListContext,
buildRemoteSessionSections,
deviceSessionEmptyState,
@@ -367,10 +366,7 @@ function DeviceDetailScreenContent() {
// useStableValue 在内容未变时保留旧引用,阻断 sections 派生链的无谓全量重建
// (与首页同款处理,风暴背景见 devices/index.tsx 对应注释)。
const messagePreviewIndexRaw = useMemo(
- () => buildSessionMessagePreviewIndex(
- sessions.map((session) => session.id),
- (sessionId) => remoteSessionStore.getMessages(sessionId),
- ),
+ () => remoteSessionStore.getSessionListMessagePreviewIndex(sessions),
[messageVersion, sessions],
);
const messagePreviewIndex = useStableValue(messagePreviewIndexRaw, mapContentEqual);
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 06f5030019..74ed4b2073 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -203,7 +203,6 @@ import {
import { serializeNewSessionDeviceOptions } from '@/session/newSession';
import {
buildRemoteSessionCardPreview,
- buildSessionMessagePreviewIndex,
formatRemoteSessionSidebarTime,
getRemoteSessionPreviewCollapse,
type RemoteAutomationSessionGroup,
@@ -386,7 +385,6 @@ function HomeScreenContent() {
const syncInFlightRef = useRef<Promise<void> | null>(null);
const syncQueuedRef = useRef<{ visible?: boolean } | null>(null);
const loadHomeRef = useRef<(options?: { visible?: boolean }) => Promise<void>>(async () => undefined);
- const homePreviewCacheRef = useRef(new Map<string, { messages: readonly unknown[]; preview?: string }>());
const homePendingCacheRef = useRef(new Map<string, { pending: readonly unknown[]; count: number }>());
const homeLiveActivityIndexRef = useRef(new Map<string, RemoteSessionLiveActivity>());
const devicesRef = useRef<DeviceView[]>([]);
@@ -1643,24 +1641,7 @@ function HomeScreenContent() {
const messagePreviewIndexRaw = useMemo(() => {
// 普通首页的预览由可见行按 session 订阅。只有搜索需要跨全部任务建立消息索引。
if (!normalizedSearchQuery) return new Map<string, string>();
- const next = new Map<string, string>();
- const activeIds = new Set<string>();
- for (const session of sessions) {
- activeIds.add(session.id);
- const messages = remoteSessionStore.getMessages(session.id);
- const cached = homePreviewCacheRef.current.get(session.id);
- if (cached?.messages === messages) {
- if (cached.preview) next.set(session.id, cached.preview);
- continue;
- }
- const preview = buildSessionMessagePreviewIndex([session.id], () => messages).get(session.id);
- homePreviewCacheRef.current.set(session.id, { messages, preview });
- if (preview) next.set(session.id, preview);
- }
- for (const sessionId of homePreviewCacheRef.current.keys()) {
- if (!activeIds.has(sessionId)) homePreviewCacheRef.current.delete(sessionId);
- }
- return next;
+ return remoteSessionStore.getSessionListMessagePreviewIndex(sessions);
}, [messageSearchVersion, normalizedSearchQuery, sessions]);
const messagePreviewIndex = useStableValue(messagePreviewIndexRaw, mapContentEqual);
const pendingInteractionIndexRaw = useMemo(() => {
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index a97f55b6ed..2988552f22 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -3226,6 +3226,13 @@ export default function SessionScreen() {
// 旧连接代的 in-flight load 若在尾部读 ref 的最新值,会把旧窗口数据标成新代已同步,
// 抢在排队的 resync 之前放行回执。开始时捕获则旧 load 落的是旧代 key,门槛不放行。
const readAckEpochAtStart = readAckEpochRef.current;
+ const reportSyncPhase = (phase: string, extra: { readMs?: number; commitMs?: number; outcome?: string } = {}) => {
+ if (syncRun.isStale() || !messageAuthorityCurrent()) return;
+ mobileDebugLog('debug', 'recovery', 'detail sync phase', {
+ startedAt: snapshotStartedAt, connection: readAckEpochAtStart, phase,
+ totalMs: Math.max(0, Date.now() - snapshotStartedAt), ...extra,
+ });
+ };
const subscriptionIdentityAtStart = JSON.stringify([
deviceId,
sessionId,
@@ -3335,6 +3342,7 @@ export default function SessionScreen() {
setLoading(true);
try {
await prepareLinkAndSubscription();
+ reportSyncPhase('link-ready');
if (syncRun.isStale() || !messageAuthorityCurrent()) return;
// Capture at the first snapshot read, after link-open. An ACK received while
// opening the link is already covered; it must not force another full batch.
@@ -3401,22 +3409,34 @@ export default function SessionScreen() {
}
},
});
- const commitRead = <T,>(read: () => Promise<T>, commit: (value: T) => void) =>
- runConnectionScopedSessionMetadataRead(() => retryRead(read), isCurrent, commit);
+ const commitRead = <T,>(phase: string, read: () => Promise<T>, commit: (value: T) => void) => {
+ const startedAt = Date.now();
+ return runConnectionScopedSessionMetadataRead(() => retryRead(read), isCurrent, (value) => {
+ const commitAt = Date.now();
+ commit(value);
+ reportSyncPhase(phase, { readMs: Math.max(0, commitAt - startedAt), commitMs: Math.max(0, Date.now() - commitAt), outcome: 'applied' });
+ }).catch((error) => {
+ reportSyncPhase(phase, { readMs: Math.max(0, Date.now() - startedAt), outcome: 'failed' });
+ throw error;
+ });
+ };
// Only the control/read-receipt barrier waits for all resources. Each response
// is applied independently, and a changed metadata response starts history
// immediately rather than waiting for pending/projection/active.
await waitForIndependentSnapshotReads([
- messageRead,
- commitRead(fetchPendingInteractions, (pendingInteractions) => {
+ messageRead.then(() => reportSyncPhase('history-settled')).catch((error) => {
+ reportSyncPhase('history', { outcome: 'failed' });
+ throw error;
+ }),
+ commitRead('pending', fetchPendingInteractions, (pendingInteractions) => {
remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);
}),
- commitRead(fetchProjection, (projectionResult) => {
+ commitRead('projection', fetchProjection, (projectionResult) => {
remoteSessionStore.setInputProjectionIfCurrent(
sessionId, projectionResult.projection, projectionResult.authorityEpochAtStart,
);
}),
- commitRead(fetchActiveSessionSnapshot, (activeSessionSnapshot) => {
+ commitRead('active', fetchActiveSessionSnapshot, (activeSessionSnapshot) => {
remoteSessionStore.setActiveSessionSnapshots(
deviceId,
Array.isArray(activeSessionSnapshot.activeSessions) ? activeSessionSnapshot.activeSessions : [],
@@ -3437,8 +3457,7 @@ export default function SessionScreen() {
setContentSyncedKey(contentKeyAtStart);
if (contentKeyAtStart !== null && contentRecoveryKeyRef.current === contentKeyAtStart) {
syncRun.satisfy('subscription-acked');
- console.debug('[device-link] recovery snapshot applied', { elapsedMs: Date.now() - snapshotStartedAt });
- mobileDebugLog('debug', 'recovery', 'snapshot applied', { elapsedMs: Date.now() - snapshotStartedAt });
+ reportSyncPhase('complete');
}
// 已读回执门槛:本会话在当前连接代完成过整窗同步。sessionId / epoch / 门槛代号
// 都取 sync 开始时的快照——原地切 session、重连、attention 上升沿之后,启动更早
diff --git a/apps/mobile/src/__tests__/mobilePushRecovery.test.ts b/apps/mobile/src/__tests__/mobilePushRecovery.test.ts
index 220edf8f8e..4fda9d9d09 100644
--- a/apps/mobile/src/__tests__/mobilePushRecovery.test.ts
+++ b/apps/mobile/src/__tests__/mobilePushRecovery.test.ts
@@ -23,15 +23,42 @@ describe('background push recovery', () => {
const release = deferred<void>();
const stop = vi.fn();
const connect = vi.fn();
+ const report = vi.fn();
const releaseTopics = vi.fn(() => [release.promise]);
const lifecycle = createBackgroundConnection({
isBackground: () => background,
- releaseTopics, stop, connect,
+ releaseTopics, stop, connect, report,
graceMs: 2500, releaseWaitMs: 1000, suspendMs: 10_000,
});
- return { lifecycle, release, stop, connect, releaseTopics, active: () => { background = false; lifecycle.active(); } };
+ return { lifecycle, release, stop, connect, releaseTopics, report, active: () => { background = false; lifecycle.active(); } };
}
+ it('keeps stopping and reconnecting when a diagnostic sink throws', async () => {
+ const f = fixture();
+ f.report.mockImplementation(() => { throw new Error('diagnostic unavailable'); });
+ f.lifecycle.background();
+ await vi.advanceTimersByTimeAsync(3500);
+ expect(f.stop).toHaveBeenCalledTimes(1);
+ f.active();
+ expect(f.connect).toHaveBeenCalledTimes(1);
+ f.release.resolve();
+ f.lifecycle.dispose();
+ });
+
+ it('records grace execution and ignores release completion from an old background', async () => {
+ const f = fixture();
+ f.lifecycle.background();
+ expect(f.report).toHaveBeenLastCalledWith({ phase: 'background', generation: 1, elapsedMs: 0, releases: 1 });
+ await vi.advanceTimersByTimeAsync(2500);
+ expect(f.report).toHaveBeenLastCalledWith({ phase: 'grace-fired', generation: 1, elapsedMs: 2500 });
+ f.active();
+ const count = f.report.mock.calls.length;
+ f.release.resolve();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(f.report).toHaveBeenCalledTimes(count);
+ expect(f.stop).not.toHaveBeenCalled();
+ });
+
it('replaces a half-open socket immediately when JS was suspended during the final unsubscribe', async () => {
const f = fixture();
f.lifecycle.background();
@@ -41,6 +68,8 @@ describe('background push recovery', () => {
// Wall time passes without running timers: iOS suspended the JS runtime.
vi.setSystemTime(Date.now() + 60_000);
f.active();
+ expect(f.report).toHaveBeenCalledWith({ phase: 'active', generation: 1, elapsedMs: 62500 });
+ expect(f.report).toHaveBeenLastCalledWith({ phase: 'stop', generation: 1, elapsedMs: 62500, reason: 'suspended' });
expect(f.stop).toHaveBeenCalledTimes(1);
expect(f.connect).toHaveBeenCalledTimes(1);
expect(f.stop.mock.invocationCallOrder[0]).toBeLessThan(f.connect.mock.invocationCallOrder[0]);
@@ -78,6 +107,7 @@ describe('background push recovery', () => {
g.lifecycle.background();
await vi.advanceTimersByTimeAsync(3500);
expect(g.stop).toHaveBeenCalledTimes(1);
+ expect(g.report).toHaveBeenLastCalledWith({ phase: 'stop', generation: 1, elapsedMs: 3500, reason: 'grace', releaseOutcome: 'timed-out' });
g.lifecycle.dispose();
});
});
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 380b48f8ca..b24590f748 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -2055,6 +2055,130 @@ describe('remoteSessionStore', () => {
expect(remoteSessionStore.getMessageVersion()).toBeGreaterThan(versionAfterAppend);
});
+ it('uses fresh list metadata after opening history without rewriting the old message mirror', () => {
+ const meta = session('s1', { preview: 'old reply', _count: { messages: 1 } });
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [meta, session('s2')]);
+ remoteSessionStore.setMessages('s1', [{ ...message('m1', 's1'), content: 'old reply' }]);
+ remoteSessionStore.markSessionMessagesSynced('s1', meta);
+ const oldMirror = remoteSessionStore.getMessages('s1');
+ const first = vi.fn();
+ const second = vi.fn();
+ const offFirst = remoteSessionStore.subscribeSessionMessagePreview('s1', first);
+ const offSecond = remoteSessionStore.subscribeSessionMessagePreview('s2', second);
+ try {
+ // The history-view route commits fresh metadata but keeps persisted
+ // history outside this legacy mirror. Returning home must use that metadata.
+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', {
+ ...meta, preview: 'new reply', updatedAt: '2026-01-01T00:00:02.000Z', _count: { messages: 2 },
+ });
+ expect(remoteSessionStore.getMessages('s1')).toBe(oldMirror);
+ expect(remoteSessionStore.getSessionMessagePreview('s1')).toBe('old reply');
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('new reply');
+ expect(remoteSessionStore.getSessionListMessagePreviewIndex(remoteSessionStore.getSessions()).get('s1')).toBe('new reply');
+ expect(first).toHaveBeenCalled();
+ expect(second).not.toHaveBeenCalled();
+ } finally { offFirst(); offSecond(); }
+ });
+
+ it('notifies list previews when the same message array becomes synchronized', () => {
+ const meta = session('s1', { preview: 'host preview', _count: { messages: 1 } });
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [meta]);
+ remoteSessionStore.setMessages('s1', [{ ...message('m1', 's1'), content: 'loaded reply' }]);
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('host preview');
+ const changed = vi.fn();
+ const off = remoteSessionStore.subscribeSessionMessagePreview('s1', changed);
+ const version = remoteSessionStore.getMessageVersion();
+ try {
+ remoteSessionStore.markSessionMessagesSynced('s1', meta);
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('loaded reply');
+ expect(remoteSessionStore.getMessageVersion()).toBeGreaterThan(version);
+ expect(changed).toHaveBeenCalledTimes(1);
+ remoteSessionStore.markSessionMessagesSynced('s1', meta);
+ expect(changed).toHaveBeenCalledTimes(1);
+ remoteSessionStore.applySessionPatch('dev-1', 's1', { preview: 'edited reply' });
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('edited reply');
+ // Preview selection must not make the history-loading gate more eager.
+ expect(remoteSessionStore.isSessionMessageWindowSynced('s1', meta)).toBe(true);
+ remoteSessionStore.applySessionPatch('dev-1', 's1', { _count: { messages: 2 }, preview: 'next reply' });
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('next reply');
+ } finally { off(); }
+ });
+
+ it('preserves actual live text over metadata but does not trust cached streaming flags', () => {
+ vi.useFakeTimers();
+ try {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { preview: 'host preview' })]);
+ remoteSessionStore.setMessages('s1', [{ ...message('m1', 's1'), content: 'stale stream', agentMeta: { isStreaming: true } }]);
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('host preview');
+ pushMakerText('s1', 'live-tail', 'live reply', false);
+ vi.runOnlyPendingTimers();
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('live reply');
+ pushMakerText('s1', 'live-tail', ' continues', false);
+ vi.runOnlyPendingTimers();
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('live reply continues');
+ } finally { vi.useRealTimers(); }
+ });
+
+ it.each(['done', 'status'] as const)('retains received text when %s only finalizes streaming flags', (type) => {
+ vi.useFakeTimers();
+ try {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { preview: 'old reply' })]);
+ pushMakerText('s1', 'live-tail', 'new reply', false);
+ vi.runOnlyPendingTimers();
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1', event: { type, data: { isRunning: false } },
+ });
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('new reply');
+ } finally { vi.useRealTimers(); }
+ });
+
+ it('keeps loaded previews for old hosts without preview metadata', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ remoteSessionStore.setMessages('s1', [message('m1', 's1')]);
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('hello');
+ });
+
+ it.each([false, true])('refreshes the preview after missing completion in background (final received: %s)', (finalReceived) => {
+ vi.useFakeTimers();
+ try {
+ const meta = session('s1', { preview: 'earlier reply', _count: { messages: 1 } });
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [meta]);
+ pushMakerText('s1', 'live-tail', 'partial reply', finalReceived);
+ vi.runOnlyPendingTimers();
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('partial reply');
+ // No final/status push while suspended. The existing foreground loadHome
+ // refreshes sessions; it does not download all message mirrors.
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [{
+ ...meta, preview: 'completed reply', updatedAt: '2026-01-01T00:00:04.000Z', _count: { messages: 2 },
+ }]);
+ expect(remoteSessionStore.getSessionMessagePreview('s1')).toBe('partial reply');
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('completed reply');
+ expect(remoteSessionStore.getSessionListMessagePreviewIndex(remoteSessionStore.getSessions()).get('s1')).toBe('completed reply');
+ } finally { vi.useRealTimers(); }
+ });
+
+ it.each(['offline', 'deletion'] as const)('notifies when %s invalidates only message freshness', (reason) => {
+ const meta = session('s1', { preview: 'host reply', _count: { messages: 1 } });
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [meta]);
+ remoteSessionStore.setMessages('s1', [message('m1', 's1')]);
+ remoteSessionStore.markSessionMessagesSynced('s1', meta);
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('hello');
+ const changed = vi.fn();
+ const off = remoteSessionStore.subscribeSessionMessagePreview('s1', changed);
+ try {
+ if (reason === 'offline') remoteSessionStore.markDeviceOffline('dev-1');
+ else remoteSessionStore.removeMessages('s1', ['not-in-mirror']);
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('host reply');
+ expect(changed).toHaveBeenCalled();
+ } finally { off(); }
+ });
+
+ it('does not resurrect an old cached preview when Host explicitly clears it', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { preview: '' })]);
+ remoteSessionStore.setMessages('s1', [message('m1', 's1')]);
+ expect(remoteSessionStore.getSessionListMessagePreview('s1')).toBe('');
+ });
+
it('tracks which session metadata the message window has been synced against', () => {
const meta = session('s1', {
updatedAt: '2026-01-01T00:00:01.000Z',
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index 653e449355..1bad1023c0 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -57,7 +57,7 @@ describe('mobile session composer desktop-first surface', () => {
'const activityEpochAtFetchStart = remoteSessionStore.captureActiveSessionSnapshotEpoch();',
);
// First open and reopen share one progressive, independently retried reader.
- expect(source).toContain('commitRead(fetchActiveSessionSnapshot,');
+ expect(source).toContain("commitRead('active', fetchActiveSessionSnapshot,");
expect((source.match(/activeSessionSnapshot\.activityEpochAtFetchStart/g) ?? []).length).toBe(1);
expect((source.match(/maker\.listActiveSessions\(\)/g) ?? []).length).toBe(1);
});
diff --git a/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx b/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
index e061537d0e..8775340ea4 100644
--- a/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
+++ b/apps/mobile/src/__tests__/sessionListDrawerUpdates.test.tsx
@@ -329,9 +329,16 @@ describe("drawer selective updates", () => {
]);
await render();
expect(row("s1")?.textContent).toContain("host preview");
- await act(async () =>
- remoteSessionStore.setMessages("s1", [message("s1", "loaded preview")]),
- );
+ await act(async () => {
+ remoteSessionStore.setMessages("s1", [message("s1", "loaded preview")]);
+ });
+ expect(row("s1")?.textContent).toContain("host preview");
+ await act(async () => {
+ remoteSessionStore.markSessionMessagesSynced(
+ "s1",
+ session("s1", { preview: "host preview" }),
+ );
+ });
expect(row("s1")?.textContent).toContain("loaded preview");
await act(async () => remoteSessionStore.setMessages("s1", []));
expect(row("s1")?.textContent).toContain("host preview");
diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
index 3817314421..9fbf8b021a 100644
--- a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
@@ -79,6 +79,7 @@ function fixture(reopen = false, remoteHistoryAvailable = true) {
listActiveSessions: vi.fn(async () => []),
};
const bindings = {
+ mobileDebugLog: vi.fn(),
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') }) } },
@@ -266,6 +267,17 @@ describe('production session recovery callbacks', () => {
expect(f.state.hold).not.toBeNull();
});
+ it('reports failed history without clearing the read-receipt barrier', async () => {
+ const f = fixture();
+ const error = new Error('history unavailable');
+ f.maker.listMessages.mockRejectedValue(error);
+ await expect(f.sync()).rejects.toBe(error);
+ expect(f.bindings.mobileDebugLog).toHaveBeenCalledWith('debug', 'recovery', 'detail sync phase',
+ expect.objectContaining({ phase: 'history', outcome: 'failed', connection: 1 }));
+ expect(f.state.readAck).toBeNull();
+ expect(f.state.hold).not.toBeNull();
+ });
+
it('retains early progressive display while control state is pending', async () => {
const f = fixture();
const projection = deferred<object>();
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 5eeffd9750..9561da9ee8 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -839,6 +839,12 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
},
});
clientRef.current = client;
+ mobileDebugLog('debug', 'device-link', 'runtime identity', {
+ commit: /^[a-f0-9]{7,40}$/i.test(process.env.EXPO_PUBLIC_XDT_GIT_COMMIT ?? '')
+ ? process.env.EXPO_PUBLIC_XDT_GIT_COMMIT : 'unknown',
+ version: Constants.nativeAppVersion ?? 'unknown',
+ build: Constants.nativeBuildVersion ?? 'unknown',
+ });
const diagnostics = createRecoveryDiagnostics(
(event) => mobileDeviceLinkLogger.info('recovery phase', event),
() => connectionEpochRef.current,
@@ -1179,6 +1185,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
graceMs: BACKGROUND_STOP_GRACE_MS,
releaseWaitMs: BACKGROUND_FINAL_UNSUBSCRIBE_WAIT_MS,
suspendMs: BACKGROUND_SUSPEND_SUSPECT_MS,
+ report: (event) => mobileDebugLog('debug', 'device-link', 'background lifecycle', event),
});
const sub = AppState.addEventListener('change', (next) => {
if (next === 'active') {
diff --git a/apps/mobile/src/device-link/backgroundConnection.ts b/apps/mobile/src/device-link/backgroundConnection.ts
index 9051ee2b5c..9c616e606a 100644
--- a/apps/mobile/src/device-link/backgroundConnection.ts
+++ b/apps/mobile/src/device-link/backgroundConnection.ts
@@ -1,3 +1,13 @@
+export interface BackgroundConnectionDiagnostic {
+ phase: "background" | "release-settled" | "grace-fired" | "stop" | "active";
+ generation: number;
+ elapsedMs: number;
+ reason?: "grace" | "suspended";
+ releases?: number;
+ failed?: number;
+ releaseOutcome?: "settled" | "timed-out";
+}
+
interface BackgroundConnectionOptions {
isBackground(): boolean;
releaseTopics(): Promise<void>[];
@@ -6,14 +16,34 @@ interface BackgroundConnectionOptions {
graceMs: number;
releaseWaitMs: number;
suspendMs: number;
+ report?(event: BackgroundConnectionDiagnostic): void;
}
/** Owns the background grace period, including the async unsubscribe tail after its timer fires. */
-export function createBackgroundConnection(options: BackgroundConnectionOptions) {
+export function createBackgroundConnection(
+ options: BackgroundConnectionOptions,
+) {
let backgroundAt: number | null = null;
let generation = 0;
let stopTimer: ReturnType<typeof setTimeout> | null = null;
let releaseTimer: ReturnType<typeof setTimeout> | null = null;
+ const report = (
+ phase: BackgroundConnectionDiagnostic["phase"],
+ extra: Partial<BackgroundConnectionDiagnostic> = {},
+ ) => {
+ // Diagnostics must never prevent stop/connect or create an unhandled async tail.
+ try {
+ options.report?.({
+ phase,
+ generation,
+ elapsedMs:
+ backgroundAt === null ? 0 : Math.max(0, Date.now() - backgroundAt),
+ ...extra,
+ });
+ } catch {
+ /* best-effort diagnostic */
+ }
+ };
const clearTimers = () => {
if (stopTimer !== null) clearTimeout(stopTimer);
if (releaseTimer !== null) clearTimeout(releaseTimer);
@@ -24,29 +54,58 @@ export function createBackgroundConnection(options: BackgroundConnectionOptions)
clearTimers();
const captured = ++generation;
backgroundAt = Date.now();
- for (const release of options.releaseTopics()) void release.catch(() => undefined);
+ const initialReleases = options.releaseTopics();
+ report("background", { releases: initialReleases.length });
+ void Promise.allSettled(initialReleases).then((results) => {
+ if (captured !== generation) return;
+ report("release-settled", {
+ releases: results.length,
+ failed: results.filter((result) => result.status === "rejected")
+ .length,
+ });
+ });
stopTimer = setTimeout(() => {
stopTimer = null;
if (!options.isBackground() || generation !== captured) return;
+ report("grace-fired");
const releases = Promise.allSettled(options.releaseTopics());
const boundedWait = new Promise<void>((resolve) => {
releaseTimer = setTimeout(resolve, options.releaseWaitMs);
});
- void Promise.race([releases, boundedWait]).finally(() => {
+ void Promise.race([releases, boundedWait]).then((result) => {
if (generation !== captured) return;
clearTimers();
- if (options.isBackground()) options.stop();
+ if (options.isBackground()) {
+ report("stop", {
+ reason: "grace",
+ releaseOutcome: Array.isArray(result) ? "settled" : "timed-out",
+ ...(Array.isArray(result)
+ ? {
+ releases: result.length,
+ failed: result.filter(
+ (entry) => entry.status === "rejected",
+ ).length,
+ }
+ : {}),
+ });
+ options.stop();
+ }
});
}, options.graceMs);
},
active() {
+ const backgroundGeneration = generation;
const elapsed = backgroundAt === null ? 0 : Date.now() - backgroundAt;
+ report("active");
backgroundAt = null;
generation += 1;
clearTimers();
// A timer reference cannot tell whether the socket was actually stopped:
// JS can be suspended while the final unsubscribe is still awaiting ACK.
- if (elapsed > options.suspendMs) options.stop();
+ if (elapsed > options.suspendMs) {
+ report("stop", { reason: "suspended", elapsedMs: elapsed, generation: backgroundGeneration });
+ options.stop();
+ }
options.connect();
},
dispose() {
diff --git a/apps/mobile/src/session/SessionListDrawer.tsx b/apps/mobile/src/session/SessionListDrawer.tsx
index 3e760ffcf6..e15aadbe9f 100644
--- a/apps/mobile/src/session/SessionListDrawer.tsx
+++ b/apps/mobile/src/session/SessionListDrawer.tsx
@@ -72,7 +72,6 @@ import type { RemoteSessionLiveActivity } from '@/session/sessionList';
import { latestMobileSessionRow, resolveMobileSessionRowStatus } from '@/session/sessionRightStatus';
import {
buildRemoteSessionCardPreview,
- buildSessionMessagePreviewIndex,
formatRemoteSessionSidebarTime,
type RemoteSessionListItem,
} from '@/session/sessionList';
@@ -361,10 +360,7 @@ export function SessionListDrawer({
void homeStatusVersion;
void messageSearchVersion;
const messagePreviewIndex = searchQuery.trim()
- ? buildSessionMessagePreviewIndex(
- sessions.map((session) => session.id),
- (sessionId) => remoteSessionStore.getMessages(sessionId),
- )
+ ? remoteSessionStore.getSessionListMessagePreviewIndex(sessions)
: undefined;
// 与首页同口径的行内状态输入:等待授权/回复(awaiting)与 live error/done 都来自
// 这两个 index,缺了会全部退化成普通时间行。
@@ -565,11 +561,11 @@ const DrawerSessionRow = memo(function DrawerSessionRow({
// 运行态走订阅(行 memo 化后命令式读取会 stale,与首页行同一取舍)。
const latestItem = latestMobileSessionRow(item);
const sessionIsRunning = useSessionRunning(latestItem.session.id);
- const loadedMessagePreview = useRemoteSessionMessagePreview(item.session.id);
const running = sessionIsRunning || !!latestItem.scheduleInfo?.running;
const { status: rightStatus, target: statusTarget } = resolveMobileSessionRowStatus(item, sessionIsRunning);
// 索引搜索展示命中摘要;普通行(含自动化代表行)才使用自己的最新消息预览。
const previewItem = item.automationGroup ? statusTarget : item;
+ const loadedMessagePreview = useRemoteSessionMessagePreview(previewItem.session.id);
const preview = buildRemoteSessionCardPreview(
searchResult || loadedMessagePreview === undefined || loadedMessagePreview === previewItem.messagePreview
? previewItem
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 3ceac32d28..d497b6479e 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -26,6 +26,7 @@ import { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consume
import { applyCodexPlanSnapshotOnDone, markCodexPlanTurnFailed } from '@cindy/maker-shared/message-render';
import {
buildSessionMessagePreviewIndex,
+ sessionRowMessagePreview,
type RemoteSessionLiveActivity,
} from '@cindy/maker-shared/session-list';
import { buildDeviceIdentity, resolveCanonicalDeviceId } from '@cindy/maker-shared/mobile-home';
@@ -141,6 +142,7 @@ export interface RemoteSessionReconnectAttempt {
interface SessionMessageSyncMarker {
messageCount: number | null;
updatedAt: string;
+ preview?: string | null;
}
export interface SetLatestMessageWindowOptions {
@@ -692,7 +694,7 @@ const messageIdentityIndexes = new WeakMap<
>();
const messagePreviewCache = new WeakMap<
readonly RemoteMessage[],
- { preview: string | undefined }
+ { preview: string | undefined; liveSession?: RemoteSession }
>();
const EMPTY_MESSAGE_STRUCTURE_TOKEN = Object.freeze({ kind: 'empty-message-structure' });
const emptySessionMessageStructureTokens = new Map<string, object>();
@@ -1484,6 +1486,7 @@ function recomputeSessions(): void {
for (const { session, physicalDeviceId } of byId.values()) {
const prev = prevById.get(session.id);
const projected = applyPendingTitlePreview(session);
+ if (!prev || !remoteSessionEqual(prev, projected)) pendingMessagePreviewSessionIds.add(session.id);
next.push(prev && remoteSessionEqual(prev, projected) ? prev : projected);
sessionDeviceIndex.set(session.id, physicalDeviceId);
}
@@ -2444,6 +2447,26 @@ function applyRemoteTextEvent(
event: Record<string, unknown>,
persistId?: string,
deviceId?: string,
+): boolean {
+ const previous = messages.get(sessionId);
+ const changed = mergeRemoteTextEvent(sessionId, event, persistId, deviceId);
+ const list = messages.get(sessionId);
+ if (list && list !== previous) {
+ // Cache provenance with the extracted text, not with a lingering streaming
+ // pointer. Any later session metadata makes this live preview yield to Host.
+ messagePreviewCache.set(list, {
+ preview: buildSessionMessagePreviewIndex([sessionId], () => list).get(sessionId),
+ liveSession: sessionById(sessionId),
+ });
+ }
+ return changed;
+}
+
+function mergeRemoteTextEvent(
+ sessionId: string,
+ event: Record<string, unknown>,
+ persistId?: string,
+ deviceId?: string,
): boolean {
const data = isRecord(event.data) ? event.data : null;
const text = typeof data?.text === 'string' ? data.text : '';
@@ -2838,6 +2861,8 @@ function finalizeRemoteStreamingMessageByClientId(
return { ...message, agentMeta: clearStreamingMeta(message.agentMeta) };
});
if (!changed) return false;
+ const preview = messagePreviewCache.get(existing);
+ if (preview) messagePreviewCache.set(next, preview);
messages.set(sessionId, next);
bumpMessageVersion(sessionId);
return true;
@@ -2863,6 +2888,8 @@ function finalizeRemoteStreamingMessages(
return { ...message, agentMeta: clearStreamingMeta(mergedMeta) };
});
if (!changed) return false;
+ const preview = messagePreviewCache.get(existing);
+ if (preview) messagePreviewCache.set(next, preview);
messages.set(sessionId, next);
bumpMessageVersion(sessionId);
return true;
@@ -3525,9 +3552,13 @@ export const remoteSessionStore = {
return true;
},
- markSessionMessagesSynced(sessionId: string, session: Pick<RemoteSession, '_count' | 'updatedAt'>): void {
+ markSessionMessagesSynced(sessionId: string, session: Pick<RemoteSession, '_count' | 'updatedAt' | 'preview'>): void {
if (!sessionId) return;
+ if (this.isSessionMessageWindowSynced(sessionId, session)
+ && sessionMessageSyncMarkers.get(sessionId)?.preview === session.preview) return;
sessionMessageSyncMarkers.set(sessionId, buildSessionMessageSyncMarker(session));
+ bumpMessageVersion(sessionId);
+ emit();
},
isSessionMessageWindowSynced(sessionId: string, session: Pick<RemoteSession, '_count' | 'updatedAt'>): boolean {
@@ -3547,7 +3578,10 @@ export const remoteSessionStore = {
pendingRefreshSessions.delete(sessionId);
// A history read already in flight when the dirty push arrived may have
// reinstalled its older marker. The queued repair must still read history.
- sessionMessageSyncMarkers.delete(sessionId);
+ if (sessionMessageSyncMarkers.delete(sessionId)) {
+ bumpMessageVersion(sessionId);
+ emit();
+ }
return true;
},
@@ -3710,7 +3744,7 @@ export const remoteSessionStore = {
const next = existing.filter((message) => (
!deletedClientIds.has(message.clientId) && !deletedClientIds.has(message.id)
));
- sessionMessageSyncMarkers.delete(sessionId);
+ const syncMarkerChanged = sessionMessageSyncMarkers.delete(sessionId);
// 连续性结论随窗口一起失效:rewind 可能删掉中间的行,清空/回收更是整窗重来。
// 重置为未知,下一次最新窗口同步会重建(见 sessionWindowCoverage)。
forgetWindowCoverage(sessionId);
@@ -3762,7 +3796,7 @@ export const remoteSessionStore = {
applyMessageWriteRetention(sessionId);
}
resetRemoteHistoryViews(deviceId, sessionId);
- if (!messagesChanged && !tasksChanged && !projectionSettled) return;
+ if (!messagesChanged && !tasksChanged && !projectionSettled && !syncMarkerChanged) return;
bumpMessageVersion(sessionId);
emit();
},
@@ -4786,7 +4820,10 @@ export const remoteSessionStore = {
}
for (const [sessionId, indexedDeviceId] of sessionDeviceIndex) {
if (indexedDeviceId !== deviceId) continue;
- changed = sessionMessageSyncMarkers.delete(sessionId) || changed;
+ if (sessionMessageSyncMarkers.delete(sessionId)) {
+ bumpMessageVersion(sessionId);
+ changed = true;
+ }
changed = livePlanSnapshots.delete(sessionId) || changed;
changed = pendingRefreshSessions.delete(sessionId) || changed;
changed = deletePendingInteractionState(sessionId) || changed;
@@ -5021,6 +5058,27 @@ export const remoteSessionStore = {
return preview;
},
+ /** Lists must not let an old message mirror hide fresh history-view metadata. */
+ getSessionListMessagePreview(sessionId: string, session = sessionById(sessionId)): string | undefined {
+ const loaded = this.getSessionMessagePreview(sessionId);
+ if (!session || (this.isSessionMessageWindowSynced(sessionId, session)
+ && sessionMessageSyncMarkers.get(sessionId)?.preview === session.preview)) return loaded;
+ // Only text received against the current metadata may outrun its preview.
+ // A missed done event must not let an old stream win after foreground refresh.
+ const cached = messagePreviewCache.get(messages.get(sessionId) ?? emptyMessages);
+ if (cached?.liveSession === session) return loaded;
+ return sessionRowMessagePreview(session) ?? (typeof session.preview === 'string' ? '' : loaded);
+ },
+
+ getSessionListMessagePreviewIndex(sessions: readonly RemoteSession[]): Map<string, string> {
+ const index = new Map<string, string>();
+ for (const session of sessions) {
+ const preview = this.getSessionListMessagePreview(session.id, session);
+ if (preview) index.set(session.id, preview);
+ }
+ return index;
+ },
+
getMessageVersion(): number {
return messageVersion;
},
@@ -5364,10 +5422,11 @@ function writeSessionRunStatus(sessionId: string, next: RemoteSessionRunStatus):
return true;
}
-function buildSessionMessageSyncMarker(session: Pick<RemoteSession, '_count' | 'updatedAt'>): SessionMessageSyncMarker {
+function buildSessionMessageSyncMarker(session: Pick<RemoteSession, '_count' | 'updatedAt' | 'preview'>): SessionMessageSyncMarker {
const count = session._count?.messages;
return {
updatedAt: session.updatedAt,
+ preview: session.preview,
messageCount: typeof count === 'number' && Number.isFinite(count) ? count : null,
};
}
@@ -5598,7 +5657,7 @@ export function useRemoteSessionMessagePreview(sessionId: string): string | unde
);
return usePausableRemoteSessionStoreSnapshot(
`message-preview:${sessionId}`,
- useCallback(() => remoteSessionStore.getSessionMessagePreview(sessionId), [sessionId]),
+ useCallback(() => remoteSessionStore.getSessionListMessagePreview(sessionId), [sessionId]),
subscribe,
);
}
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 7f8596fe86..5a4c5fed58 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -1596,6 +1596,30 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('redacts unknown channels from reliable timeout diagnostics', async () => {
+ vi.useFakeTimers();
+ const warn = vi.fn();
+ const h = makeHarness({
+ timing: { pingIntervalMs: 60_000, transportRetryIntervalMs: 5, transportMaxRetryAttempts: 2 },
+ logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() },
+ });
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(0);
+ h.current().ack();
+ const opened = establishInboundReliableLink(h, 'unknown-channel-stream');
+ await vi.advanceTimersByTimeAsync(0);
+ await opened;
+ h.client.sendPush('dev-b', 'private-user-content\nforged-log', { secret: 'private-body' });
+ await vi.advanceTimersByTimeAsync(50);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('kind=push channel=unknown'));
+ expect(JSON.stringify(warn.mock.calls)).not.toMatch(/private-user-content|forged-log|private-body/);
+ } finally {
+ h.client.stop();
+ vi.useRealTimers();
+ }
+ });
+
it('入站 link 的可靠重试耗尽只重置该 peer link:relay 连接不拆,发 transport-timeout link-close,重开后 live 帧按原 seq 重放', async () => {
vi.useFakeTimers();
const warn = vi.fn();
@@ -1638,7 +1662,7 @@ describe('DeviceLinkClient', () => {
expect(firstSocket.closed).toBeNull();
expect(h.sockets).toHaveLength(1);
expect(warn).toHaveBeenCalledWith(expect.stringMatching(
- /ACK timeout; resetting peer link .*dst=dev-b seq=1 kind=push request=\S+ attempts=2 sent=true ageMs=\d+ pending=2\/\d+ ack=0 next=3 send=ready receive=true stream=.{8} remoteStream=inbound-/,
+ /ACK timeout; resetting peer link .*dst=dev-b seq=1 kind=push channel=maker:event request=\S+ attempts=2 sent=true ageMs=\d+ pending=2\/\d+ ack=0 next=3 send=ready receive=true stream=.{8} remoteStream=inbound-/,
));
// 对端重开链路 → 陈旧 push 前缀被清扫,live invoke-result 按原 seq 重放
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index f70d9359a0..18328d14cc 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -1,4 +1,5 @@
import { CongestionSendBudget } from './congestionSendBudget.js';
+import { PUSH_FORWARD_ALLOWLIST, REMOTE_INVOKE_ALLOWLIST } from './allowlist.js';
import {
PROTOCOL_VERSION,
MAX_FRAME_BYTES,
@@ -4336,8 +4337,13 @@ export class DeviceLinkClient {
const ageMs = pending
? Math.max(0, Math.round(this.monotonicNow() - pending.enqueuedAt))
: -1;
+ const rawChannel = (pending?.envelope.payload as { channel?: unknown } | undefined)?.channel;
+ const channel = typeof rawChannel === 'string'
+ && (PUSH_FORWARD_ALLOWLIST.has(rawChannel) || REMOTE_INVOKE_ALLOWLIST.has(rawChannel))
+ ? rawChannel : 'unknown';
return `dst=${dst.slice(0, 8)} seq=${seq}`
+ ` kind=${pending?.envelope.kind ?? 'missing'}`
+ + ` channel=${channel}`
+ ` request=${pending?.envelope.id?.slice(0, 8) ?? 'none'}`
+ ` attempts=${pending?.attempts ?? -1} sent=${pending?.sent ?? false} ageMs=${ageMs}`
+ ` pending=${peer.pending.size}/${peer.pendingBytes}`