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(mobile): 合并同步查询并补齐两端拥塞诊断

Dashffcefb492121
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
index c8e9fe1e29..8882266de2 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
@@ -35,6 +35,13 @@ const deviceLinkSettings = vi.hoisted(() => ({
revokedControllers: [] as string[],
},
}));
+const diagnosticLog = vi.hoisted(() => ({
+ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), trace: vi.fn(), fatal: vi.fn(),
+}));
+vi.mock('../../logger', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../../logger')>(),
+ createLogger: () => diagnosticLog,
+}));
vi.mock('../settings-store', () => ({
readDeviceLinkSettings: () => deviceLinkSettings.value,
@@ -214,6 +221,7 @@ function makeDispatchTestClient(relay: DispatchTestRelay, deviceId: string): Dev
beforeEach(() => {
vi.useFakeTimers();
+ vi.clearAllMocks();
deviceLinkSettings.value = {
remoteControlEnabled: true,
revokedControllers: [],
@@ -374,7 +382,7 @@ describe('[2] outbox 离线不自旋,上线事件驱动投递', () => {
client as never,
'ctrl-a',
'req-1',
- { ok: true, result: 1 },
+ { ok: true, result: 'PRIVATE_RESPONSE_BODY' },
'local-db:sessions:list',
),
).toBe(true);
@@ -391,6 +399,10 @@ describe('[2] outbox 离线不自旋,上线事件驱动投递', () => {
flushRemoteInvokeResultOutboxOnReconnect();
expect(sendInvokeResult).toHaveBeenCalledTimes(2);
expect(__testing.remoteInvokeResultOutboxSize()).toBe(0);
+ expect(diagnosticLog.warn).toHaveBeenCalledWith(expect.stringContaining('request=req-1 queueMessages=1'));
+ expect(diagnosticLog.info).toHaveBeenCalledWith(expect.stringContaining('request=req-1 queuedMs=20000'));
+ expect(JSON.stringify(diagnosticLog.warn.mock.calls)).not.toContain('PRIVATE_RESPONSE_BODY');
+ expect(JSON.stringify(diagnosticLog.info.mock.calls)).not.toContain('PRIVATE_RESPONSE_BODY');
});
});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 03a18e0c41..79df5ed396 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -2346,6 +2346,7 @@ async function handleInvoke(
const releaseBusyLease = shouldAcquireRemoteInvokeBusyLease(src, payload)
? acquireRemoteInvokeBusyLease()
: () => undefined;
+ const handlerStartedAt = Date.now();
const executionPromise = Promise.resolve()
.then(() => executeInvoke(src, payload))
.catch((err): InvokeResultPayload => {
@@ -2375,6 +2376,12 @@ async function handleInvoke(
let result: InvokeResultPayload;
try {
result = normalizeInvokeResultForWire(await resultPromise);
+ const executionWaitMs = Date.now() - handlerStartedAt;
+ if (executionWaitMs >= 1_000) {
+ log.debug(`remote invoke slow execution request=${shortId(requestId)} from=${shortId(src)}`
+ + ` channel=${payload && REMOTE_INVOKE_ALLOWLIST.has(payload.channel) ? payload.channel : 'unknown'}`
+ + ` executionWaitMs=${executionWaitMs} ok=${result.ok}`);
+ }
if ((remoteInvokeLinkEpoch.get(src) ?? 0) !== invokeLinkEpoch) return;
} finally {
if (inFlightRemoteInvokeResults.get(cacheKey) === inFlightEntry) {
@@ -2638,7 +2645,7 @@ function sendInvokeResultSafe(
rememberRemoteInvokeResult(key, fingerprint, attempt.result);
}
if (attempt.sent) {
- removeRemoteInvokeResultOutboxEntry(key);
+ removeRemoteInvokeResultOutboxEntry(key, true);
return true;
}
return enqueueRemoteInvokeResult({
@@ -2754,15 +2761,20 @@ function enqueueRemoteInvokeResult(entry: QueuedRemoteInvokeResult): boolean {
remoteInvokeResultOutboxBytes += entry.bytes;
log.warn(
`queued invoke-result after local send backpressure for ${entry.channel ?? '?'} ` +
- `to ${shortId(entry.src)}`,
+ `to ${shortId(entry.src)} request=${shortId(entry.requestId)}` +
+ ` queueMessages=${remoteInvokeResultOutbox.size} queueBytes=${remoteInvokeResultOutboxBytes}`,
);
scheduleRemoteInvokeResultOutboxFlush();
return true;
}
-function removeRemoteInvokeResultOutboxEntry(key: string): void {
+function removeRemoteInvokeResultOutboxEntry(key: string, sent = false): void {
const queued = remoteInvokeResultOutbox.get(key);
if (!queued) return;
+ if (sent) {
+ log.info(`flushed queued invoke-result for ${queued.channel ?? '?'} to ${shortId(queued.src)}`
+ + ` request=${shortId(queued.requestId)} queuedMs=${Math.max(0, Date.now() - queued.queuedAt)}`);
+ }
remoteInvokeResultOutbox.delete(key);
remoteInvokeResultOutboxBytes -= queued.bytes;
if (remoteInvokeResultOutbox.size === 0) clearRemoteInvokeResultOutboxTimer();
@@ -2837,7 +2849,7 @@ function flushRemoteInvokeResultOutbox(onlySrc?: string): void {
if (now - queued.queuedAt >= outboxEntryMaxAgeMs(queued.channel)) {
log.warn(
`dropping expired invoke-result outbox entry for ${queued.channel ?? '?'} ` +
- `to ${shortId(queued.src)}`,
+ `to ${shortId(queued.src)} request=${shortId(queued.requestId)} queuedMs=${now - queued.queuedAt}`,
);
removeRemoteInvokeResultOutboxEntry(key);
continue;
@@ -2877,10 +2889,7 @@ function flushRemoteInvokeResultOutbox(onlySrc?: string): void {
}
continue;
}
- removeRemoteInvokeResultOutboxEntry(key);
- log.info(
- `flushed queued invoke-result for ${queued.channel ?? '?'} to ${shortId(queued.src)}`,
- );
+ removeRemoteInvokeResultOutboxEntry(key, true);
}
if (remoteInvokeResultOutbox.size > 0) scheduleRemoteInvokeResultOutboxFlush();
}
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index 15cafc78e3..2321f7ebff 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -543,6 +543,21 @@ describe('makerChatStore text delta batching', () => {
vi.useRealTimers();
});
+ it.each([false, true])('updates the SDK id mirror but persists only in the primary window (sidebar=%s)', async (sidebar) => {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { search: sidebar ? '?sidebarWindow=1' : '' },
+ });
+ const event = { sessionId: SESSION_ID, event: { type: 'session_id', source: 'claude-code', data: 'sdk-live-1' } };
+ onEvent?.(event);
+ await flushPromises();
+ expect(makerChatStore.getSnapshot(SESSION_ID).sdkSessionId).toBe('sdk-live-1');
+ onEvent?.(event);
+ await flushPromises();
+ expect(sessionService.update).toHaveBeenCalledTimes(sidebar ? 0 : 1);
+ if (!sidebar) expect(sessionService.update).toHaveBeenCalledWith(SESSION_ID, { sdkSessionId: 'sdk-live-1' });
+ });
+
it('coalesces consecutive text deltas into one store notification', () => {
let notifyCount = 0;
const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index f69a128475..63970d81d3 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -7212,6 +7212,9 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
const current = getOrCreateState(sessionId);
if (current.sdkSessionId === sdkSessionId) return;
setState(sessionId, (s) => ({ ...s, sdkSessionId }));
+ // The sidebar observes the same event through a read-only preload. The
+ // primary window owns persistence; the observer only updates its mirror.
+ if (isSidebarWindow()) return;
if (!isDataOwnerGenerationCurrent(dataOwnerAtIngress)) return;
sessionService
.update(sessionId, { sdkSessionId })
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index 892d3bfafc..9b002b8f59 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -1,7 +1,8 @@
import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
ActivityIndicator,
+ AppState,
RefreshControl,
ScrollView,
SectionList,
@@ -96,8 +97,7 @@ import {
getScheduleIndexInvalidationVersion,
invalidateOfflineScheduleIndexFailureFor,
invalidateRunningSessionScheduleEntries,
- loadSessionScheduleIndex,
- loadSessionScheduleIndexThrottled,
+ loadSharedSessionScheduleIndex,
} from '@/session/scheduleIndex';
import { shouldSuppressRemoteListEmptyState } from '@/session/sessionEmptyState';
import type { RemoteSession } from '@/session/types';
@@ -125,6 +125,15 @@ export default function DeviceDetailScreen() {
}
function DeviceDetailScreenContent() {
+ const screenFocused = useIsFocused();
+ const screenFocusedRef = useRef(screenFocused);
+ screenFocusedRef.current = screenFocused;
+ const [appStateActive, setAppStateActive] = useState(AppState.currentState === 'active');
+ useEffect(() => {
+ const subscription = AppState.addEventListener('change', (state) => setAppStateActive(state === 'active'));
+ return () => subscription.remove();
+ }, []);
+ const canLoadScheduleIndex = useCallback(() => screenFocusedRef.current && AppState.currentState === 'active', []);
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
const { t, i18n: i18nInstance } = useTranslation();
@@ -289,12 +298,13 @@ function DeviceDetailScreenContent() {
// 节流缓存与首页共用同一 key(deviceId):两页交替浏览时不重复全量拉取(单飞 + TTL,
// 拥塞背景见 scheduleIndex 注释)。
const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId);
- void loadSessionScheduleIndexThrottled(deviceId, () => loadSessionScheduleIndex(maker, { isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId) }))
+ void loadSharedSessionScheduleIndex(deviceId, maker, canLoadScheduleIndex)
.then((nextIndex) => {
if (getScheduleIndexInvalidationVersion(deviceId) !== invalidationVersion) return;
setScheduleIndex(nextIndex);
})
.catch(() => {
+ if (!canLoadScheduleIndex()) return;
if (getScheduleIndexInvalidationVersion(deviceId) !== invalidationVersion) return;
setScheduleIndex(new Map());
});
@@ -304,7 +314,7 @@ function DeviceDetailScreenContent() {
} finally {
setLoading(false);
}
- }, [automationScopeKey, deviceId, deviceName, invoke, maker, statusFilter, subscribe]);
+ }, [automationScopeKey, canLoadScheduleIndex, deviceId, deviceName, invoke, maker, statusFilter, subscribe]);
const loadSessions = useRemoteSyncTask(syncSessions);
useEffect(() => {
@@ -320,22 +330,18 @@ function DeviceDetailScreenContent() {
}, [loadSessions, statusFilter]);
useEffect(() => {
- if (scheduleEventSnapshot.sessionIndexVersion > 0) void loadSessions();
- }, [loadSessions, scheduleEventSnapshot.sessionIndexVersion]);
+ if (screenFocused && appStateActive && scheduleEventSnapshot.sessionIndexVersion > 0) void loadSessions();
+ }, [appStateActive, loadSessions, scheduleEventSnapshot.sessionIndexVersion, screenFocused]);
- // schedule 列表变化(changed,含 pause / resume / 改绑)与 read / all-read 都 force
- // 刷新节流缓存——否则 30s TTL 内会继续显示旧 Pause / 未读状态。依赖专用 version
- // 计数而非 lastProjection 引用:后者每个事件都换新,会让 fired / deferred 等无关事件
- // 也重跑本 effect(review P1)。
- // 上方 loadSessions effect 随 sessionIndexVersion 同步触发,其内部 throttled 调用会
- // 单飞复用本次 force 拉起的在途 promise,不产生第二次全量拉取。
+ // The event store invalidates once; all visible consumers share its next scan.
useEffect(() => {
+ if (!screenFocused || !appStateActive) return;
if (
scheduleEventSnapshot.scheduleListVersion === 0
&& scheduleEventSnapshot.unreadClearVersion === 0
) return;
const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId);
- void loadSessionScheduleIndexThrottled(deviceId, () => loadSessionScheduleIndex(maker, { isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId) }), { force: true })
+ void loadSharedSessionScheduleIndex(deviceId, maker, canLoadScheduleIndex)
.then((nextIndex) => {
if (getScheduleIndexInvalidationVersion(deviceId) !== invalidationVersion) return;
setScheduleIndex(nextIndex);
@@ -344,10 +350,13 @@ function DeviceDetailScreenContent() {
// 失败保留旧徽标,与整页 load 的容错口径一致。
});
}, [
+ appStateActive,
+ canLoadScheduleIndex,
deviceId,
maker,
scheduleEventSnapshot.scheduleListVersion,
scheduleEventSnapshot.unreadClearVersion,
+ screenFocused,
]);
// 派生索引依赖全局 messageVersion / storeVersion,逐 emit 重建出内容相同的新 Map;
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index aaec681d4e..b29d2a4be6 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -225,7 +225,6 @@ import {
invalidateRunningSessionScheduleEntries,
invalidateScheduleIndexForDevice,
loadDeviceSessionScheduleIndex,
- loadSessionScheduleIndexThrottled,
replaceSessionScheduleIndexEntries,
} from '@/session/scheduleIndex';
import { createScheduleIndexDeferRegistry } from '@/session/scheduleIndexDefer';
@@ -353,6 +352,9 @@ export default function HomeScreen() {
}
function HomeScreenContent() {
+ const screenFocused = useIsFocused();
+ const screenFocusedRef = useRef(screenFocused);
+ screenFocusedRef.current = screenFocused;
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
const { t, i18n: i18nInstance } = useTranslation();
@@ -642,8 +644,9 @@ function HomeScreenContent() {
const refreshDeviceScheduleIndex = useCallback((
deviceId: string,
sessionIds: readonly string[],
- options?: { accountGeneration?: number; force?: boolean; homeSyncGeneration?: number },
+ options?: { accountGeneration?: number; homeSyncGeneration?: number },
) => {
+ if (!screenFocusedRef.current || AppState.currentState !== 'active') return;
const expectedAccountGeneration = options?.accountGeneration ?? accountGeneration;
const expectedHomeSyncGeneration = options?.homeSyncGeneration
?? homeSyncGenerationByDeviceRef.current.get(deviceId);
@@ -654,19 +657,18 @@ function HomeScreenContent() {
) return;
// 节流(单飞 + 30s TTL):focus / hydrate / schedule 推送三个触发源高频交叠,每次都全量
// 重放 1+N×listRuns 会拥塞 device-link 管道、拖慢会话打开的关键读(见 scheduleIndex 注释)。
- // force = 已读类权威信号(read / all-read 推送),必须绕过 TTL 立即重拉——否则「看完
- // 返回首页」这个最常见路径永远命中 30s 内的陈旧缓存,未读徽标清不掉(review P1)。
+ // Authoritative events invalidate the shared cache before notifying screens.
const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId);
void homeDeviceSyncLimiterRef.current.run(async () => {
if (
- homeAccountGenerationRef.current !== expectedAccountGeneration
+ !screenFocusedRef.current || AppState.currentState !== 'active'
+ || homeAccountGenerationRef.current !== expectedAccountGeneration
|| !isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration)
) return null;
- return loadSessionScheduleIndexThrottled(
- deviceId,
- () => loadDeviceSessionScheduleIndex(deviceId, invoke),
- { force: options?.force },
- );
+ return loadDeviceSessionScheduleIndex(deviceId, invoke,
+ () => screenFocusedRef.current && AppState.currentState === 'active'
+ && homeAccountGenerationRef.current === expectedAccountGeneration
+ && isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration));
})
.then((nextIndex) => {
if (!nextIndex) return;
@@ -1221,14 +1223,7 @@ function HomeScreenContent() {
remoteSessionStore.requestReseed(deviceId);
continue;
}
- // schedule 列表变化(changed,含 pause / resume / 改绑)与 read / all-read 都是低频
- // 权威信号,force 穿透节流保证状态即时更新;fired / running 等高频事件照常吃 TTL
- // (全量 force 会把 listRuns 风暴请回来)。
- refreshDeviceScheduleIndex(deviceId, sessionIds, {
- force: projection.refresh.scheduleList === true
- || projection.unreadImpact === 'may-clear-schedule'
- || projection.unreadImpact === 'clear-all',
- });
+ refreshDeviceScheduleIndex(deviceId, sessionIds);
}
}), [refreshDeviceScheduleIndex]);
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 83dd046d48..59a51c454d 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -2062,21 +2062,9 @@ export default function SessionScreen() {
// 只能靠 index 探测。无 schedule 的用户只多一次轻量 schedule.list;延后是避开首开关键读抢 WS 管道(#324)。
// 瞬态失败兜底:短暂抖动走 withTransientRemoteRetry 原地重试;冷启动首开时 device-link 可能尚未
// 就绪且失败被吞,依赖 connectionEpoch 在重连后重跑一次探测,用户停在会话里红点也能自愈。
- // unreadVersion 依赖:store 只存最近一条事件投影,completed 被紧随的事件覆盖时下面的快路径会漏;
- // 任何影响未读的事件都 bump unreadVersion(累计计数不丢),据此重跑延后探测兜底。标已读后广播回来的
- // read 事件会再触发一轮探测,发现无未读即收敛;800ms defer + effect cleanup 会把连续事件合并成一次。
- useEffect(() => {
- if (!sessionId) return;
- return deferScheduleIndexHydration(() => {
- void withTransientRemoteRetry(() => markSessionScheduleRunsRead(maker, sessionId))
- .catch(() => undefined);
- });
- }, [connectionEpoch, maker, scheduleEventSnapshot.unreadVersion, sessionId]);
- // 会话开着时报告刚完成:事件投影直接给出绑定到本会话的 runId,单次标已读、免拉 index。
- useEffect(() => {
- if (!completedRunId) return;
- void maker.schedule.markRunRead(completedRunId).catch(() => undefined);
- }, [completedRunId, maker]);
+ // Keep completed/failed events even when a following read replaces lastProjection,
+ // without treating our own read acknowledgement as another reason to scan.
+ const scheduleUnreadAddedVersion = scheduleEventSnapshot.unreadVersion - scheduleEventSnapshot.unreadClearVersion;
// —— 会话未读「真实展示即已读」回执 ——
// 手机端打开会话且**本次连接代已完成整窗同步**后,驻留满 dwell 把被控端该会话的
// 未读态(灵动岛 / Dock 角标 / 桌面侧栏红绿点)清掉;被控端清完经 sessions relay
@@ -2119,6 +2107,21 @@ export default function SessionScreen() {
});
return () => subscription.remove();
}, []);
+ useFocusEffect(useCallback(() => {
+ if (!appStateActive || !deviceId || !sessionId) return;
+ let active = true;
+ const isActive = () => active && AppState.currentState === 'active' && navigation.isFocused();
+ const cancel = deferScheduleIndexHydration(() => {
+ void withTransientRemoteRetry(() => markSessionScheduleRunsRead(maker, sessionId, deviceId, isActive))
+ .catch(() => undefined);
+ });
+ return () => { active = false; cancel(); };
+ }, [appStateActive, connectionEpoch, deviceId, maker, navigation, scheduleUnreadAddedVersion, sessionId]));
+ // The event fast path also belongs only to the task actually being viewed.
+ useFocusEffect(useCallback(() => {
+ if (!appStateActive || !completedRunId) return;
+ void maker.schedule.markRunRead(completedRunId).catch(() => undefined);
+ }, [appStateActive, completedRunId, maker]));
useFocusEffect(
useCallback(() => {
if (!appStateActive || !deviceId || !sessionId || !hasRenderedMessages) return undefined;
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index 4466d7c95f..8de7a3b143 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -313,7 +313,7 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('loadDeviceIdentityCache()');
expect(source).toContain('reconcileDeviceIdentities(');
expect(source).toContain('saveDeviceIdentityCache(result.cache)');
- expect(source).toContain('loadDeviceSessionScheduleIndex(deviceId, invoke)');
+ expect(source).toContain('loadDeviceSessionScheduleIndex(deviceId, invoke,');
expect(source).toContain('replaceSessionScheduleIndexEntries(');
expect(source).toContain("invoke<unknown[]>(device.deviceId, 'maker:list-active', [");
expect(source).toContain("{ summary: true }");
@@ -332,7 +332,8 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('if (version === 0) {');
expect(source).toContain('scheduleEventVersionsRef.current.delete(deviceId)');
expect(source).toContain("projection?.refresh.sessionIndex !== true && projection?.runPatch.status !== 'running'");
- expect(source).toContain('force: projection.refresh.scheduleList === true');
+ expect(source).toContain('refreshDeviceScheduleIndex(deviceId, sessionIds);');
+ expect(source).not.toContain('force: projection.refresh.scheduleList');
expect(source).toContain('scheduleIndex,');
expect(source).toContain('const attention = item.pendingInteractionCount > 0');
expect(source).toContain('|| (item.scheduleInfo?.unreadCount ?? 0) > 0');
diff --git a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts b/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts
index 7620f73c72..5c8980ca0f 100644
--- a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts
+++ b/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts
@@ -13,12 +13,16 @@ describe('mobile remote session bootstrap', () => {
expect(detailSource).toMatch(listWithPinned);
});
- it('forces detail schedule-index refreshes for schedule-list and unread-clear events', () => {
+ it('shares centrally invalidated detail refreshes for schedule-list and unread-clear events', () => {
const detailSource = readFileSync(resolve(process.cwd(), 'app/devices/[deviceId].tsx'), 'utf8');
+ const eventSource = readFileSync(resolve(process.cwd(), 'src/scheduler/remoteScheduleEvents.ts'), 'utf8');
expect(detailSource).toContain('scheduleEventSnapshot.scheduleListVersion === 0');
expect(detailSource).toContain('scheduleEventSnapshot.unreadClearVersion === 0');
- expect(detailSource).toContain('{ force: true }');
+ expect(detailSource).toContain('loadSharedSessionScheduleIndex(deviceId, maker, canLoadScheduleIndex)');
+ expect(detailSource).not.toContain('{ force: true }');
+ expect(eventSource).toContain('projection.refresh.sessionIndex || projection.refresh.scheduleList || clearsUnread');
+ expect(eventSource).toContain('invalidateScheduleIndexForDevice(deviceId)');
expect(detailSource).toContain('scheduleEventSnapshot.scheduleListVersion,');
expect(detailSource).toContain('scheduleEventSnapshot.unreadClearVersion,');
});
diff --git a/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts b/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
index 849a0fc0c0..90197118f8 100644
--- a/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
+++ b/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
@@ -1,9 +1,44 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';
+import { getScheduleIndexInvalidationVersion, loadSessionScheduleIndexThrottled, resetScheduleIndexThrottleForTesting } from '@/session/scheduleIndex';
describe('remote schedule event store', () => {
beforeEach(() => {
remoteScheduleEventStore.clearAll();
+ resetScheduleIndexThrottleForTesting();
+ });
+
+ it('invalidates once before consumers reload and preserves unrelated device caches', async () => {
+ const load = vi.fn(async () => new Map());
+ const loadOther = vi.fn(async () => new Map());
+ await loadSessionScheduleIndexThrottled('dev-1', load);
+ await loadSessionScheduleIndexThrottled('dev-2', loadOther);
+ const requests: Promise<unknown>[] = [];
+ const off = remoteScheduleEventStore.subscribe(() => {
+ requests.push(loadSessionScheduleIndexThrottled('dev-1', load));
+ requests.push(loadSessionScheduleIndexThrottled('dev-1', load));
+ });
+ try {
+ remoteScheduleEventStore.apply('dev-1', { type: 'read', scheduleId: 'sched-1' });
+ await Promise.all(requests);
+ await loadSessionScheduleIndexThrottled('dev-2', loadOther);
+ expect(load).toHaveBeenCalledTimes(2);
+ expect(loadOther).toHaveBeenCalledTimes(1);
+ expect(getScheduleIndexInvalidationVersion('dev-1')).toBe(1);
+ } finally { off(); }
+ });
+
+ it('preserves a completed-event probe while read feedback does not request another probe', () => {
+ const probeVersion = () => {
+ const state = remoteScheduleEventStore.getSnapshot('dev-1');
+ return state.unreadVersion - state.unreadClearVersion;
+ };
+ remoteScheduleEventStore.apply('dev-1', { type: 'completed', scheduleId: 'sched-1', runId: 'run-1', sessionId: 'task-1' });
+ const completedVersion = probeVersion();
+ expect(completedVersion).toBeGreaterThan(0);
+ remoteScheduleEventStore.apply('dev-1', { type: 'read', scheduleId: 'sched-1' });
+ remoteScheduleEventStore.apply('dev-1', { type: 'all-read' });
+ expect(probeVersion()).toBe(completedVersion);
});
it('increments per-device versions for pushed schedule events', () => {
diff --git a/apps/mobile/src/__tests__/scheduleIndex.test.ts b/apps/mobile/src/__tests__/scheduleIndex.test.ts
index 0894467bbf..83c5e9d7e9 100644
--- a/apps/mobile/src/__tests__/scheduleIndex.test.ts
+++ b/apps/mobile/src/__tests__/scheduleIndex.test.ts
@@ -303,6 +303,41 @@ describe('scheduleIndex', () => {
});
describe('loadSessionScheduleIndexThrottled (单飞 + TTL 节流)', () => {
+ it('shares an in-flight scan even when network delay exceeds the success TTL', async () => {
+ resetScheduleIndexThrottleForTesting();
+ let finish!: (index: Map<string, RemoteSessionScheduleInfo>) => void;
+ const load = vi.fn(() => new Promise<Map<string, RemoteSessionScheduleInfo>>((resolve) => { finish = resolve; }));
+ let at = 0;
+ const options = { now: () => at };
+ const first = loadSessionScheduleIndexThrottled('dev-1', load, options);
+ at += SCHEDULE_INDEX_THROTTLE_TTL_MS * 2;
+ expect(loadSessionScheduleIndexThrottled('dev-1', load, options)).toBe(first);
+ expect(load).toHaveBeenCalledTimes(1);
+ finish(new Map());
+ await first;
+ expect(loadSessionScheduleIndexThrottled('dev-1', load, options)).toBe(first);
+ });
+
+ it.each([false, true])('coalesces invalidated scans after the old scan settles (rejected=%s)', async (rejected) => {
+ resetScheduleIndexThrottleForTesting();
+ let finish!: (index: Map<string, RemoteSessionScheduleInfo>) => void;
+ let fail!: (error: Error) => void;
+ const fresh = new Map<string, RemoteSessionScheduleInfo>();
+ const load = vi.fn()
+ .mockImplementationOnce(() => new Promise((resolve, reject) => { finish = resolve; fail = reject; }))
+ .mockResolvedValue(fresh);
+ const old = loadSessionScheduleIndexThrottled('dev-1', load).catch(() => undefined);
+ invalidateScheduleIndexForDevice('dev-1');
+ const home = loadSessionScheduleIndexThrottled('dev-1', load);
+ const task = loadSessionScheduleIndexThrottled('dev-1', load);
+ expect(load).toHaveBeenCalledTimes(1);
+ if (rejected) fail(new Error('old request failed')); else finish(new Map());
+ await old;
+ expect(await home).toBe(fresh);
+ expect(await task).toBe(fresh);
+ expect(load).toHaveBeenCalledTimes(2);
+ });
+
it('TTL 内的重复触发复用同一在途/已完成 promise,不重复加载', async () => {
resetScheduleIndexThrottleForTesting();
const load = vi.fn(async () => new Map<string, RemoteSessionScheduleInfo>());
diff --git a/apps/mobile/src/__tests__/scheduleRunRead.test.ts b/apps/mobile/src/__tests__/scheduleRunRead.test.ts
index 23b0f77043..d59ffe10da 100644
--- a/apps/mobile/src/__tests__/scheduleRunRead.test.ts
+++ b/apps/mobile/src/__tests__/scheduleRunRead.test.ts
@@ -1,7 +1,8 @@
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { projectScheduleEvent } from '@cindy/maker-shared/schedule-events';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { markSessionScheduleRunsRead, unreadRunIdFromProjection } from '@/session/scheduleRunRead';
+import { invalidateScheduleIndexForDevice, loadSessionScheduleIndex, loadSessionScheduleIndexThrottled, loadSharedSessionScheduleIndex, resetScheduleIndexThrottleForTesting } from '@/session/scheduleIndex';
function makerWith(
runs: readonly Record<string, unknown>[],
@@ -22,6 +23,37 @@ function transientError(message = 'target timed out'): Error & { code: string }
}
describe('markSessionScheduleRunsRead', () => {
+ beforeEach(resetScheduleIndexThrottleForTesting);
+ it('retries a transient scan inside the shared load before caching failure', async () => {
+ const mark = vi.fn(async () => undefined);
+ const listRuns = vi.fn().mockRejectedValueOnce(transientError()).mockResolvedValue([
+ { id: 'run-1', scheduleId: 'sched-1', sessionId: 'session-1', status: 'success', firedAt: 1 },
+ ]);
+ const maker = makerWith([], mark, listRuns);
+ const home = loadSharedSessionScheduleIndex('dev-1', maker);
+ const task = markSessionScheduleRunsRead(maker, 'session-1', 'dev-1');
+ await home;
+ await expect(task).resolves.toEqual(['run-1']);
+ expect(listRuns).toHaveBeenCalledTimes(2);
+ });
+
+ it('abandons a queued refresh after blur without poisoning the next visible consumer', async () => {
+ let finish!: (index: Map<string, never>) => void;
+ const old = loadSessionScheduleIndexThrottled('dev-1', () => new Promise((resolve) => { finish = resolve; }));
+ invalidateScheduleIndexForDevice('dev-1');
+ let active = true;
+ const listRuns = vi.fn(async () => []);
+ const maker = makerWith([], vi.fn(async () => undefined), listRuns);
+ const task = markSessionScheduleRunsRead(maker, 'session-1', 'dev-1', () => active);
+ const assertion = expect(task).rejects.toThrow('consumer inactive');
+ active = false;
+ finish(new Map<string, never>());
+ await old;
+ await assertion;
+ expect(listRuns).not.toHaveBeenCalled();
+ await markSessionScheduleRunsRead(maker, 'session-1', 'dev-1');
+ expect(listRuns).toHaveBeenCalledTimes(1);
+ });
it('marks only the target session unread runs as read', async () => {
const markRunRead = vi.fn(async () => undefined);
const maker = makerWith([
@@ -31,7 +63,7 @@ describe('markSessionScheduleRunsRead', () => {
{ id: 'run-still-running', scheduleId: 'sched-1', sessionId: 'session-1', status: 'running', firedAt: 5 },
], markRunRead);
- const marked = await markSessionScheduleRunsRead(maker, 'session-1');
+ const marked = await markSessionScheduleRunsRead(maker, 'session-1', 'dev-1');
expect(marked).toEqual(['run-mine-unread']);
expect(markRunRead).toHaveBeenCalledTimes(1);
@@ -44,8 +76,8 @@ describe('markSessionScheduleRunsRead', () => {
{ id: 'run-read', scheduleId: 'sched-1', sessionId: 'session-1', status: 'success', firedAt: 1, readAt: 2 },
], markRunRead);
- await expect(markSessionScheduleRunsRead(maker, 'session-1')).resolves.toEqual([]);
- await expect(markSessionScheduleRunsRead(maker, '')).resolves.toEqual([]);
+ await expect(markSessionScheduleRunsRead(maker, 'session-1', 'dev-1')).resolves.toEqual([]);
+ await expect(markSessionScheduleRunsRead(maker, '', 'dev-1')).resolves.toEqual([]);
expect(markRunRead).not.toHaveBeenCalled();
});
@@ -58,21 +90,26 @@ describe('markSessionScheduleRunsRead', () => {
{ id: 'run-b', scheduleId: 'sched-1', sessionId: 'session-1', status: 'failed', firedAt: 2 },
], markRunRead);
- const marked = await markSessionScheduleRunsRead(maker, 'session-1');
+ const marked = await markSessionScheduleRunsRead(maker, 'session-1', 'dev-1');
expect(marked).toEqual(['run-b']);
expect(markRunRead).toHaveBeenCalledTimes(2);
});
- it('rejects on transient listRuns failures so the caller retry wrapper can rerun the probe', async () => {
+ it('rejects after the shared transient scan retry is exhausted', async () => {
+ vi.useFakeTimers();
const error = transientError();
const markRunRead = vi.fn(async () => undefined);
const maker = makerWith([], markRunRead, async () => {
throw error;
});
- await expect(markSessionScheduleRunsRead(maker, 'session-1')).rejects.toBe(error);
- expect(markRunRead).not.toHaveBeenCalled();
+ try {
+ const assertion = expect(markSessionScheduleRunsRead(maker, 'session-1', 'dev-1')).rejects.toBe(error);
+ await vi.runAllTimersAsync();
+ await assertion;
+ expect(markRunRead).not.toHaveBeenCalled();
+ } finally { vi.useRealTimers(); }
});
it('rejects on transient markRunRead failures so the caller retry wrapper can rerun the mark', async () => {
@@ -85,7 +122,7 @@ describe('markSessionScheduleRunsRead', () => {
{ id: 'run-b', scheduleId: 'sched-1', sessionId: 'session-1', status: 'failed', firedAt: 2 },
], markRunRead);
- await expect(markSessionScheduleRunsRead(maker, 'session-1')).rejects.toBe(error);
+ await expect(markSessionScheduleRunsRead(maker, 'session-1', 'dev-1')).rejects.toBe(error);
expect(markRunRead).toHaveBeenCalledTimes(2);
});
@@ -99,7 +136,37 @@ describe('markSessionScheduleRunsRead', () => {
{ id: 'run-b', scheduleId: 'sched-1', sessionId: 'session-1', status: 'success', firedAt: 2 },
], markRunRead);
- await expect(markSessionScheduleRunsRead(maker, 'session-1')).resolves.toEqual(['run-a', 'run-b']);
+ await expect(markSessionScheduleRunsRead(maker, 'session-1', 'dev-1')).resolves.toEqual(['run-a', 'run-b']);
+ });
+
+ it('reuses the home scan across ordinary task visits without losing bound task receipts', async () => {
+ const listRuns = vi.fn(async () => [
+ { id: 'run-1', scheduleId: 'sched-1', sessionId: 'bound-task', status: 'success', firedAt: 1 },
+ ]);
+ const mark = vi.fn(async () => undefined);
+ const maker = makerWith([], mark, listRuns);
+ await loadSessionScheduleIndexThrottled('dev-1', () => loadSessionScheduleIndex(maker));
+ await markSessionScheduleRunsRead(maker, 'ordinary-1', 'dev-1');
+ await markSessionScheduleRunsRead(maker, 'ordinary-2', 'dev-1');
+ await markSessionScheduleRunsRead(maker, 'bound-task', 'dev-1');
+ expect(listRuns).toHaveBeenCalledTimes(1);
+ expect(mark).toHaveBeenCalledExactlyOnceWith('run-1');
+ });
+
+ it('does not start a scan when inactive or mark receipts after leaving during a shared scan', async () => {
+ let finish!: (runs: Record<string, unknown>[]) => void;
+ const listRuns = vi.fn(() => new Promise<Record<string, unknown>[]>((resolve) => { finish = resolve; }));
+ const mark = vi.fn(async () => undefined);
+ const maker = makerWith([], mark, listRuns);
+ await markSessionScheduleRunsRead(maker, 'session-1', 'dev-1', () => false);
+ expect(listRuns).not.toHaveBeenCalled();
+ let active = true;
+ const pending = markSessionScheduleRunsRead(maker, 'session-1', 'dev-1', () => active);
+ await vi.waitFor(() => expect(listRuns).toHaveBeenCalledTimes(1));
+ active = false;
+ finish([{ id: 'run-1', scheduleId: 'sched-1', sessionId: 'session-1', status: 'success', firedAt: 1 }]);
+ await expect(pending).resolves.toEqual([]);
+ expect(mark).not.toHaveBeenCalled();
});
});
diff --git a/apps/mobile/src/scheduler/remoteScheduleEvents.ts b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
index f11ad7929c..b2c86cd239 100644
--- a/apps/mobile/src/scheduler/remoteScheduleEvents.ts
+++ b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
@@ -3,6 +3,7 @@ import {
projectScheduleEvent,
type ScheduleEventProjection,
} from '@cindy/maker-shared/schedule-events';
+import { invalidateScheduleIndexForDevice } from '@/session/scheduleIndex';
export interface RemoteScheduleEventSnapshot {
lastProjection: ScheduleEventProjection | null;
@@ -11,7 +12,7 @@ export interface RemoteScheduleEventSnapshot {
sessionIndexVersion: number;
/**
* 未读清除类事件(unreadImpact = may-clear-schedule / clear-all,即 read / all-read)
- * 的专用计数:消费方据此对 schedule-index 节流做 force 穿透(见 scheduleIndex 节流注释)。
+ * 的专用计数:事件先使共享索引失效,消费方据此读取同一轮新索引。
* 单列一个 version 而不让消费方依赖 lastProjection 引用——后者每个事件都换新,
* 进 effect deps 会让 fired / deferred 等无关事件也触发昂贵的全量拉取。
*/
@@ -49,6 +50,11 @@ export const remoteScheduleEventStore = {
const prev = snapshots.get(deviceId) ?? emptySnapshot;
const clearsUnread = projection.unreadImpact === 'may-clear-schedule'
|| projection.unreadImpact === 'clear-all';
+ // Invalidate once before notifying all screens. Consumer-local force loads
+ // otherwise launch competing scans for the same authoritative event.
+ if (projection.refresh.sessionIndex || projection.refresh.scheduleList || clearsUnread) {
+ invalidateScheduleIndexForDevice(deviceId);
+ }
snapshots.set(deviceId, {
lastProjection: projection,
runsVersion: prev.runsVersion + (projection.refresh.runRefresh.mode === 'none' ? 0 : 1),
diff --git a/apps/mobile/src/session/scheduleIndex.ts b/apps/mobile/src/session/scheduleIndex.ts
index 11593280e5..ae06b23902 100644
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@ -1,7 +1,7 @@
import { isDeviceUnresponsiveRemoteError } from '@cindy/maker-shared/device-link-contract';
import { createMobileMakerTransport, type MobileMakerTransport, type RemoteInvoke } from '@/device-link/mobileMakerTransport';
import { unresponsiveDevicesStore } from '@/device-link/unresponsiveDevicesStore';
-import { isTransientRemoteError } from '@/device-link/remoteRetry';
+import { isTransientRemoteError, withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { normalizeScheduleList, normalizeScheduleRuns } from '@/scheduler/scheduleModel';
import type { RemoteScheduleRun } from '@/scheduler/types';
import { buildSessionScheduleIndex, type RemoteSessionScheduleInfo } from '@/session/sessionList';
@@ -70,6 +70,8 @@ export const SCHEDULE_INDEX_FAILURE_TTL_MS = 30_000;
interface ScheduleIndexThrottleEntry {
at: number;
promise: Promise<Map<string, RemoteSessionScheduleInfo>>;
+ pending: boolean;
+ invalidated: boolean;
/** 该轮加载失败的时刻;非 null 表示条目处于负缓存态。 */
failedAt: number | null;
/** 失败原因是 DEVICE_UNRESPONSIVE(熔断快速失败);恢复旁路判定用。 */
@@ -127,6 +129,14 @@ export function loadSessionScheduleIndexThrottled(
const ttlMs = options.ttlMs ?? SCHEDULE_INDEX_THROTTLE_TTL_MS;
const failureTtlMs = options.failureTtlMs ?? SCHEDULE_INDEX_FAILURE_TTL_MS;
const existing = scheduleIndexThrottleEntries.get(key);
+ if (existing?.pending) {
+ if (options.force) existing.invalidated = true;
+ if (!existing.invalidated) return existing.promise;
+ // An authoritative change needs a post-event snapshot, but must not start
+ // another 1+N scan beside the old one. All waiters re-enter the same cache.
+ const reload = () => loadSessionScheduleIndexThrottled(key, load, { ...options, force: false });
+ return existing.promise.then(reload, reload);
+ }
if (!options.force && existing) {
// 熔断恢复旁路(review P1):DEVICE_UNRESPONSIVE 负缓存的存在意义是「open
// 期间别再压请求」,设备一旦恢复(移出 unresponsive 集合)就立刻失效——
@@ -146,6 +156,8 @@ export function loadSessionScheduleIndexThrottled(
const entry: ScheduleIndexThrottleEntry = {
at: now(),
promise,
+ pending: true,
+ invalidated: false,
failedAt: null,
failedUnresponsive: false,
failedTransient: false,
@@ -154,12 +166,22 @@ export function loadSessionScheduleIndexThrottled(
scheduleIndexThrottleEntries.set(key, entry);
promise.then(
() => {
+ entry.pending = false;
+ if (entry.invalidated) {
+ if (scheduleIndexThrottleEntries.get(key) === entry) scheduleIndexThrottleEntries.delete(key);
+ return;
+ }
// TTL 语义是「完成后 TTL 内复用」:一轮 load 本身耗时较长(1+N 串行)时,
// 若从启动时刻起算,可复用窗口会被吃掉大半甚至直接过期(review 反馈)。
// 成功落定时把基准挪到 resolve 时刻;在途期间的复用由单飞(同一 promise)保证。
if (scheduleIndexThrottleEntries.get(key) === entry) entry.at = now();
},
(error) => {
+ entry.pending = false;
+ if (entry.invalidated) {
+ if (scheduleIndexThrottleEntries.get(key) === entry) scheduleIndexThrottleEntries.delete(key);
+ return;
+ }
if (scheduleIndexThrottleEntries.get(key) === entry) {
entry.failedAt = now();
// 末项竞态下抛出的是原始 INVOKE_TIMEOUT(见 loadSessionScheduleIndex
@@ -217,7 +239,9 @@ export function invalidateOfflineScheduleIndexFailureFor(deviceId: string): void
export function invalidateScheduleIndexForDevice(deviceId: string): void {
if (!deviceId) return;
- scheduleIndexThrottleEntries.delete(deviceId);
+ const entry = scheduleIndexThrottleEntries.get(deviceId);
+ if (entry?.pending) entry.invalidated = true;
+ else scheduleIndexThrottleEntries.delete(deviceId);
scheduleIndexInvalidationVersions.set(
deviceId,
(scheduleIndexInvalidationVersions.get(deviceId) ?? 0) + 1,
@@ -243,9 +267,25 @@ export function resetScheduleIndexThrottleForTesting(): void {
export function loadDeviceSessionScheduleIndex(
deviceId: string,
invoke: RemoteInvoke,
+ canStart?: () => boolean,
+): Promise<Map<string, RemoteSessionScheduleInfo>> {
+ return loadSharedSessionScheduleIndex(deviceId, createMobileMakerTransport({ deviceId, invoke }), canStart);
+}
+
+/** Every screen shares the strict load and its bounded retry, before negative caching. */
+export async function loadSharedSessionScheduleIndex(
+ deviceId: string,
+ maker: Pick<MobileMakerTransport, 'schedule'>,
+ canStart: () => boolean = () => true,
): Promise<Map<string, RemoteSessionScheduleInfo>> {
- return loadSessionScheduleIndex(createMobileMakerTransport({ deviceId, invoke }), {
- isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId),
+ return loadSessionScheduleIndexThrottled(deviceId, () => {
+ // Check again when an invalidated in-flight scan finishes. Throw before
+ // creating an entry so an abandoned waiter cannot poison active consumers.
+ if (!canStart()) throw new Error('Schedule index consumer inactive');
+ return withTransientRemoteRetry(() => loadSessionScheduleIndex(maker, {
+ throwOnTransientRunListError: true,
+ isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId),
+ }));
});
}
diff --git a/apps/mobile/src/session/scheduleRunRead.ts b/apps/mobile/src/session/scheduleRunRead.ts
index 4f7cb2ec54..8a8f564c86 100644
--- a/apps/mobile/src/session/scheduleRunRead.ts
+++ b/apps/mobile/src/session/scheduleRunRead.ts
@@ -1,7 +1,7 @@
import type { ScheduleEventProjection } from '@cindy/maker-shared/schedule-events';
import { isTransientRemoteError } from '@/device-link/remoteRetry';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
-import { loadSessionScheduleIndex } from '@/session/scheduleIndex';
+import { loadSharedSessionScheduleIndex } from '@/session/scheduleIndex';
/**
* 会话维度的自动化 run「已读」编排(对齐桌面端 CCAgentSidebarUpper 的「激活即已读」语义)。
@@ -23,9 +23,12 @@ type ScheduleReadTransport = Pick<MobileMakerTransport, 'schedule'>;
export async function markSessionScheduleRunsRead(
maker: ScheduleReadTransport,
sessionId: string,
+ deviceId: string,
+ isActive: () => boolean = () => true,
): Promise<string[]> {
- if (!sessionId) return [];
- const index = await loadSessionScheduleIndex(maker, { throwOnTransientRunListError: true });
+ if (!sessionId || !deviceId || !isActive()) return [];
+ const index = await loadSharedSessionScheduleIndex(deviceId, maker, isActive);
+ if (!isActive()) return [];
const unreadRunIds = index.get(sessionId)?.unreadRunIds ?? [];
if (unreadRunIds.length === 0) return [];
// 单个永久失败不阻塞其它 run;瞬态失败需要抛出,让外层 retry 重新探测并补标。
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 12148e04aa..e7684fa798 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -16,6 +16,7 @@ import {
DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE,
DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
MAX_TRANSPORT_PENDING_MESSAGES,
+ MAX_TRANSPORT_CHUNK_BYTES,
MAX_TRANSPORT_WEBSOCKET_BUFFERED_BYTES,
TRANSPORT_PENDING_PUSH_MAX_AGE_MS,
TRANSPORT_RETRY_PASS_BUDGET,
@@ -116,6 +117,27 @@ function makeHarness(opts?: {
const tick = (ms = 0): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
describe('network change probes', () => {
+ it.each([true, false])('only post-hint valid inbound activity avoids the redundant probe (valid=%s)', async (valid) => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(0);
+ const socket = h.current(); socket.ack();
+ await vi.advanceTimersByTimeAsync(1);
+ h.client.notifyNetworkChanged();
+ await vi.advanceTimersByTimeAsync(100);
+ socket.push(valid ? { v: PROTOCOL_VERSION, kind: 'pong' } : { v: 999, kind: 'pong' });
+ await vi.advanceTimersByTimeAsync(400);
+ expect(socket.sent.filter((e) => e.kind === 'ping')).toHaveLength(valid ? 0 : 1);
+ if (valid) {
+ // A later hint may mean another AP, even if its Wi-Fi label is unchanged.
+ h.client.notifyNetworkChanged();
+ await vi.advanceTimersByTimeAsync(500);
+ expect(socket.sent.filter((e) => e.kind === 'ping')).toHaveLength(1);
+ }
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
it.each([true, false])('debounces hints and retains only a responsive socket (responsive=%s)', async (responsive) => {
vi.useFakeTimers();
const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
@@ -471,6 +493,22 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('correlates request timeout logs without recording request arguments', async () => {
+ vi.useFakeTimers();
+ const warn = vi.fn();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 }, logger: { warn, debug: vi.fn(), info: vi.fn(), error: vi.fn() } });
+ try {
+ h.client.start(); await vi.advanceTimersByTimeAsync(0); h.current().ack();
+ const request = h.client.invoke('dev-b', { channel: 'maker:list-active', args: ['PRIVATE_ARGUMENT'] }, 1_000);
+ const assertion = expect(request).rejects.toMatchObject({ code: 'INVOKE_TIMEOUT' });
+ const sent = h.current().sent.find((env) => env.kind === 'invoke')!;
+ await vi.advanceTimersByTimeAsync(1_000);
+ await assertion;
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(`request=${sent.id?.slice(0, 8)}`));
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('PRIVATE_ARGUMENT');
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
it('invoke:同 id invoke-result 配对 resolve', async () => {
const h = makeHarness();
h.client.start();
@@ -670,6 +708,65 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('distinguishes receive capacity from declared size and recovers the missing head in order', async () => {
+ const warn = vi.fn();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 }, logger: { warn, debug: vi.fn(), info: vi.fn(), error: vi.fn() } });
+ h.client.start();
+ await tick(); h.current().ack();
+ try {
+ const streamId = 'capacity-stream';
+ await establishInboundReliableLink(h, streamId);
+ const received: number[] = [];
+ h.client.onFrame((env) => {
+ if (env.kind === 'push') received.push((env.payload as { payload: { seq: number } }).payload.seq);
+ });
+ const frames = (seq: number, large = false) => encodeReliableFrames({
+ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', id: `request-${seq}`,
+ payload: { channel: 'maker:event', payload: { seq, text: large ? 'PRIVATE'.repeat(30_000) : '' } },
+ }, streamId, seq);
+ for (let seq = 2; seq <= 17; seq++) h.current().push(frames(seq)[0]);
+ h.current().push(frames(18, true)[0]);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('reason=receive_capacity_exceeded'));
+ const line = warn.mock.calls.at(-1)?.[0];
+ expect(line).toContain('src=dev-b stream=capacity seq=18 request=request-');
+ expect(line).toContain('next=1');
+ expect(line).not.toContain('PRIVATE');
+ expect(() => h.current().push({ ...frames(18, true)[0], id: 123 } as unknown as Envelope)).not.toThrow();
+ expect(warn.mock.calls.at(-1)?.[0]).toContain('request=none');
+ expect(received).toEqual([]);
+ // The full cache still makes room for the missing segmented head.
+ for (const frame of frames(1, true)) h.current().push(frame);
+ await tick();
+ for (const frame of frames(17)) h.current().push(frame);
+ for (const frame of frames(18, true)) h.current().push(frame);
+ await tick();
+ expect(received).toEqual(Array.from({ length: 18 }, (_, i) => i + 1));
+ } finally { h.client.stop(); }
+ });
+
+ it.each(['chunk_too_large', 'declared_size_exceeded'])('reports the actual malformed fragment reason: %s', async (reason) => {
+ const warn = vi.fn();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 }, logger: { warn, debug: vi.fn(), info: vi.fn(), error: vi.fn() } });
+ h.client.start(); await tick(); h.current().ack();
+ try {
+ const streamId = 'invalid-fragments';
+ await establishInboundReliableLink(h, streamId);
+ const received = vi.fn(); h.client.onFrame(received);
+ const frame = (index: number, bytes: number): Envelope => ({
+ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', id: 'fragment-id',
+ payload: { __cindyDeviceLinkTransport: { version: 1, streamId, seq: 1,
+ segment: { index, total: 2, totalBytes: MAX_TRANSPORT_CHUNK_BYTES + 1 } }, data: 'x'.repeat(bytes) },
+ });
+ if (reason === 'declared_size_exceeded') {
+ h.current().push(frame(0, MAX_TRANSPORT_CHUNK_BYTES));
+ h.current().push(frame(1, 2));
+ } else h.current().push(frame(0, MAX_TRANSPORT_CHUNK_BYTES + 1));
+ await tick();
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(`reason=${reason}`));
+ expect(received).not.toHaveBeenCalled();
+ } finally { h.client.stop(); }
+ });
+
it('乱序分片只在缺口补齐后按 seq 交付,重复帧不重复触发 host', async () => {
const h = makeHarness({ timing: { pingIntervalMs: 1_000 } });
h.client.start();
@@ -1206,7 +1303,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 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 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 34f71ebf37..d2f537e661 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -800,6 +800,7 @@ export class DeviceLinkClient {
* Repeated hints coalesce and cannot extend an already running probe. */
notifyNetworkChanged(): void {
if (this.stopped || this.networkProbeTimer) return;
+ const hintedAt = this.monotonicNow();
if (this.networkChangeTimer) clearTimeout(this.networkChangeTimer);
this.networkChangeTimer = setTimeout(() => {
this.networkChangeTimer = null;
@@ -809,6 +810,9 @@ export class DeviceLinkClient {
if (this.reconnectTimer) this.connectNow('network-change');
return;
}
+ // Activity after the latest hint already proves this relay is reachable.
+ // Do not compare Wi-Fi labels: switching access points can keep them equal.
+ if (this.lastInboundAt > hintedAt) return;
const epoch = this.connEpoch;
const socket = this.ws;
const startedAt = this.monotonicNow();
@@ -1398,7 +1402,7 @@ export class DeviceLinkClient {
const id = createRequestId();
const timeout = timeoutMs ?? this.timing.requestTimeoutMs;
const startedAt = Date.now();
- const requestDescription = this.describeRequest(env, expectKind);
+ const requestDescription = `${this.describeRequest(env, expectKind)} request=${id.slice(0, 8)}`;
const logFinished = (outcome: 'ok' | 'timeout' | 'error', err?: DeviceLinkError): void => {
const elapsedMs = Date.now() - startedAt;
@@ -2377,6 +2381,12 @@ export class DeviceLinkClient {
meta.streamId,
Math.max(peer.remoteBaseSeq, meta.baseSeq ?? 1),
);
+ // Only emitted on an existing rejection path; never log payload contents.
+ const describeRejectedFrame = (): string =>
+ `src=${env.src?.slice(0, 8)} stream=${meta.streamId.slice(0, 8)} seq=${meta.seq}`
+ + ` request=${typeof env.id === 'string' ? env.id.slice(0, 8) : 'none'} kind=${env.kind}`
+ + ` next=${stream.lastDeliveredSeq + 1} delivering=${stream.deliveringSeq ?? 'none'}`
+ + ` ready=${stream.ready.size} assemblies=${stream.assemblies.size} bufferedBytes=${stream.bufferedBytes}`;
const isSkip = !meta.segment && (() => {
try {
return isTransportSkipPayload(decodeTransportJson(parsed.data));
@@ -2390,7 +2400,7 @@ export class DeviceLinkClient {
return { handled: true };
}
if (meta.seq > stream.lastDeliveredSeq + MAX_TRANSPORT_SEQUENCE_WINDOW) {
- this.log.warn(`dropping reliable payload beyond receive window seq=${meta.seq}`);
+ this.log.warn(`dropping reliable payload reason=receive_window ${describeRejectedFrame()}`);
this.sendTransportAck(env.src, meta.streamId, stream.lastDeliveredSeq);
return { handled: true };
}
@@ -2412,11 +2422,10 @@ export class DeviceLinkClient {
this.sendTransportAck(env.src, meta.streamId, stream.lastDeliveredSeq);
return { handled: true };
}
- if (
- bytes > MAX_TRANSPORT_CHUNK_BYTES
- || !this.ensureReceiveCapacity(stream, meta.seq, bytes)
- ) {
- this.log.warn(`dropping reliable payload because receive buffer is full seq=${meta.seq}`);
+ const rejection = bytes > MAX_TRANSPORT_CHUNK_BYTES ? 'chunk_too_large'
+ : !this.ensureReceiveCapacity(stream, meta.seq, bytes) ? 'receive_capacity_exceeded' : null;
+ if (rejection) {
+ this.log.warn(`dropping reliable payload reason=${rejection} ${describeRejectedFrame()} incomingBytes=${bytes}`);
this.sendTransportAck(env.src, meta.streamId, stream.lastDeliveredSeq);
return { handled: true };
}
@@ -2460,13 +2469,14 @@ export class DeviceLinkClient {
}
if (!assembly.chunks.has(segment.index)) {
const bytes = byteLength(parsed.data);
- if (
- bytes > MAX_TRANSPORT_CHUNK_BYTES ||
- assembly.bytes + bytes > assembly.totalBytes
- || !this.ensureReceiveCapacity(stream, meta.seq, bytes)
- ) {
+ const rejection = bytes > MAX_TRANSPORT_CHUNK_BYTES ? 'chunk_too_large'
+ : assembly.bytes + bytes > assembly.totalBytes ? 'declared_size_exceeded'
+ : !this.ensureReceiveCapacity(stream, meta.seq, bytes) ? 'receive_capacity_exceeded' : null;
+ if (rejection) {
+ this.log.warn(`dropping reliable payload reason=${rejection} ${describeRejectedFrame()}`
+ + ` incomingBytes=${bytes} assembledBytes=${assembly.bytes} declaredBytes=${assembly.totalBytes}`
+ + ` segment=${segment.index}/${segment.total}`);
this.removeReceiveEntry(stream, meta.seq);
- this.log.warn(`dropping reliable payload beyond declared size seq=${meta.seq}`);
return { handled: true };
}
assembly.chunks.set(segment.index, parsed.data);
@@ -4086,6 +4096,7 @@ export class DeviceLinkClient {
: -1;
return `dst=${dst.slice(0, 8)} seq=${seq}`
+ ` kind=${pending?.envelope.kind ?? 'missing'}`
+ + ` request=${pending?.envelope.id?.slice(0, 8) ?? 'none'}`
+ ` attempts=${pending?.attempts ?? -1} sent=${pending?.sent ?? false} ageMs=${ageMs}`
+ ` pending=${peer.pending.size}/${peer.pendingBytes}`
+ ` ack=${peer.highestAckSeq} next=${peer.nextSeq}`