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): 校验当前订阅确认并限制传输诊断日志预算

Dash8bc30ef5591b
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index e3eeec59b5..9416130fb8 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1808,7 +1808,6 @@ function SessionScreenContent() {
typeof createTransientTopicSubscriptionCoordinator
> | null>(null);
sessionsSubscriptionCoordinatorRef.current ??= createTransientTopicSubscriptionCoordinator();
- const focusedSubscriptionRef = useRef<Promise<void> | null>(null);
// 门槛代号:每次「作废门槛」(原地切 session / liveAttention 上升沿)都递增。
// sync 尾部只有代号与自己启动时一致才允许落 key——否则 A→B→A 场景下,visit-1
// 的在途旧 load 会在重置之后用**相同的** `${sessionId}:${connectionEpoch}` 把门槛
@@ -3720,8 +3719,8 @@ function SessionScreenContent() {
// cached content is already readable; timeout/failure still permits a snapshot.
// An ACK after the read starts retains the existing recovery follow-up.
const needsAck = (getSubscriptionIdentity?.(deviceId, ['sessions', `session:${sessionId}`]) ?? null) === null;
- await waitForCachedSubscription(syncRun, isReopen && needsAck,
- Promise.all([sessionsReady, focusedSubscriptionRef.current]));
+ await waitForCachedSubscription(syncRun, isReopen && needsAck, sessionsReady,
+ () => (getSubscriptionIdentity?.(deviceId, ['sessions', `session:${sessionId}`]) ?? null) !== null);
};
const retryRead = <T,>(read: () => Promise<T>): Promise<T> => {
let failedAtVersion: number | null = null;
@@ -4271,18 +4270,13 @@ function SessionScreenContent() {
useFocusEffect(
useCallback(() => {
if (!deviceId || !sessionId) return undefined;
- const cleanup = startFocusedTopicSubscription({
+ return startFocusedTopicSubscription({
deviceId,
owner: `session:${sessionId}`,
- subscribe: (owner, target, topics) => {
- const ready = subscribe(owner, target, topics);
- focusedSubscriptionRef.current = ready;
- return ready;
- },
+ subscribe,
topic: `session:${sessionId}`,
unsubscribe,
});
- return () => { focusedSubscriptionRef.current = null; cleanup(); };
}, [deviceId, sessionId, subscribe, unsubscribe]),
);
diff --git a/apps/mobile/src/__tests__/remoteSyncTask.test.ts b/apps/mobile/src/__tests__/remoteSyncTask.test.ts
index 16389c7ff3..36a647745a 100644
--- a/apps/mobile/src/__tests__/remoteSyncTask.test.ts
+++ b/apps/mobile/src/__tests__/remoteSyncTask.test.ts
@@ -5,6 +5,7 @@ import {
createRemoteSyncRunner,
waitForCachedSubscription,
} from '@/device-link/remoteSyncTask';
+import { SubscriptionAcknowledgements } from '@/device-link/subscriptionAcknowledgements';
function deferred() {
let resolve!: () => void;
@@ -30,12 +31,13 @@ describe('remote sync task runner', () => {
const subscription = new Promise<void>((done, fail) => { resolve = done; reject = fail; });
const run = { signal: controller.signal, isStale: () => controller.signal.aborted };
let settled = false;
- const waiting = waitForCachedSubscription(run, outcome !== 'cold', subscription).then(() => { settled = true; });
+ let ack = false;
+ const waiting = waitForCachedSubscription(run, outcome !== 'cold', subscription, () => ack).then(() => { settled = true; });
const observed = waiting.catch(() => undefined);
try {
await vi.advanceTimersByTimeAsync(0);
expect(settled).toBe(outcome === 'cold');
- if (outcome === 'ack') resolve();
+ if (outcome === 'ack') { ack = true; resolve(); }
if (outcome === 'failure') reject(new Error('offline'));
if (outcome === 'cancel') controller.abort();
if (outcome === 'timeout') await vi.advanceTimersByTimeAsync(2000);
@@ -128,6 +130,33 @@ describe('remote sync task runner', () => {
});
describe('remote sync coordinator', () => {
+ // Unit, PR #6325: previous tests had one promise for one connection. A completed
+ // old subscription (or only the new list ACK) must not start a cached read while
+ // the current detail ACK is missing. Exercise the production ACK table + waiter.
+ it('waits for current detail ACK after a focused reconnect', async () => {
+ vi.useFakeTimers();
+ const acks = new SubscriptionAcknowledgements(() => {});
+ const topics = ['sessions', 'session:s'] as const;
+ acks.set('d', new Set(topics));
+ const previousSubscription = Promise.resolve();
+ await previousSubscription;
+ acks.delete('d');
+ acks.set('d', new Set(['sessions']));
+ const controller = new AbortController();
+ let reads = 0;
+ const waiting = waitForCachedSubscription(
+ { signal: controller.signal }, true, previousSubscription,
+ () => acks.identity('d', topics) !== null,
+ ).then(() => { reads++; });
+ await vi.advanceTimersByTimeAsync(500);
+ expect(reads).toBe(0);
+ acks.set('d', new Set(topics));
+ await vi.advanceTimersByTimeAsync(50);
+ await waiting;
+ expect(reads).toBe(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
// Unit: the ACK may land during cached-return preparation or after the first
// snapshot starts. Only the former can safely remove the recovery batch.
it.each([false, true])('coalesces cached return but preserves an ACK after snapshot start (%s)', async (lateAck) => {
@@ -137,7 +166,7 @@ describe('remote sync coordinator', () => {
let ack = false;
let reads = 0;
const coordinator = createRemoteSyncCoordinator(async run => {
- await waitForCachedSubscription(run, true, subscription.promise);
+ await waitForCachedSubscription(run, true, subscription.promise, () => ack);
const covered = ack;
reads++;
await snapshot.promise;
diff --git a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
index eece9f1c3e..0b3141c32c 100644
--- a/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
+++ b/apps/mobile/src/__tests__/sessionSyncProductionCallbacks.test.ts
@@ -1,8 +1,10 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import ts from 'typescript';
-import { describe, expect, it, vi } from 'vitest';
-import { createRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createRemoteSyncCoordinator, waitForCachedSubscription } from '@/device-link/remoteSyncTask';
+import { createTransientTopicSubscriptionCoordinator } from '@/device-link/transientTopicSubscription';
+import { SubscriptionAcknowledgements } from '@/device-link/subscriptionAcknowledgements';
import { runConnectionScopedSessionMetadataRead, waitForIndependentSnapshotReads } from '@/device-link/sessionSnapshotSingleFlight';
import { syncSessionMessageWindow } from '@/session/sessionMessageWindowSync';
import { shouldClearOperationErrorAfterSync } from '@/session/sessionSyncErrorRecovery';
@@ -56,6 +58,7 @@ function historyAvailable(status: string, presence: boolean | null): boolean {
`return ${expression.getText(source)};`)(status, () => presence, 'd1');
}
const tick = () => new Promise((done) => setTimeout(done, 0));
+afterEach(() => vi.useRealTimers());
const session = { id: 's1', updatedAt: '2026-09-06T00:00:00Z', _count: { messages: 100 } };
const page = {
messages: [{ id: 'm1' }] as { id: string; clientId?: string }[], limit: 1, reducedByPayloadTooLarge: false,
@@ -112,8 +115,10 @@ function fixture(reopen = false, remoteHistoryAvailable = true) {
sessionSubscriptionIdentityRef: { current: JSON.stringify(['d1', 's1', 1]) },
createRemoteSyncReopenCoordinator: () => ({ captureVersion: () => 0 }),
reopenLink: async () => undefined, openLink: async () => undefined,
- subscribe: async () => undefined, sessionsSubscriptionCoordinatorRef: { current: null },
+ subscribe: async () => undefined,
+ sessionsSubscriptionCoordinatorRef: { current: createTransientTopicSubscriptionCoordinator() },
// Retry delays / transport single-flight are tested separately; preserve callbacks and fences here.
+ waitForCachedSubscription: (async () => undefined) as typeof waitForCachedSubscription,
retryRemoteSyncRead: (_run: unknown, read: () => unknown) => read(),
runConnectionScopedSessionMetadataRead, waitForIndependentSnapshotReads, syncSessionMessageWindow,
runSessionProjectionSnapshotSingleFlight: (_scope: unknown, _epoch: unknown, read: () => unknown) => read(),
@@ -153,6 +158,33 @@ function fixture(reopen = false, remoteHistoryAvailable = true) {
}
describe('production session recovery callbacks', () => {
+ // Existing callback-execution guard: PR #6325 missed a focused reconnect where
+ // only the new list topic is ACKed. Use the real waiter and ACK table here so
+ // an old completed Promise cannot start the actual page's history read early.
+ it('waits for current detail ACK before the cached reconnect read', async () => {
+ vi.useFakeTimers();
+ const f = fixture(true);
+ const acks = new SubscriptionAcknowledgements(() => {});
+ const topics = ['sessions', 'session:s1'] as const;
+ acks.set('d1', new Set(topics));
+ acks.delete('d1');
+ acks.set('d1', new Set(['sessions']));
+ f.bindings.waitForCachedSubscription = waitForCachedSubscription;
+ f.bindings.getSubscriptionIdentity = () => acks.identity('d1', topics);
+ const coordinator = createRemoteSyncCoordinator(pageCallback('syncSession', f.bindings));
+ coordinator.setContext('d1:s1:reconnect');
+ const sync = coordinator.request({ reason: 'connection' });
+ await vi.advanceTimersByTimeAsync(500);
+ expect(f.state.rows).toEqual([{ id: 'cached', clientId: 'cached' }]);
+ expect(f.maker.listMessages).not.toHaveBeenCalled();
+ acks.set('d1', new Set(topics));
+ await vi.advanceTimersByTimeAsync(50);
+ await sync;
+ expect(f.maker.listMessages).toHaveBeenCalledTimes(1);
+ expect(f.state.rows).toEqual(page.messages);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
it.each([null, true])('recovers cached history with an online relay and presence=%s', async (presence) => {
// A failed roster request leaves presence unknown even after link/subscription
// recovery. Evaluate the real page gate and then execute its real sync callback.
diff --git a/apps/mobile/src/debug/jankMetrics.test.ts b/apps/mobile/src/debug/jankMetrics.test.ts
index 6cc7778037..713b915ca3 100644
--- a/apps/mobile/src/debug/jankMetrics.test.ts
+++ b/apps/mobile/src/debug/jankMetrics.test.ts
@@ -21,6 +21,29 @@ const store = {
describe("jank metrics", () => {
afterEach(() => setJankMetricsEnabled(false));
+ // Unit, PR #6325: the single-channel case misses the writer's 120-value budget.
+ // Exercise the real serializer with full push/invoke lists and a large transfer
+ // inserted last; important bytes and all emitted rows must survive on disk.
+ it("keeps the largest relay channels within the actual log writer budget", () => {
+ setJankMetricsEnabled(true);
+ setRemoteSessionStoreSizeSource(() => store);
+ for (let i = 0; i < 10; i++) {
+ const channel = `channel:${i}`;
+ recordPushHandled(channel, i + 1);
+ recordInvokeSent(channel);
+ recordInvokeTransfer({ channel, phase: 'sent' });
+ recordInvokeTransfer({ channel, phase: 'result', payloadBytes: (i + 1) * 100 });
+ }
+ const line = serializeMobileDebugRecord('debug', 'performance', ['jank metrics', takeJankMetrics()]);
+ expect(line).not.toContain('[truncated]');
+ const snapshot = JSON.parse(line).args[1];
+ expect(snapshot.relayTransfers[0]).toMatchObject({ channel: 'channel:9', payloadBytes: 1000 });
+ expect(snapshot.relayTransfers).toHaveLength(6);
+ expect(snapshot.relayTransfersOmitted).toBe(4);
+ expect(snapshot.pushCount).toBe(10);
+ expect(snapshot.invokeCount).toBe(10);
+ });
+
it("records nothing while diagnostics are off", () => {
recordPushHandled("local-db:messages:created", 5);
setJankMetricsEnabled(true);
@@ -57,6 +80,7 @@ describe("jank metrics", () => {
invokeCount: 2,
invokes: [{ channel: "git-context:pr-status", count: 2 }],
relayTransfers: [],
+ relayTransfersOmitted: 0,
});
expect(takeJankMetrics()).toMatchObject({ pushCount: 0, invokeCount: 0 });
});
diff --git a/apps/mobile/src/debug/jankMetrics.ts b/apps/mobile/src/debug/jankMetrics.ts
index 474c0c27c7..f8edf7dd9b 100644
--- a/apps/mobile/src/debug/jankMetrics.ts
+++ b/apps/mobile/src/debug/jankMetrics.ts
@@ -112,6 +112,7 @@ export function takeJankMetrics(): {
invokeCount: number;
invokes: ChannelCountRow[];
relayTransfers: ({ channel: string } & TransferCounters)[];
+ relayTransfersOmitted: number;
} {
let pushCount = 0;
let pushMs = 0;
@@ -139,7 +140,13 @@ export function takeJankMetrics(): {
pushes: topChannels(pushRows, (row) => row.totalMs),
invokeCount,
invokes: topChannels(invokeRows, (row) => row.count),
- relayTransfers: [...transfers].map(([channel, counts]) => ({ channel, ...counts })),
+ // Six rows per list keep the complete record below the writer's 120-value
+ // budget. Rank by bytes so a late large response cannot disappear behind noise.
+ relayTransfers: topChannels(
+ [...transfers].map(([channel, counts]) => ({ channel, ...counts })),
+ (row) => row.payloadBytes,
+ ),
+ relayTransfersOmitted: Math.max(0, transfers.size - TOP_CHANNELS),
};
pushes = new Map();
invokes = new Map();
diff --git a/apps/mobile/src/device-link/remoteSyncTask.ts b/apps/mobile/src/device-link/remoteSyncTask.ts
index da24040388..c1cf844187 100644
--- a/apps/mobile/src/device-link/remoteSyncTask.ts
+++ b/apps/mobile/src/device-link/remoteSyncTask.ts
@@ -145,16 +145,35 @@ export async function waitForCachedSubscription(
run: Pick<RemoteSyncRun, 'signal'>,
cached: boolean,
subscription: Promise<unknown>,
+ isSubscribed: () => boolean,
): Promise<void> {
- const settled = subscription.catch(() => undefined);
+ let failed = false;
+ const settled = subscription.then(
+ () => undefined,
+ () => { failed = true; },
+ );
if (!cached) return;
let timer: ReturnType<typeof setTimeout> | undefined;
+ let stopped = false;
+ const deadline = Date.now() + 2000;
try {
- await waitForRemoteSync(run.signal, () => Promise.race([
- settled,
- new Promise<void>(resolve => { timer = setTimeout(resolve, 2000); }),
- ]));
+ await waitForRemoteSync(run.signal, () => new Promise<void>(resolve => {
+ const check = () => {
+ if (stopped) return;
+ if (timer !== undefined) clearTimeout(timer);
+ // Promise completion can belong to an old connection. Only the current
+ // ACK table proves both topics are ready. This samples local state only,
+ // for at most two seconds; it never sends or retries a subscription.
+ if (failed || isSubscribed() || Date.now() >= deadline) {
+ stopped = true;
+ resolve();
+ } else timer = setTimeout(check, Math.min(50, deadline - Date.now()));
+ };
+ check();
+ void settled.then(check);
+ }));
} finally {
+ stopped = true;
if (timer !== undefined) clearTimeout(timer);
}
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 31b30b8e44..237e8fa617 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -237,6 +237,8 @@ Mobile 开启本地诊断时,在原有 30 秒/卡顿区间统计内汇总 `r
首次写入 socket 的请求数、收到的响应数、还原正文前的响应 payload UTF-8 字节数、
`notModified` 与 gzip 命中数。前者不把准入等待或取消算作已发送,也不重复计重传;
后者不包含 envelope、分片头、ACK 与重传字节,不是总线上流量。peer 直连不经过此计数。
+传输行按响应 payload 字节数降序只保留前六个通道,`relayTransfersOmitted` 标明省略的
+通道数;与 push/invoke 列表一起保持在单条日志的 120 值预算内,不能当作全部通道总量。
旧 `invokeCount` 仍是业务调用次数,不能与已发请求数混用。不开诊断时不序列化计量,
不记录请求参数、正文、设备/任务 ID,不改变传输协议或恢复策略。
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 626adccc00..b869ee3fef 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -270,7 +270,9 @@ Mobile 历史读取在 relay 已在线且目标 presence 不是明确不可用
Mobile 返回任务或恢复网络时,历史视图只恢复展示,由页面既有同步协调器发起快照,
不再由视图激活另读一页。已有缓存且订阅尚未确认时,最多等待 2 秒合并本次列表/详情
-订阅确认;确认或失败即继续,首次无缓存立即读取。这个预算只限制等待订阅的时间,
+订阅确认;以当前 ACK 表为准,不复用前一次聚焦/连接已完成的 Promise。等待期间只
+每 50 毫秒检查本地 ACK 状态,不发送网络请求;确认、明确失败或预算到期即继续,
+首次无缓存立即读取。这个预算只限制等待订阅的时间,
不缩短业务请求超时,也不取消原订阅重试。读取开始之后才确认的订阅仍需补齐空档;
读取期间的内容变化仍由历史控制器合并补读,失败保留画面、不推进同步成功标记。
只影响当前手机页面,不重启共享 relay、不改变其它 peer。Desktop 保持原激活读取行为。