Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 合并任务恢复读取并补充弱网传输统计
Dashd28d4d5e174d
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 3dcf798746..e3eeec59b5 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -142,6 +142,7 @@ import {createRemoteSyncReopenCoordinator,retryRemoteSyncRead,useRemoteSyncCoordinator,+ waitForCachedSubscription,type RemoteSyncRun,} from '@/device-link/remoteSyncTask';import {@@ -1807,6 +1808,7 @@ 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}` 把门槛@@ -3652,7 +3654,7 @@ function SessionScreenContent() {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,+ startedAt: snapshotStartedAt, connection: readAckEpochAtStart, phase, reasons: syncRun.reasons,totalMs: Math.max(0, Date.now() - snapshotStartedAt), ...extra,});};@@ -3703,9 +3705,9 @@ function SessionScreenContent() {await retryRemoteSyncRead(syncRun, () => openLink(deviceId));if (subscriptionRetryIsStale()) return;let subscriptionAttemptVersion = syncReopenCoordinator.captureVersion();- // sessions topic 只负责之后的实时推送,不挡快照读。自己在后台- // 处理瞬时 route / ACK 失败;重试前重开 peer link,不再等未来 rehydrate 碰运气。- void sessionsSubscriptionCoordinatorRef.current?.start({+ // 订阅重试独立于快照;缓存返回只在下方有限等待 ACK,冷启动不等待。+ // 瞬时 route / ACK 失败时先重开 peer link,不等未来 rehydrate。+ const sessionsReady = sessionsSubscriptionCoordinatorRef.current!.start({identity: subscriptionIdentityAtStart,isStale: subscriptionRetryIsStale,reopenLink: () => syncReopenCoordinator.reopenAfter(subscriptionAttemptVersion),@@ -3714,6 +3716,12 @@ function SessionScreenContent() {return subscribe(`session:${sessionId}`, deviceId, ['sessions']);},});+ // The focused owner starts the heavy topic independently. Wait only when+ // 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]));};const retryRead = <T,>(read: () => Promise<T>): Promise<T> => {let failedAtVersion: number | null = null;@@ -4263,13 +4271,18 @@ function SessionScreenContent() {useFocusEffect(useCallback(() => {if (!deviceId || !sessionId) return undefined;- return startFocusedTopicSubscription({+ const cleanup = startFocusedTopicSubscription({deviceId,owner: `session:${sessionId}`,- subscribe,+ subscribe: (owner, target, topics) => {+ const ready = subscribe(owner, target, topics);+ focusedSubscriptionRef.current = ready;+ return ready;+ },topic: `session:${sessionId}`,unsubscribe,});+ return () => { focusedSubscriptionRef.current = null; cleanup(); };}, [deviceId, sessionId, subscribe, unsubscribe]),);diff --git a/apps/mobile/src/__tests__/remoteHistoryReentry.test.ts b/apps/mobile/src/__tests__/remoteHistoryReentry.test.tsindex e3aae677b7..0bbbbfd737 100644--- a/apps/mobile/src/__tests__/remoteHistoryReentry.test.ts+++ b/apps/mobile/src/__tests__/remoteHistoryReentry.test.ts@@ -85,10 +85,14 @@ describe('history reentry', () => {const reopened = getRemoteHistoryView('d', 's', next);expect(reopened.view).toBe(entry.view);mount(reopened, next);- expect(reopened.view.getSnapshot()).toMatchObject({ ready: true, loading: true });+ expect(reopened.view.getSnapshot()).toMatchObject({ ready: true, loading: false });+ expect(next.readHistoryView).not.toHaveBeenCalled();expect(reopened.view.getSnapshot().items).toBe(items);+ // Resume belongs to the session sync coordinator, which starts one read+ // after its subscription grace period instead of activation starting another.+ const sync = reopened.view.refresh(false, true);resolve(page());- await reopened.view.refresh();+ await sync;expect(reopened.view.getSnapshot().items).toBe(items);expect(first.readHistoryView).toHaveBeenCalledTimes(1);expect(next.readHistoryView).toHaveBeenCalledTimes(1);diff --git a/apps/mobile/src/__tests__/remoteSyncTask.test.ts b/apps/mobile/src/__tests__/remoteSyncTask.test.tsindex f93eed3ee0..16389c7ff3 100644--- a/apps/mobile/src/__tests__/remoteSyncTask.test.ts+++ b/apps/mobile/src/__tests__/remoteSyncTask.test.ts@@ -1,8 +1,9 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {createRemoteSyncCoordinator,createRemoteSyncReopenCoordinator,createRemoteSyncRunner,+ waitForCachedSubscription,} from '@/device-link/remoteSyncTask';function deferred() {@@ -16,8 +17,36 @@ function deferred() {function nextTick(): Promise<void> {return new Promise((resolve) => setTimeout(resolve, 0));}+afterEach(() => vi.useRealTimers());describe('remote sync task runner', () => {+ // Unit: a cached return used to read before ACK and repeat the whole batch.+ // Bound the optimization without delaying cold reads or losing late recovery.+ it.each(['ack', 'timeout', 'failure', 'cancel', 'cold'] as const)('bounds cached subscription waiting: %s', async (outcome) => {+ vi.useFakeTimers();+ const controller = new AbortController();+ let resolve!: () => void;+ let reject!: (error: Error) => void;+ 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; });+ const observed = waiting.catch(() => undefined);+ try {+ await vi.advanceTimersByTimeAsync(0);+ expect(settled).toBe(outcome === 'cold');+ if (outcome === 'ack') resolve();+ if (outcome === 'failure') reject(new Error('offline'));+ if (outcome === 'cancel') controller.abort();+ if (outcome === 'timeout') await vi.advanceTimersByTimeAsync(2000);+ await observed;+ if (outcome === 'cancel') await expect(waiting).rejects.toThrow('superseded');+ else expect(settled).toBe(true);+ expect(vi.getTimerCount()).toBe(0);+ resolve(); // A late ACK may still drive the existing recovery effect.+ } finally { vi.useRealTimers(); }+ });+it('shares one successful peer reopen across staggered retries in the same sync run', async () => {const reopen = vi.fn(async () => undefined);const coordinator = createRemoteSyncReopenCoordinator(reopen);@@ -99,6 +128,34 @@ describe('remote sync task runner', () => {});describe('remote sync coordinator', () => {+ // 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) => {+ vi.useFakeTimers();+ const subscription = deferred();+ const snapshot = deferred();+ let ack = false;+ let reads = 0;+ const coordinator = createRemoteSyncCoordinator(async run => {+ await waitForCachedSubscription(run, true, subscription.promise);+ const covered = ack;+ reads++;+ await snapshot.promise;+ if (covered) run.satisfy('subscription-acked');+ });+ coordinator.setContext('device:session:visit');+ const sync = coordinator.request({ reason: 'passive-refresh' });+ await vi.advanceTimersByTimeAsync(lateAck ? 2000 : 0);+ expect(reads).toBe(lateAck ? 1 : 0);+ ack = true;+ subscription.resolve();+ void coordinator.request({ reason: 'subscription-acked' });+ snapshot.resolve();+ await sync;+ expect(reads).toBe(lateAck ? 2 : 1);+ expect(coordinator.isRunning()).toBe(false);+ });+it('merges repeated passive requests into one follow-up run', async () => {const gates = [deferred(), deferred()];const runs: Array<{ reasons: readonly string[]; replaceMessages: boolean }> = [];diff --git a/apps/mobile/src/debug/jankMetrics.test.ts b/apps/mobile/src/debug/jankMetrics.test.tsindex 0357c33af9..6cc7778037 100644--- a/apps/mobile/src/debug/jankMetrics.test.ts+++ b/apps/mobile/src/debug/jankMetrics.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it } from "vitest";import {recordInvokeSent,+ recordInvokeTransfer,recordPushHandled,setJankMetricsEnabled,setRemoteSessionStoreSizeSource,@@ -55,6 +56,7 @@ describe("jank metrics", () => {],invokeCount: 2,invokes: [{ channel: "git-context:pr-status", count: 2 }],+ relayTransfers: [],});expect(takeJankMetrics()).toMatchObject({ pushCount: 0, invokeCount: 0 });});@@ -65,6 +67,8 @@ describe("jank metrics", () => {// Channel names that look sensitive must not take their counts with them.recordPushHandled("auth:token-refreshed", 3);recordInvokeSent("local-db:messages:view");+ recordInvokeTransfer({ channel: 'local-db:messages:view', phase: 'sent' });+ recordInvokeTransfer({ channel: 'local-db:messages:view', phase: 'result', payloadBytes: 95, notModified: true });const line = serializeMobileDebugRecord("debug", "performance", ["jank metrics",takeJankMetrics(),@@ -75,6 +79,8 @@ describe("jank metrics", () => {store,pushes: [{ count: 1, totalMs: 3 }],invokes: [{ channel: "local-db:messages:view", count: 1 }],+ relayTransfers: [{ channel: 'local-db:messages:view', sent: 1, results: 1, payloadBytes: 95, notModified: 1, gzip: 0 }],});+ expect(takeJankMetrics().relayTransfers).toEqual([]);});});diff --git a/apps/mobile/src/debug/jankMetrics.ts b/apps/mobile/src/debug/jankMetrics.tsindex df4c70e298..474c0c27c7 100644--- a/apps/mobile/src/debug/jankMetrics.ts+++ b/apps/mobile/src/debug/jankMetrics.ts@@ -40,6 +40,8 @@ const TOP_CHANNELS = 6;let enabled = false;let pushes = new Map<string, ChannelTiming>();let invokes = new Map<string, number>();+type TransferCounters = { sent: number; results: number; payloadBytes: number; notModified: number; gzip: number };+let transfers = new Map<string, TransferCounters>();let storeSizeSource: (() => RemoteSessionStoreSizeMetrics) | null = null;export function setJankMetricsEnabled(next: boolean): void {@@ -47,6 +49,7 @@ export function setJankMetricsEnabled(next: boolean): void {enabled = next;pushes = new Map();invokes = new Map();+ transfers = new Map();}export function jankMetricsEnabled(): boolean {@@ -67,6 +70,23 @@ export function recordInvokeSent(channel: string): void {invokes.set(channel, (invokes.get(channel) ?? 0) + 1);}+/** Relay requests that actually wrote to the socket, and encoded response payloads.+ * Excludes peer-direct traffic, frame headers and retransmissions; not a wire-byte total.+ */+export function recordInvokeTransfer(event: { channel: string; phase: 'sent' | 'result';+ payloadBytes?: number; notModified?: boolean; gzip?: boolean }): void {+ if (!enabled) return;+ const entry = transfers.get(event.channel) ?? { sent: 0, results: 0, payloadBytes: 0, notModified: 0, gzip: 0 };+ if (event.phase === 'sent') entry.sent++;+ else {+ entry.results++;+ entry.payloadBytes += event.payloadBytes ?? 0;+ if (event.notModified) entry.notModified++;+ if (event.gzip) entry.gzip++;+ }+ transfers.set(event.channel, entry);+}+/** The store registers itself so this module does not import the store's module graph. */export function setRemoteSessionStoreSizeSource(source: () => RemoteSessionStoreSizeMetrics,@@ -91,6 +111,7 @@ export function takeJankMetrics(): {pushes: ChannelTimingRow[];invokeCount: number;invokes: ChannelCountRow[];+ relayTransfers: ({ channel: string } & TransferCounters)[];} {let pushCount = 0;let pushMs = 0;@@ -118,8 +139,10 @@ export function takeJankMetrics(): {pushes: topChannels(pushRows, (row) => row.totalMs),invokeCount,invokes: topChannels(invokeRows, (row) => row.count),+ relayTransfers: [...transfers].map(([channel, counts]) => ({ channel, ...counts })),};pushes = new Map();invokes = new Map();+ transfers = new Map();return snapshot;}diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 6d439c4249..ec6333b17e 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -171,7 +171,7 @@ import type { InputProjection, PendingInteraction, RemoteMessage } from '@/sessiimport { prepareVisualMockDeviceLinkContext } from '@/debug/visualMock';import { meterDeviceLinkInvokes, recordDeviceLinkPush } from '@/debug/deviceLinkTraffic';import { decodeGzipBase64TextBounded } from '@/utils/gzipBase64';-import { jankMetricsEnabled, recordInvokeSent, recordPushHandled } from '@/debug/jankMetrics';+import { jankMetricsEnabled, recordInvokeSent, recordInvokeTransfer, recordPushHandled } from '@/debug/jankMetrics';import { localNetworkStore, type NetworkState } from '@/device-link/localNetworkStatus';export interface DeviceLinkContextValue {@@ -966,6 +966,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {logger: mobileDeviceLinkLogger,// 弱网减流量:声明可解 gzip,大结果压缩、内容未变的结果只回标记(被控端支持时)。transferCodec: { gunzipBase64: decodeGzipBase64TextBounded },+ invokeMetrics: { enabled: jankMetricsEnabled, record: recordInvokeTransfer },// Mobile 具备按 deviceId 独立 openLink/订阅/快照恢复能力。可靠 ACK// 耗尽时只复位该 peer,共享 WSS 和其它远端继续工作;恢复仍只使用所有// Desktop 版本都支持的 link-open,不增加 wire/capability 要求。diff --git a/apps/mobile/src/device-link/remoteSyncTask.ts b/apps/mobile/src/device-link/remoteSyncTask.tsindex 6545c62961..da24040388 100644--- a/apps/mobile/src/device-link/remoteSyncTask.ts+++ b/apps/mobile/src/device-link/remoteSyncTask.ts@@ -138,6 +138,27 @@ export interface RemoteSyncCoordinator {isRunning(): boolean;}+/** Cached reading can coalesce with ACK, but a broken subscription must not stall snapshots.+ * This is only a validation grace period; cold reads and the subscription retry loop remain independent.+ */+export async function waitForCachedSubscription(+ run: Pick<RemoteSyncRun, 'signal'>,+ cached: boolean,+ subscription: Promise<unknown>,+): Promise<void> {+ const settled = subscription.catch(() => undefined);+ if (!cached) return;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ await waitForRemoteSync(run.signal, () => Promise.race([+ settled,+ new Promise<void>(resolve => { timer = setTimeout(resolve, 2000); }),+ ]));+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+}+interface PendingRemoteSync {reasons: Set<string>;replaceMessages: boolean;diff --git a/apps/mobile/src/session/remoteHistoryViews.ts b/apps/mobile/src/session/remoteHistoryViews.tsindex 364ca34fdf..59cf133b18 100644--- a/apps/mobile/src/session/remoteHistoryViews.ts+++ b/apps/mobile/src/session/remoteHistoryViews.ts@@ -49,6 +49,7 @@ export function getRemoteHistoryView(deviceId: string, sessionId: string, readerif (existing) return existing;const entry: Entry = { deviceId, sessionId, reader, consumers: 0,view: new HistoryViewController<RemoteMessage>({+ refreshOnResume: false,page: (before) => entry.reader.readHistoryView(sessionId, before),details: (ref, after) => entry.reader.readWorkDetails(sessionId, ref, after),expanded: (refs) => entry.reader.setHistoryExpanded(sessionId, refs),diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex f1846ee1e8..31b30b8e44 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -233,6 +233,13 @@ Desktop 的压缩保持 gzip level 4 与同步发送/错误处理契约,手DEBUG 统计只记原始/gzip/wire 字节与压缩耗时,不记录正文或凭证。回归见 Desktop `device-link/__tests__/transferCodec.test.ts`(实际 zlib/pako 解码)。+Mobile 开启本地诊断时,在原有 30 秒/卡顿区间统计内汇总 `relayTransfers`:每个 channel+首次写入 socket 的请求数、收到的响应数、还原正文前的响应 payload UTF-8 字节数、+`notModified` 与 gzip 命中数。前者不把准入等待或取消算作已发送,也不重复计重传;+后者不包含 envelope、分片头、ACK 与重传字节,不是总线上流量。peer 直连不经过此计数。+旧 `invokeCount` 仍是业务调用次数,不能与已发请求数混用。不开诊断时不序列化计量,+不记录请求参数、正文、设备/任务 ID,不改变传输协议或恢复策略。+## 群执行终态与错误展示发送前拒绝、SDK 错误、正常完成和宿主超时进入同一个执行收尾入口;首个终态及提交正文固定,diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 7fd95c93ad..626adccc00 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -268,6 +268,15 @@ Mobile 历史读取在 relay 已在线且目标 presence 不是明确不可用历史控制器与页面同步;也不能为了放行读取伪造在线快照。明确离线/停用或 relay 未在线时仍只展示缓存,授权、撤权和旧代结果拦截继续由原链路处理。+Mobile 返回任务或恢复网络时,历史视图只恢复展示,由页面既有同步协调器发起快照,+不再由视图激活另读一页。已有缓存且订阅尚未确认时,最多等待 2 秒合并本次列表/详情+订阅确认;确认或失败即继续,首次无缓存立即读取。这个预算只限制等待订阅的时间,+不缩短业务请求超时,也不取消原订阅重试。读取开始之后才确认的订阅仍需补齐空档;+读取期间的内容变化仍由历史控制器合并补读,失败保留画面、不推进同步成功标记。+只影响当前手机页面,不重启共享 relay、不改变其它 peer。Desktop 保持原激活读取行为。+实现与回归见 `remoteSyncTask.ts`、`remoteHistoryViews.ts`、`remoteSyncTask.test.ts`、+`remoteHistoryReentry.test.ts` 与共享 `historyView.test.ts`。+Mobile 明确观察到断网后恢复,或已连接网络类型切换(如蜂窝 → Wi-Fi)时,替换本机仍显示 online 的旧连接,避免旧路径上的半开连接额外等待探测超时。相同类型的能力通知、仅 Internet reachability 变化和未知网络仍走原探测预算;diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 376758e21b..8896a7c845 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -95,6 +95,7 @@ function makeHarness(opts?: {logger?: ConstructorParameters<typeof DeviceLinkClient>[0]['logger'];peerFailurePolicy?: ConstructorParameters<typeof DeviceLinkClient>[0]['peerFailurePolicy'];peerResetReadRetry?: ConstructorParameters<typeof DeviceLinkClient>[0]['peerResetReadRetry'];+ invokeMetrics?: ConstructorParameters<typeof DeviceLinkClient>[0]['invokeMetrics'];}): Harness {const sockets: FakeWs[] = [];const client = new DeviceLinkClient({@@ -115,6 +116,7 @@ function makeHarness(opts?: {},peerFailurePolicy: opts?.peerFailurePolicy,peerResetReadRetry: opts?.peerResetReadRetry,+ invokeMetrics: opts?.invokeMetrics,timing: {reconnectBaseMs: 5,reconnectMaxMs: 40,@@ -266,7 +268,9 @@ describe('outbound invoke admission', () => {it('rechecks a queued write before dispatch and releases its slot when the caller cancels', async () => {vi.useFakeTimers();- const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 30_000 } });+ const metrics = vi.fn();+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 30_000 },+ invokeMetrics: { enabled: () => true, record: metrics } });const calls: Promise<unknown>[] = [];try {h.client.start(); await vi.advanceTimersByTimeAsync(1); h.current().ack();@@ -291,6 +295,7 @@ describe('outbound invoke admission', () => {expect(sent()).toHaveLength(13);expect(sent().at(-1)?.payload).toMatchObject({ channel: 'maker:send', args: ['fresh'] });expect(sent().some(e => (e.payload as { args: unknown[] }).args[0] === 'stale')).toBe(false);+ expect(metrics.mock.calls.filter(([event]) => event.phase === 'sent')).toHaveLength(13);} finally {h.client.stop(); await Promise.all(calls); vi.useRealTimers();}@@ -787,7 +792,7 @@ function makeRelayClient(relay: MemoryRelay,deviceId: string,timing?: ConstructorParameters<typeof DeviceLinkClient>[0]['timing'],- extra?: Pick<ConstructorParameters<typeof DeviceLinkClient>[0], 'transferCodec'>,+ extra?: Pick<ConstructorParameters<typeof DeviceLinkClient>[0], 'transferCodec' | 'invokeMetrics'>,): DeviceLinkClient {return new DeviceLinkClient({...extra,@@ -7917,7 +7922,9 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {};const relay = new MemoryRelay();const host = makeRelayClient(relay, 'desktop', undefined, { transferCodec: codec });- const controller = makeRelayClient(relay, 'ios', undefined, { transferCodec: codec });+ const metrics = vi.fn();+ const controller = makeRelayClient(relay, 'ios', undefined, { transferCodec: codec,+ invokeMetrics: { enabled: () => true, record: metrics } });let rows = Array.from({ length: 400 }, (_, i) => ({ id: `session-${i}`, title: '弱网任务', status: 'idle' }));const handled: Envelope[] = [];const offHost = host.onFrame((env) => {@@ -7956,6 +7963,14 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {expect(second).toEqual({ ok: true, result: rows });expect((handled[1]!.payload as InvokePayload).transfer?.ifNoneMatch).toEqual(expect.any(String));expect(resultBytes() - firstBytes).toBeLessThan(1_000);+ // Unit: measure encoded logical payloads, not the reconstructed full page.+ expect(metrics.mock.calls.map(([event]) => event.phase)).toEqual(['sent', 'result', 'sent', 'result']);+ const encodedResponses = (relay.deliveredTo.get('ios') ?? []).filter(env => env.kind === 'invoke-result')+ .map(env => Buffer.byteLength(parseTransportPayload(env.payload)?.data ?? JSON.stringify(env.payload)));+ expect(metrics.mock.calls[1][0]).toMatchObject({ gzip: true, notModified: false, payloadBytes: encodedResponses[0] });+ expect(metrics.mock.calls[3][0]).toMatchObject({ notModified: true, payloadBytes: encodedResponses[1] });+ // A failed diagnostics sink cannot turn a valid response into a failed read.+ metrics.mockImplementation(() => { throw new Error('diagnostic sink failed'); });// Each call returns its own object: a consumer mutating one result cannot corrupt the cache.expect(second.ok && second.result).not.toBe(first.ok && first.result);diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex 9357ef092f..e2a10bcd3a 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -272,6 +272,12 @@ export interface DeviceLinkClientOptions {* 不传时 wire 行为与旧版完全相同。*/transferCodec?: DeviceLinkTransferCodec;+ /** Optional local counters; no content/identities, never part of delivery decisions. */+ invokeMetrics?: {+ enabled(): boolean;+ record(event: { channel: string; phase: 'sent' | 'result'; payloadBytes?: number;+ notModified?: boolean; gzip?: boolean }): void;+ };/** 测试注入:覆盖重连/心跳的时间参数 */timing?: Partial<DeviceLinkTiming>;}@@ -1456,6 +1462,7 @@ export class DeviceLinkClient {'invoke-result',timeoutMs,);+ this.reportInvokeMetric(payload.channel, env.payload as InvokeResultPayload);const result = transfer? transfer.decode(env.payload as InvokeResultPayload): env.payload as InvokeResultPayload;@@ -1630,6 +1637,17 @@ export class DeviceLinkClient {// ─── 内部:请求配对 ─────────────────────────────────────────────────────────+ private reportInvokeMetric(channel: string, result?: InvokeResultPayload): void {+ try {+ if (!this.opts.invokeMetrics?.enabled()) return;+ this.opts.invokeMetrics.record(result === undefined ? { channel, phase: 'sent' } : {+ channel, phase: 'result', payloadBytes: byteLength(JSON.stringify(result)),+ notModified: result.ok && result.transfer?.notModified === true,+ gzip: result.ok && typeof result.transfer?.gzipBase64 === 'string',+ });+ } catch { /* Diagnostics must never affect delivery or response decoding. */ }+ }+/** 发送请求帧并等待同 id 响应;同 id relay-error 转成 DeviceLinkError reject */private request(env: Omit<Envelope, 'id'>,@@ -1703,6 +1721,7 @@ export class DeviceLinkClient {noteFirstWrite: () => {if (firstWriteAt !== undefined) return;firstWriteAt = this.monotonicNow();+ if (env.kind === 'invoke') this.reportInvokeMetric((env.payload as InvokePayload).channel);// Only the first write can move the deadline. Replays and partial writes// cannot extend it; total transport lifetime is at most sendWaitMs + timeout.deadlineMonotonicAt = Math.min(firstWriteAt + timeout, startedMonotonicAt + sendWaitMs + timeout);diff --git a/packages/maker-shared/src/__tests__/historyView.test.ts b/packages/maker-shared/src/__tests__/historyView.test.tsindex eb88c87513..57da07eeac 100644--- a/packages/maker-shared/src/__tests__/historyView.test.ts+++ b/packages/maker-shared/src/__tests__/historyView.test.ts@@ -183,6 +183,38 @@ const ungroupedStructure = {};describe('shared history view lifecycle', () => {+ // Unit: Mobile's session coordinator owns resume reads. Previously activation+ // issued a pre-ACK page even when the coordinated batch would read after ACK.+ it('preserves cached content on managed resume and still reconciles changes during a read', async () => {+ vi.useFakeTimers();+ const page = (content: string) => ({ version: 1 as const,+ items: projectHistoryView([row(0, 'user', content)], false), hasMore: false, nextCursor: null });+ const read = vi.fn(async () => page('cached'));+ const view = new HistoryViewController({ page: read, refreshOnResume: false,+ details: async () => ({ version: 1 as const, messages: [], hasMore: false, nextCursor: null }),+ expanded: async () => undefined });+ try {+ await view.refresh();+ view.setActive(false);+ view.setNetworkAvailable(false);+ view.setActive(true);+ view.setNetworkAvailable(true);+ expect(read).toHaveBeenCalledTimes(1);+ expect(view.getSnapshot()).toMatchObject({ ready: true, stale: true, items: page('cached').items });+ let resolve!: (value: ReturnType<typeof page>) => void;+ read.mockImplementationOnce(() => new Promise(done => { resolve = done; }));+ const syncing = view.refresh();+ view.invalidate(); // Edit/delete/completion received after the read began.+ await vi.advanceTimersByTimeAsync(500);+ read.mockResolvedValue(page('edited'));+ resolve(page('cached'));+ await syncing;+ await vi.advanceTimersByTimeAsync(500);+ expect(read).toHaveBeenCalledTimes(3);+ expect(view.getSnapshot().items).toEqual(page('edited').items);+ } finally { view.setActive(false); vi.useRealTimers(); }+ });+it.each([true, false])('retains loaded history only when regrouping proves the same source start (%s)', async (overlap) => {const prefix = projectHistoryView([row(0, 'user', 'Earlier')], false);const rows = [row(1, 'assistant', 'Looking into it'), row(2, 'thinking', 'details'),diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.tsindex 2af65528e7..42a7a2873b 100644--- a/packages/maker-shared/src/historyViewController.ts+++ b/packages/maker-shared/src/historyViewController.ts@@ -32,6 +32,8 @@ export interface HistoryViewSnapshot<T extends HistoryMessageSource> {}export interface HistoryViewTransport<T extends HistoryMessageSource> {+ /** False when the owning screen already coordinates focus/reconnect snapshots. */+ refreshOnResume?: boolean;page(before?: string): Promise<HistoryViewPage<T>>;details(summary: HistoryWorkSummary, after?: string): Promise<HistoryDetailPage<T>>;/** Full replacement of this view's intent; empty releases detail streaming. */@@ -77,7 +79,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {this.publish({ loading: false, ...(available ? {} : { stale: this.state.ready }),details: new Map([...this.state.details].map(([key, detail]) =>[key, detail.loading ? { ...detail, loading: false } : detail])) });- if (available && this.active) void this.refresh();+ if (available && this.active && this.transport.refreshOnResume !== false) void this.refresh();}getSnapshot = (): HistoryViewSnapshot<T> => this.state;/** Pagination feedback only; background validation must not disturb the reading viewport. */@@ -342,7 +344,10 @@ export class HistoryViewController<T extends HistoryMessageSource> {/** View blur/background and source resets invalidate all outstanding reads. */setActive(active: boolean): void {- if (active === this.active) { if (active && !this.state.ready) void this.refresh(); return; }+ if (active === this.active) {+ if (active && !this.state.ready && this.transport.refreshOnResume !== false) void this.refresh();+ return;+ }if (this.refreshTimer) clearTimeout(this.refreshTimer);this.refreshTimer = null;this.active = active;@@ -352,7 +357,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {this.detailRuns.clear();this.publish({ loading: false, ...(active ? {} : { stale: this.state.ready }) });this.sendIntent();- if (active) void this.refresh();+ if (active && this.transport.refreshOnResume !== false) void this.refresh();}reset(): void {this.generation++;