Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(desktop): 统一本地与远程任务读取并合并目录刷新 (#4602)
Dash8538a22735b5
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.tsindex b125b060fd..1beb54ca16 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts@@ -950,7 +950,7 @@ describe('remote companion Session visibility at the device-link boundary', () =describe('background database admission covers the complete remote list lifecycle', () => {- it.each(['local-db:sessions:list', 'local-db:bots:list', 'maker:list-active', 'local-db:sessions:interrupted-pending', 'maker:remote-resources:list'])(+ it.each(['local-db:sessions:list', 'local-db:sessions:get-many', 'local-db:bots:list', 'maker:list-active', 'local-db:sessions:interrupted-pending', 'maker:remote-resources:list'])('keeps %s handler and visibility checks in background admission', async (channel) => {const admissions: string[] = [];setRemoteBotSessionLookup(async () => {@@ -1129,3 +1129,13 @@ it('isolates an unresponsive peer with an overloaded mutation replay from anotheexpect(handler).toHaveBeenCalledTimes(1);expect(client.closeLink).not.toHaveBeenCalled();});++it('lets a controller fall back to individual reads when a detail batch exceeds the frame budget', () => {+ const client = mkClient();+ client.sendInvokeResult.mockImplementationOnce(() => { throw tooLarge(); });+ expect(__testing.sendInvokeResultSafe(client as never, 'ctrl-1', 'batch',+ { ok: true, result: [{ id: 'large' }] }, 'local-db:sessions:get-many')).toBe(true);+ expect(client.sendInvokeResult).toHaveBeenLastCalledWith('ctrl-1', 'batch', {+ ok: false, error: { code: 'IPC_ERROR', message: '[PRECONDITION_FAILED] REMOTE_SESSION_BATCH_TOO_LARGE' },+ });+});diff --git a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.tsindex c126b7a49e..62e51a3f6f 100644--- a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts@@ -43,3 +43,14 @@ it('fails closed for incomplete batch results, rejects hidden gets and clears aexpect(await projectRemoteSessionResult('maker:list-active', [{ sessionId: 's1' }])).toEqual([{ sessionId: 's1' }]);expect(batch).toHaveBeenCalledTimes(1);});+++it('filters batch detail reads using the shared fresh visibility lookup', async () => {+ let hidden = false;+ const batch = vi.fn(async () => new Map([['s', hidden ? 'hidden' as const : 'visible' as const]]));+ setRemoteBotSessionLookup(async () => 'visible', batch);+ expect(await projectRemoteSessionResult('local-db:sessions:get-many', [{ id: 's' }])).toEqual([{ id: 's' }]);+ hidden = true;+ expect(await projectRemoteSessionResult('local-db:sessions:get-many', [{ id: 's' }])).toEqual([]);+ expect(batch).toHaveBeenCalledTimes(2);+});diff --git a/apps/desktop/src/main/device-link/__tests__/remoteInvokeTiming.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteInvokeTiming.test.tsnew file mode 100644index 0000000000..617153803b--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/remoteInvokeTiming.test.ts@@ -0,0 +1,11 @@+import { expect, it } from 'vitest';+import { RemoteInvokeTiming } from '../remoteInvokeTiming';+it('records failed stages without changing the error and separates subsequent work', async () => {+ let now = 0;+ const timing = new RemoteInvokeTiming(() => now);+ const failure = new Error('private');+ await expect(timing.measure('authorizeBefore', async () => { now += 125; throw failure; })).rejects.toBe(failure);+ expect(await timing.measure('handler', async () => { now += 250; return 42; })).toBe(42);+ expect(timing.stages).toEqual({ authorizeBefore: 125, handler: 250 });+ expect(JSON.stringify(timing)).not.toContain('private');+});diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex f87bc87c11..d237d456b3 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -21,6 +21,7 @@ import { requestFilePeer, stopFilePeers } from './filePeer';* 本地 settings(第二道),server 缓存陈旧 / 被绕过时兜底。*/+import { RemoteInvokeTiming } from './remoteInvokeTiming.js';import {computeAllowlistHash,canCoalesceRemoteListing,@@ -163,6 +164,7 @@ const REMOTE_INVOKE_FRAME_SAFETY_BYTES = 1024;// interactive activity would refresh the updater quiet period forever for sessions-only viewers.const UPDATE_RELAUNCH_NON_BLOCKING_INVOKE_CHANNELS: ReadonlySet<string> = new Set(['local-db:sessions:list',+ 'local-db:sessions:get-many',]);const textEncoder = new TextEncoder();const offlinePushQueue = createOfflinePushQueue();@@ -645,6 +647,7 @@ const REMOTE_INVOKE_IN_FLIGHT_LIMIT = 64;/** Host DB admission is independent of whether a read can share an in-flight snapshot. */const BACKGROUND_REMOTE_INVOKE_CHANNELS: ReadonlySet<string> = new Set(['local-db:sessions:list',+ 'local-db:sessions:get-many','local-db:sessions:interrupted-pending','maker:list-active','local-db:bots:list',@@ -2565,9 +2568,10 @@ async function handleInvoke(const releaseBusyLease = shouldAcquireRemoteInvokeBusyLease(src, payload)? acquireRemoteInvokeBusyLease(): () => undefined;- const handlerStartedAt = Date.now();+ const handlerStartedAt = performance.now();+ const timing = new RemoteInvokeTiming();const executionPromise = Promise.resolve()- .then(() => executeInvoke(src, payload))+ .then(() => executeInvoke(src, payload, timing)).catch((err): InvokeResultPayload => {const message = err instanceof Error ? err.message : String(err);log.error(`remote invoke escaped execution boundary from ${shortId(src)}: ${message}`);@@ -2599,11 +2603,11 @@ async function handleInvoke(let result: InvokeResultPayload;try {result = normalizeInvokeResultForWire(await resultPromise);- const executionWaitMs = Date.now() - handlerStartedAt;+ const executionWaitMs = Math.round(performance.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}`);+ + ` executionWaitMs=${executionWaitMs} ok=${result.ok} stagesMs=${JSON.stringify(timing.stages)}`);}if ((remoteInvokeLinkEpoch.get(src) ?? 0) !== invokeLinkEpoch) return;} finally {@@ -2633,8 +2637,9 @@ async function handleInvoke(async function executeInvoke(src: string,payload: InvokePayload | undefined,+ timing: RemoteInvokeTiming,): Promise<InvokeResultPayload> {- return await runInvoke(src, payload);+ return await runInvoke(src, payload, timing);}function settleRemoteInvokeWithOrphanDeadline(@@ -2946,7 +2951,9 @@ function trySendInvokeResult(}}}- candidate = { ok: false, error: { code, message } };+ candidate = channel === 'local-db:sessions:get-many'+ ? { ok: false, error: { code: 'IPC_ERROR', message: '[PRECONDITION_FAILED] REMOTE_SESSION_BATCH_TOO_LARGE' } }+ : { ok: false, error: { code, message } };try {client.sendInvokeResult(src, requestId, candidate);return { sent: true, result: candidate };@@ -3523,11 +3530,12 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeResexport async function runInvoke(src: string,payload: InvokePayload | undefined,+ timing = new RemoteInvokeTiming(),): Promise<InvokeResultPayload> {- return withRemoteDbAdmission(payload?.channel, () => executeRemoteInvoke(src, payload));+ return withRemoteDbAdmission(payload?.channel, () => executeRemoteInvoke(src, payload, timing));}-async function executeRemoteInvoke(src: string, payload: InvokePayload | undefined): Promise<InvokeResultPayload> {+async function executeRemoteInvoke(src: string, payload: InvokePayload | undefined, timing: RemoteInvokeTiming): Promise<InvokeResultPayload> {if (!payload || typeof payload.channel !== 'string') {return { ok: false, error: { code: 'INTERNAL', message: 'malformed invoke payload' } };}@@ -3726,11 +3734,11 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefinconst invocationOwner = broadcastTap.captureDataOwnerBroadcastScope();const historyView = (payload.channel === 'local-db:messages:view' || payload.channel === 'local-db:messages:view-intent')&& typeof args[0] === 'string' ? subscriptions.prepareHistoryView(src, args[0]) : undefined;- if (hasRemoteBotSessionLookup()) await assertRemoteBotInvocationAllowed(args, payload.channel);+ if (hasRemoteBotSessionLookup()) await timing.measure('authorizeBefore', () => assertRemoteBotInvocationAllowed(args, payload.channel));const listingCapabilities = payload.channel === 'maker:provider:list'? invokeControllerCapabilities(payload): [];- const result = await runDeviceLinkInvokeContext(+ const result = await timing.measure('handler', () => runDeviceLinkInvokeContext({controllerDeviceId: src,channel: payload.channel,@@ -3744,16 +3752,14 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefinpayload.channel,payload.channel === 'maker:provider:list' ? [] : args,),- );+ ));handlerCompleted = true;- if (hasRemoteBotSessionLookup()) await assertRemoteBotInvocationAllowed(args, payload.channel);+ if (hasRemoteBotSessionLookup()) await timing.measure('authorizeAfter', () => assertRemoteBotInvocationAllowed(args, payload.channel));if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(invocationOwner)) throw new Error('[NOT_FOUND] Session does not exist');// 远程 set-* 回流:被控端 set-* runtime-only,补一次 DB 持久化 + 广播 patched,让控制端// 镜像收敛到被控端真相(取代控制端乐观覆盖)。本机会话不走这条(走 renderer update)。- await persistRemoteSetting(payload.channel, payload.args ?? [], result);- return {- ok: true,- result: projectInvokeResultForTunnel(+ await timing.measure('persist', () => persistRemoteSetting(payload.channel, payload.args ?? [], result));+ const projected = await timing.measure('project', async () => projectInvokeResultForTunnel(payload.channel,await projectRemoteSessionResult(payload.channel, result),subscriptions.controllerSupports(@@ -3762,8 +3768,9 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefin)|| listingCapabilities.includes(CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2),args,- ),- };+ ));+ if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(invocationOwner)) throw new Error('[NOT_FOUND] Session does not exist');+ return { ok: true, result: projected };} catch (err) {// 被控端 handler 的 throwIpcError `[CODE] message` 原样透传,// 控制端 renderer 继续用 extractIpcError 解码diff --git a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.tsindex eee53fd8dc..85643034a1 100644--- a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts+++ b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts@@ -49,7 +49,7 @@ export async function assertRemoteBotInvocationAllowed(args: unknown[], channel}export async function projectRemoteSessionResult(channel: string, value: unknown): Promise<unknown> {- if (!lookup || !['local-db:sessions:get', 'local-db:sessions:list', 'maker:list-active', 'local-db:sessions:interrupted-pending', 'local-db:bots:get', 'local-db:bots:list', 'maker:remote-resources:get', 'maker:remote-resources:list'].includes(channel)) return value;+ if (!lookup || !['local-db:sessions:get', 'local-db:sessions:get-many', 'local-db:sessions:list', 'maker:list-active', 'local-db:sessions:interrupted-pending', 'local-db:bots:get', 'local-db:bots:list', 'maker:remote-resources:get', 'maker:remote-resources:list'].includes(channel)) return value;const activeLookup = lookup;const activeBatchLookup = batchLookup;const identity = (item: unknown) => {diff --git a/apps/desktop/src/main/device-link/remoteInvokeTiming.ts b/apps/desktop/src/main/device-link/remoteInvokeTiming.tsnew file mode 100644index 0000000000..19646c4a9f--- /dev/null+++ b/apps/desktop/src/main/device-link/remoteInvokeTiming.ts@@ -0,0 +1,15 @@+/** Per-invocation monotonic stage timings; no payload, SQL, or identity data. */+export class RemoteInvokeTiming {+ readonly stages: Partial<Record<'authorizeBefore' | 'handler' | 'authorizeAfter' | 'persist' | 'project', number>> = {};++ constructor(private readonly now: () => number = () => performance.now()) {}++ async measure<T>(stage: keyof RemoteInvokeTiming['stages'], work: () => T | Promise<T>): Promise<T> {+ const started = this.now();+ try {+ return await work();+ } finally {+ this.stages[stage] = Math.round(Math.max(0, this.now() - started));+ }+ }+}diff --git a/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.tsindex 68a4dafdf7..73482d9305 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionListMessageCount.test.ts@@ -204,7 +204,7 @@ describeWithDb('sessions:list messageCount', () => {describe('sessions:list messageCount source', () => {it('keeps the production query pinned to the covering-index column', () => {- const source = readFileSync(path.join(__dirname, '..', 'ipc', 'sessions.ts'), 'utf-8');+ const source = readFileSync(path.join(__dirname, '..', 'sessionQueries.ts'), 'utf-8');// list / get / update 都走同一条标量子查询,不再 LEFT JOIN 该会话全部消息。expect(source).toMatch(/messageCount: SESSION_MESSAGE_COUNT_SQL,/);@@ -218,7 +218,7 @@ describe('sessions:list messageCount source', () => {/WHEN \$\{sessions\.listMessageCount\} IS NOT NULL THEN \$\{sessions\.listMessageCount\}/,);expect(source).toMatch(- /SELECT count\(\*\) FROM messages m WHERE m\.session_id = \$\{sessions\.id\}/,+ /SELECT count\(\*\) FROM messages m WHERE m\.session_id = \$\{OUTER_SESSION_ID_SQL\}/,);expect(source).toMatch(/ORDER BY m\.created_at DESC, m\.rowid DESC LIMIT 1/);diff --git a/apps/desktop/src/main/localDb/client/DbTransport.ts b/apps/desktop/src/main/localDb/client/DbTransport.tsindex c65a5d25c4..ad23f9c962 100644--- a/apps/desktop/src/main/localDb/client/DbTransport.ts+++ b/apps/desktop/src/main/localDb/client/DbTransport.ts@@ -46,9 +46,12 @@ export interface RpcRequest {args?: unknown;}-export type RpcResponse =+/** Epoch-aligned monotonic timestamps; never includes SQL or parameters. */+export interface RpcTiming { startedAt: number; finishedAt: number }++export type RpcResponse = (| { id: number; ok: true; result: unknown }- | { id: number; ok: false; error: { code: string; message: string; stack?: string } };+ | { id: number; ok: false; error: { code: string; message: string; stack?: string } }) & { timing?: RpcTiming };export type WorkerEvent ={ event: 'log'; payload: LogEvent } | { event: 'vec-status'; payload: VecStatusEvent };@@ -56,7 +59,7 @@ export type WorkerEvent =export type WorkerMessage = RpcResponse | WorkerEvent;export type LogEvent = {- level: 'info' | 'warn' | 'error';+ level: 'debug' | 'info' | 'warn' | 'error';scope: string;payload: unknown;};diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex e0dd0c0af9..7587b9e862 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -2492,16 +2492,21 @@ async function dispatch(op, args) {setDatabase(workerData || {});parentPort.on('message', async (req) => {+ const startedAt = performance.timeOrigin + performance.now();+ const timing = () => ({ startedAt, finishedAt: performance.timeOrigin + performance.now() });try {const result = await dispatch(req.op, req.args);- parentPort.postMessage({ id: req.id, ok: true, result });+ parentPort.postMessage({ id: req.id, ok: true, result, timing: timing() });} catch (err) {- parentPort.postMessage({ id: req.id, ok: false, error: rpcError(err) });+ parentPort.postMessage({ id: req.id, ok: false, error: rpcError(err), timing: timing() });}});`;interface PendingRpc {+ op: string;+ enqueuedAt: number;+ dispatchedAt: number;resolve: (value: unknown) => void;reject: (err: Error) => void;timeout: ReturnType<typeof setTimeout>;@@ -2511,6 +2516,7 @@ interface PendingRpc {}interface QueuedRpc {+ enqueuedAt: number;req: RpcRequest;transferList: unknown[];resolve: (value: unknown) => void;@@ -2613,6 +2619,7 @@ export class WorkerThreadTransport implements DbTransport {const background = isBackgroundDbRpc();return new Promise<R>((resolve, reject) => {const queued: QueuedRpc = {+ enqueuedAt: performance.timeOrigin + performance.now(),req,transferList: transferList ?? [],resolve: resolve as (value: unknown) => void,@@ -2798,6 +2805,9 @@ export class WorkerThreadTransport implements DbTransport {const remainingBudgetMs = Math.max(1, this.rpcTimeoutMs - budgetElapsedMs);const timeout = setTimeout(onTimeout, remainingBudgetMs);this.pending.set(id, {+ op,+ enqueuedAt: item.enqueuedAt,+ dispatchedAt: performance.timeOrigin + performance.now(),resolve: item.resolve,reject: item.reject,timeout,@@ -2898,6 +2908,29 @@ export class WorkerThreadTransport implements DbTransport {if (!pending) return;this.pending.delete(msg.id);clearTimeout(pending.timeout);+ const receivedAt = performance.timeOrigin + performance.now();+ const totalMs = receivedAt - pending.enqueuedAt;+ if (totalMs >= 250) {+ // Local debug only: operation class and durations, never query/args/results.+ // Delivery includes result transfer and main event-loop scheduling; execution+ // includes a whole worker operation (possibly a transaction), not only SQL.+ const ms = (value: number) => Math.round(Math.max(0, value));+ try {+ this.emitClientLog('debug', {+ event: 'rpc.slow', id: msg.id, totalMs: ms(totalMs),+ op: ['rawAll', 'rawGet', 'query', 'queryOne', 'run', 'exec', 'tx', 'closeDb', 'worktreeReferences'].includes(pending.op) ? pending.op : 'other',+ queueMs: ms(pending.dispatchedAt - pending.enqueuedAt),+ ...(msg.timing ? {+ workerWaitMs: ms(msg.timing.startedAt - pending.dispatchedAt),+ workerExecutionMs: ms(msg.timing.finishedAt - msg.timing.startedAt),+ deliveryMs: ms(receivedAt - msg.timing.finishedAt),+ } : {}),+ inFlight: this.pending.size, queued: this.queued.length, ok: msg.ok,+ });+ } catch {+ // Debug sinks must not prevent settling the RPC or draining the queue.+ }+ }if (msg.ok) {pending.resolve(msg.result);} else {diff --git a/apps/desktop/src/main/localDb/client/__tests__/rpcTiming.test.ts b/apps/desktop/src/main/localDb/client/__tests__/rpcTiming.test.tsnew file mode 100644index 0000000000..d965be4402--- /dev/null+++ b/apps/desktop/src/main/localDb/client/__tests__/rpcTiming.test.ts@@ -0,0 +1,46 @@+import type { EventEmitter } from 'node:events';+import { afterEach, expect, it, vi } from 'vitest';+import type { LogEvent, RpcRequest } from '../DbTransport';+const h = vi.hoisted(() => ({ worker: null as (EventEmitter & { sent: RpcRequest[] }) | null }));+vi.mock('node:worker_threads', async () => {+ const { EventEmitter } = await import('node:events');+ return { Worker: class extends EventEmitter {+ sent: RpcRequest[] = [];+ constructor() { super(); h.worker = this; }+ postMessage(req: RpcRequest) { this.sent.push(req); }+ async terminate() { return 0; }+ } };+});+import { WorkerThreadTransport } from '../WorkerThreadTransport';+afterEach(() => vi.restoreAllMocks());+it('separates transport queue, worker wait, execution and main delivery without logging private arguments', async () => {+ let now = 0;+ vi.spyOn(performance, 'now').mockImplementation(() => now);+ const transport = new WorkerThreadTransport({ useInlineWorker: true, maxInFlightRpcs: 1 });+ const logs: LogEvent[] = [];+ transport.on('log', (event) => logs.push(event));+ const first = transport.send('rawAll', { sql: 'SECRET_SQL', params: ['SECRET_PARAMETER'] });+ const second = transport.send('rawAll', { sql: 'SECRET_SQL' });+ const epoch = performance.timeOrigin;+ now = 400;+ h.worker!.emit('message', { id: 1, ok: true, result: [], timing: { startedAt: epoch + 100, finishedAt: epoch + 300 } });+ await first;+ expect(h.worker!.sent).toHaveLength(2);+ now = 600;+ h.worker!.emit('message', { id: 2, ok: false, error: { code: 'TEST', message: 'SECRET_ERROR' },+ timing: { startedAt: epoch + 450, finishedAt: epoch + 550 } });+ await expect(second).rejects.toThrow('SECRET_ERROR');+ expect(logs.map((e) => e.payload)).toEqual([+ expect.objectContaining({ totalMs: 400, queueMs: 0, workerWaitMs: 100, workerExecutionMs: 200, deliveryMs: 100 }),+ expect.objectContaining({ totalMs: 600, queueMs: 400, workerWaitMs: 50, workerExecutionMs: 100, deliveryMs: 50, ok: false }),+ ]);+ expect(JSON.stringify(logs)).not.toContain('SECRET');+ transport.on('log', () => { throw new Error('broken debug sink'); });+ const third = transport.send('rawAll', {});+ now = 900;+ expect(() => h.worker!.emit('message', { id: 3, ok: true, result: [] })).not.toThrow();+ await expect(third).resolves.toEqual([]);+ const closing = transport.close();+ h.worker!.emit('message', { id: 4, ok: true, result: undefined });+ await closing;+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.tsnew file mode 100644index 0000000000..58a4595adc--- /dev/null+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botRemoteSessionAccess.test.ts@@ -0,0 +1,46 @@+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+const h = vi.hoisted(() => ({ db: null as ReturnType<typeof drizzle> | null, current: true }));+vi.mock('../../client/current.js', () => ({ getDbClient: () => ({ drizzle: h.db }) }));+vi.mock('../../../device-link/broadcast-tap.js', () => ({+ captureDataOwnerBroadcastScope: () => 'owner', isDataOwnerBroadcastScopeCurrent: () => h.current,+}));+import { readRemoteBotSessionAccessBatch, readRemoteBotSessionAccess } from '../botRemoteSessionAccess';+let db: Database.Database;+beforeEach(() => {+ h.current = true;+ db = new Database(':memory:');+ db.exec(`CREATE TABLE sessions(id TEXT PRIMARY KEY, source TEXT);+ CREATE TABLE bot_session_links(session_id TEXT PRIMARY KEY, bot_id TEXT);+ CREATE TABLE bot_profiles(id TEXT PRIMARY KEY, hidden_at INTEGER, status TEXT);+ INSERT INTO sessions VALUES ('ordinary','desktop'),('visible','bot'),('hidden','bot'),('archived','bot'),('orphan','bot');+ INSERT INTO bot_profiles VALUES ('v',NULL,'active'),('h',1,'active'),('a',NULL,'archived');+ INSERT INTO bot_session_links VALUES ('visible','v'),('hidden','h'),('archived','a');`);+ h.db = drizzle(db);+});+afterEach(() => db.close());+describe('batch DB visibility', () => {+ it('matches single-read visibility and includes explicit missing verdicts', async () => {+ const select = vi.spyOn(h.db!, 'select');+ const ids = ['ordinary','visible','hidden','archived','orphan','missing','visible'];+ const result = await readRemoteBotSessionAccessBatch(ids, 'session');+ expect(Object.fromEntries(result)).toEqual({ ordinary: 'ordinary', visible: 'visible', hidden: 'hidden',+ archived: 'hidden', orphan: 'hidden', missing: 'missing' });+ expect(select).toHaveBeenCalledTimes(1);+ for (const id of ids) expect(await readRemoteBotSessionAccess(id)).toBe(result.get(id));+ expect(Object.fromEntries(await readRemoteBotSessionAccessBatch(['v','h','a','no'], 'bot')))+ .toEqual({ v:'visible', h:'hidden', a:'hidden', no:'missing' });+ });+ it('bounds queries and denies the entire result when ownership changes', async () => {+ const select = vi.spyOn(h.db!, 'select');+ const ids = Array.from({ length: 600 }, (_, i) => `missing${i}`);+ expect((await readRemoteBotSessionAccessBatch(ids, 'session')).size).toBe(600);+ expect(select).toHaveBeenCalledTimes(3);+ select.mockClear();+ h.current = false;+ const result = await readRemoteBotSessionAccessBatch(['ordinary', ...ids], 'session');+ expect([...result.values()].every((value) => value === 'hidden')).toBe(true);+ expect(select).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.tsindex 4f84362d55..a3889ca464 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts@@ -63,6 +63,10 @@ vi.mock('../../../worktree/recycleEvents', () => ({ notifyWorktreeRecycleOpportuimport { registerSessionIpc } from '../sessions';import { setSessionRouteLockImplementation } from '../../sessionRouteLock';+import { getDbClient } from '../../client/current';+import { selectSessionsByIds, selectSessionWithCount, selectSessionListRows, flattenSessionReadRow } from '../../sessionQueries';+import { createDrizzleProxy } from '../../client/drizzleProxy';+import type { DbTransport } from '../../client/DbTransport';type ExpectedIdentity = {workingDir: string | null;@@ -304,3 +308,82 @@ describe('local-db:sessions:restore-if-archived', () => {expect(h.tapWindowBroadcast).not.toHaveBeenCalled();});});++describe('bounded reconciliation read', () => {+ it.each(['native', 'worker-proxy'])('correlates uncached projections to the outer session through %s', async (mode) => {+ h.sqlite!.exec(`+ CREATE INDEX idx_messages_session_created ON messages(session_id, created_at);+ INSERT INTO sessions (id, created_at, updated_at) VALUES ('other', 1, 1), ('empty', 1, 1);+ UPDATE sessions SET cleared_at = 2 WHERE id = 'target';+ INSERT INTO messages (id, client_id, session_id, role, content, agent_meta, created_at, rewind_at) VALUES+ ('old', 'old', 'target', 'user', '{"text":"cleared"}', NULL, 1, NULL),+ ('user', 'user', 'target', 'user', '{"text":"question"}', NULL, 3, NULL),+ ('answer', 'answer', 'target', 'assistant', '"answer"', NULL, 4, NULL),+ ('resume', 'resume', 'target', 'user', '{"text":"continue"}', '{"autoResume":true}', 5, NULL),+ ('rewound', 'rewound', 'target', 'assistant', '"rewound"', NULL, 6, 7),+ ('other', 'other', 'other', 'assistant', '"another session"', NULL, 8, NULL);+ `);+ const plans: string[] = [];+ const transport = {+ async send(_op: string, args: { sql: string; params: unknown[] }) {+ plans.push(...(h.sqlite!.prepare(`EXPLAIN QUERY PLAN ${args.sql}`).all(...args.params) as { detail: string }[])+ .map((row) => row.detail));+ return h.sqlite!.prepare(args.sql).raw().all(...args.params);+ },+ } as unknown as DbTransport;+ const db = mode === 'native' ? getDbClient().drizzle : createDrizzleProxy(transport);+ const single = await selectSessionWithCount(db, 'target');+ expect(single).toMatchObject({ messageCount: 5, latestMessageExtract: 'answer', latestMessageRole: 'assistant' });+ const batch = await selectSessionsByIds(db, ['target', 'empty']);+ expect(batch[0]).toEqual(single);+ expect(batch[1]).toMatchObject({ messageCount: 0, latestMessageExtract: null, latestMessageRole: null });+ const list = (await selectSessionListRows(db, undefined, 20)).map(flattenSessionReadRow);+ expect(list.find((row) => row.id === 'target')).toEqual(single);+ if (mode === 'worker-proxy') {+ expect(plans.some((plan) => /SEARCH m USING (?:COVERING )?INDEX idx_messages_session_created/.test(plan))).toBe(true);+ expect(plans.some((plan) => /SCAN m\b/.test(plan))).toBe(false);+ }+ h.sqlite!.prepare("UPDATE sessions SET cleared_at = 10 WHERE id = 'target'").run();+ expect(await selectSessionWithCount(db, 'target')).toMatchObject({ messageCount: 5, latestMessageExtract: null, latestMessageRole: null });+ });++ it('shares exact database projection across single, batch and list reads without retaining stale results', async () => {+ const db = getDbClient().drizzle;+ const select = vi.spyOn(db, 'select');+ const batch = await selectSessionsByIds(db, ['target', 'missing', 'target']);+ expect(select).toHaveBeenCalledTimes(1);+ expect(batch).toHaveLength(1);+ expect(await selectSessionWithCount(db, 'target')).toEqual(batch[0]);+ expect((await selectSessionListRows(db, undefined, 20)).map(flattenSessionReadRow)).toEqual(batch);+ h.sqlite!.prepare("UPDATE sessions SET title = 'fresh title' WHERE id = 'target'").run();+ expect((await selectSessionsByIds(db, ['target']))[0].title).toBe('fresh title');+ select.mockRestore();+ });++ it('does not query for empty input and bounds larger internal reads', async () => {+ const db = getDbClient().drizzle;+ const select = vi.spyOn(db, 'select');+ expect(await selectSessionsByIds(db, [])).toEqual([]);+ expect(select).not.toHaveBeenCalled();+ expect(await selectSessionsByIds(db, Array.from({ length: 600 }, (_, i) => `missing-${i}`))).toEqual([]);+ expect(select).toHaveBeenCalledTimes(3);+ select.mockRestore();+ });++ it('returns the same projection as GET, deduplicates ids and omits missing rows', async () => {+ const { runDeviceLinkInvokeContext } = await import('../../../device-link/invoke-context.js');+ const get = h.handlers.get('local-db:sessions:get')!;+ const batch = h.handlers.get('local-db:sessions:get-many')!;+ const expected = await get({}, 'target');+ const result = await runDeviceLinkInvokeContext({ controllerDeviceId: 'phone', channel: 'local-db:sessions:get-many' },+ () => batch({}, ['target', 'missing', 'target']));+ expect(result).toEqual([expected]);+ });+ it('rejects untrusted local callers and oversized remote batches before querying', async () => {+ const { runDeviceLinkInvokeContext } = await import('../../../device-link/invoke-context.js');+ const batch = h.handlers.get('local-db:sessions:get-many')!;+ await expect(batch({}, ['target'])).rejects.toThrow();+ await expect(runDeviceLinkInvokeContext({ controllerDeviceId: 'phone', channel: 'local-db:sessions:get-many' },+ () => batch({}, Array.from({ length: 33 }, () => 'target')))).rejects.toThrow('INVALID_PARAMS');+ });+});diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 258ddfd9c2..9f94e83524 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -27,10 +27,9 @@ import { getDbClient } from '../client/current';import * as currentDb from '../client/current';import type { DbClient } from '../client/DbClient';import { sessions, messages } from '../schema';+import { selectSessionListRows, selectSessionWithCount, selectSessionsByIds, flattenSessionReadRow, projectSessionReadResult, type SessionListRow } from '../sessionQueries';import { commitBotProfileDeletion } from '../botProfileDeletionStore.js';import {- LIST_PREVIEW_EXTRACT_SQL,- LATEST_VISIBLE_PREVIEW_FILTER_SQL,persistSessionListProjectionBatch,type SessionListProjectionBackfillItem,} from '../sessionListProjection';@@ -51,7 +50,6 @@ import {persistableSessionEffort,normalizeRemoteHostId,finalizePlainPreview,- type SessionRowWithCount,} from '../mapper';import { ensureDialogueWorkspaceDir } from '../dialogueWorkspace';import { recomputePrRefsForSession } from '../../git-context/prRefsStore';@@ -82,6 +80,8 @@ import {setOnSessionTurnEndedPersisted,} from '../sessionActiveTurn';import { dismissErrorMessage, rebroadcastAgentSwitchBoundary } from './messages';+import { SESSION_READ_BATCH_LIMIT } from '../../../shared/sessionRead';+import { isDeviceLinkInvoke } from '../../device-link/invoke-context.js';import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';import { removeTurnChangeSetsForSession } from '../../turn-change-set/store.js';import { quiesceSessionBeforeWorktreeRecycle } from './sessionRemovalOperations.js';@@ -731,64 +731,6 @@ export async function persistSessionFields(const MAX_LIMIT = 1000;-/**- * list / get / update 共用的 messageCount:标量子查询。口径是该会话的全部 messages 行数,- * 不过滤 role / rewind_at / cleared_at(口径要动就得连手机端卡片上的「N 条消息」一起想,- * 见 maker-shared/sessionList 的 messageCountLabel)。- *- * 标量子查询没有 LEFT JOIN 补的那一行空行,无匹配时聚合返回 0,所以这里用 `count(*)` 是- * 安全的。仍然只扫 idx_messages_session_created(session_id 是首列),不回表。- *- * 旧的一段式 LEFT JOIN + GROUP BY 不能图快改用 `count(*)`:LEFT JOIN 会给空会话补一行,- * 数出 1 而非 0,打歪 sidebar 的「单空 New Maker 草稿」判定。list 已改成两段式;get/update- * 也走同一条标量子查询,避免切任务时把几万行 join 进单行快照。- *- * 由 sessionListMessageCount 回归测试守护。- *- * list_message_count 已回填时走缓存列,跳过 messages 扫描。未回填时 count(*) 精确总数- * (侧栏文案仍用 messageCountLabel 把 ≥1001 显示成 1000+;wire `_count.messages` 保持精确)。- * 非 NULL 即信任:绕过 createMessage 的 messages 增删必须同步投影。- * import / treeRehydrate 置空三列;turn/review 租约、context.rebuild、createMessage 只置空计数。- */-const SESSION_MESSAGE_COUNT_SQL = sql<number>`(- CASE- WHEN ${sessions.listMessageCount} IS NOT NULL THEN ${sessions.listMessageCount}- ELSE (- SELECT count(*) FROM messages m WHERE m.session_id = ${sessions.id}- )- END-)`.as('message_count');--/**- * sidebar-card-mode:最近一条可见 user/assistant 的预览抽出 / role。- * list_preview 已回填时 CASE 短路,不碰 messages。否则 SQL 侧 json_extract 纯文本,- * 不把整段 content 跨 worker RPC。autoResume 只检查 user 行的 agent_meta。- */-const LATEST_MSG_EXTRACT_SQL = sql<string | null>`(- CASE- WHEN ${sessions.listPreview} IS NOT NULL THEN NULL- ELSE (- SELECT ${sql.raw(LIST_PREVIEW_EXTRACT_SQL)} FROM messages m- WHERE m.session_id = ${sessions.id}- AND ${sql.raw(LATEST_VISIBLE_PREVIEW_FILTER_SQL)}- AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})- ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1- )- END-)`.as('latest_message_extract');-const LATEST_MSG_ROLE_SQL = sql<string | null>`(- CASE- WHEN ${sessions.listPreviewRole} IS NOT NULL THEN ${sessions.listPreviewRole}- ELSE (- SELECT m.role FROM messages m- WHERE m.session_id = ${sessions.id}- AND ${sql.raw(LATEST_VISIBLE_PREVIEW_FILTER_SQL)}- AND (${sessions.clearedAt} IS NULL OR m.created_at > ${sessions.clearedAt})- ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1- )- END-)`.as('latest_message_role');-/*** 按 session id 查 desktop 端 sessions 表的产品快照。* 与 maker-core SessionMeta 不重叠 —— SessionMeta 故意不带 status (那是 desktop 产品语义)。@@ -1260,19 +1202,7 @@ export function registerSessionIpc(}scheduleSessionListProjectionBackfill(mergedRows);- return mergedRows.map((r) =>- sessionToCamel(- projectSessionContextWindow(- {- ...r.session,- messageCount: r.messageCount,- latestMessageExtract: r.latestMessageExtract,- latestMessageRole: r.latestMessageRole,- },- opts.resolveContextWindow,- ),- ),- );+ return mergedRows.map((row) => projectSessionReadResult(flattenSessionReadRow(row), opts.resolveContextWindow));};const loadUsageHistoryRows = async () => {// 用量历史的“最耗任务”必须覆盖整个会话表,再由 renderer 按所选日历范围@@ -1557,12 +1487,25 @@ export function registerSessionIpc(return { ok: true };});+ // Bounded reconciliation read: same metadata/count/preview as GET, one DB RPC.+ // Omitted rows mean missing or remotely hidden; the tunnel filters visibility.+ ipcMain.handle('local-db:sessions:get-many', async (event, value: unknown) => {+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);+ if (!Array.isArray(value) || value.length > SESSION_READ_BATCH_LIMIT) {+ throwIpcError('INVALID_PARAMS', `sessionIds must be an array of at most ${SESSION_READ_BATCH_LIMIT} ids`);+ }+ const ids = [...new Set(value.map((id) => requireString(id, 'sessionId')))];+ if (!ids.length) return [];+ const rows = await selectSessionsByIds(getDbClient().drizzle, ids);+ return rows.map((row) => projectSessionReadResult(row, opts.resolveContextWindow));+ });+ipcMain.handle('local-db:sessions:get', async (_e, id: unknown) => {const sid = requireString(id, 'id');const db = getDbClient().drizzle;const row = await selectSessionWithCount(db, sid);if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');- return sessionToCamel(projectSessionContextWindow(row, opts.resolveContextWindow));+ return projectSessionReadResult(row, opts.resolveContextWindow);});/**@@ -2685,14 +2628,6 @@ async function drainSessionListProjectionBackfill(): Promise<void> {}}-/** {@link selectSessionListRows} 的行形状——与 sessionToCamel 的入参对齐。 */-interface SessionListRow {- session: typeof sessions.$inferSelect;- messageCount: number;- latestMessageExtract: string | null;- latestMessageRole: string | null;-}-/** 用量历史专用行查询:全量读取 sessions,但跳过 sidebar 的消息预览子查询。 */function selectSessionUsageRows(db: DbClient['drizzle'],@@ -2735,79 +2670,6 @@ function selectSessionUsageRows(.then((rows) => rows);}-/**- * sessions:list 的行查询——**两段式**:CTE 先按排序取够 `cap` 个 id,主查询只对这批行算- * messageCount 与 preview。- *- * 为什么不能沿用一段式的 `LEFT JOIN messages + GROUP BY`:那个形状下 `LIMIT` 在 GROUP BY- * **之后**才生效,于是每个候选会话的全部消息都要参与聚合,成本与"最终只要 1000 行"无关。- * 4.7GB / 111 万条消息的真实库上,把聚合面从 1743 个会话收窄到 1000 个,热缓存 104ms →- * 54ms。会话越多、limit 占比越小,收益越大。- *- * 用单条 CTE 而不是"先查 id 再 IN (...)"两次往返,有两个理由:- * 1. 一致性——两次查询之间会话可能被删/改状态,第二段就会比第一段少行,列表凭空少一条。- * CTE 是单条语句、单一致性快照。- * 2. 参数——`IN (...)` 要绑 cap 个参数(当前 MAX_LIMIT=1000),CTE 只绑一个 limit。- *- * messageCount 在这里是**标量子查询**里的 `count(*)`:无匹配行时聚合返回 0,不存在 LEFT JOIN- * 那个"空会话数出 1"的坑。它同样只扫 idx_messages_session_created,不回表。- *- * @param where 行过滤条件,同时作用于 CTE 与主查询(CTE 决定取哪些、主查询决定算哪些)。- * @param cap 取前 N 行;`null` = 不限(置顶补齐分支用,pinned 行数天然很少)。- */-function selectSessionListRows(- db: DbClient['drizzle'],- where: SQL | undefined,- cap: number | null,-): Promise<SessionListRow[]> {- const pickedBase = db.select({ id: sessions.id }).from(sessions).where(where);- const picked = db- .$with('picked')- .as(- cap === null- ? pickedBase.orderBy(desc(sessions.updatedAt))- : pickedBase.orderBy(desc(sessions.updatedAt)).limit(cap),- );- return db- .with(picked)- .select({- session: sessions,- messageCount: SESSION_MESSAGE_COUNT_SQL,- latestMessageExtract: LATEST_MSG_EXTRACT_SQL,- latestMessageRole: LATEST_MSG_ROLE_SQL,- })- .from(sessions)- .innerJoin(picked, eq(picked.id, sessions.id))- .where(where)- .orderBy(desc(sessions.updatedAt));-}--/** 单行 SELECT + 标量 count / preview:与 list 同口径,不 JOIN 该会话全部消息。- * preview 子查询同步带出——get/update 路径返回的 Session 会整体替换 store 里的行,- * 缺字段会把列表查询带回的 preview 冲掉。 */-async function selectSessionWithCount(- db: DbClient['drizzle'],- id: string,-): Promise<SessionRowWithCount | undefined> {- const [r] = await db- .select({- session: sessions,- messageCount: SESSION_MESSAGE_COUNT_SQL,- latestMessageExtract: LATEST_MSG_EXTRACT_SQL,- latestMessageRole: LATEST_MSG_ROLE_SQL,- })- .from(sessions)- .where(eq(sessions.id, id))- .limit(1);- if (!r) return undefined;- return {- ...r.session,- messageCount: r.messageCount,- latestMessageExtract: r.latestMessageExtract,- latestMessageRole: r.latestMessageRole,- };-}-function clampLimit(raw: unknown, fallback: number): number {const n = typeof raw === 'number' ? raw : Number(raw);if (!Number.isFinite(n) || n <= 0) return fallback;diff --git a/apps/desktop/src/main/localDb/sessionQueries.ts b/apps/desktop/src/main/localDb/sessionQueries.tsnew file mode 100644index 0000000000..b40b89d2ac--- /dev/null+++ b/apps/desktop/src/main/localDb/sessionQueries.ts@@ -0,0 +1,159 @@+/** Shared database reads for local IPC, remote IPC and internal callers. */+import { desc, eq, inArray, sql, type SQL } from 'drizzle-orm';+import type { DbClient } from './client/DbClient';+import { sessions } from './schema';+import { LIST_PREVIEW_EXTRACT_SQL, LATEST_VISIBLE_PREVIEW_FILTER_SQL } from './sessionListProjection';+import { sessionToCamel, type SessionRowWithCount } from './mapper';+import { projectSessionContextWindow, type ContextWindowSession } from '../../shared/sessionContextWindow';++// Drizzle strips table names from Column chunks in single-table SELECT projections,+// including nested SQL. An unqualified "id" inside the messages subquery resolves+// to messages.id, not the outer session: wrong results and a full messages scan.+// Identifier fragments retain the outer scope in both single-table and joined reads.+const OUTER_SESSION_ID_SQL = sql`${sql.identifier('sessions')}.${sql.identifier('id')}`;+const OUTER_SESSION_CLEARED_AT_SQL = sql`${sql.identifier('sessions')}.${sql.identifier('cleared_at')}`;++/**+ * list / get / update 共用的 messageCount:标量子查询。口径是该会话的全部 messages 行数,+ * 不过滤 role / rewind_at / cleared_at(口径要动就得连手机端卡片上的「N 条消息」一起想,+ * 见 maker-shared/sessionList 的 messageCountLabel)。+ *+ * 标量子查询没有 LEFT JOIN 补的那一行空行,无匹配时聚合返回 0,所以这里用 `count(*)` 是+ * 安全的。仍然只扫 idx_messages_session_created(session_id 是首列),不回表。+ *+ * 旧的一段式 LEFT JOIN + GROUP BY 不能图快改用 `count(*)`:LEFT JOIN 会给空会话补一行,+ * 数出 1 而非 0,打歪 sidebar 的「单空 New Maker 草稿」判定。list 已改成两段式;get/update+ * 也走同一条标量子查询,避免切任务时把几万行 join 进单行快照。+ *+ * 由 sessionListMessageCount 回归测试守护。+ *+ * list_message_count 已回填时走缓存列,跳过 messages 扫描。未回填时 count(*) 精确总数+ * (侧栏文案仍用 messageCountLabel 把 ≥1001 显示成 1000+;wire `_count.messages` 保持精确)。+ * 非 NULL 即信任:绕过 createMessage 的 messages 增删必须同步投影。+ * import / treeRehydrate 置空三列;turn/review 租约、context.rebuild、createMessage 只置空计数。+ */+const SESSION_MESSAGE_COUNT_SQL = sql<number>`(+ CASE+ WHEN ${sessions.listMessageCount} IS NOT NULL THEN ${sessions.listMessageCount}+ ELSE (+ SELECT count(*) FROM messages m WHERE m.session_id = ${OUTER_SESSION_ID_SQL}+ )+ END+)`.as('message_count');++/**+ * sidebar-card-mode:最近一条可见 user/assistant 的预览抽出 / role。+ * list_preview 已回填时 CASE 短路,不碰 messages。否则 SQL 侧 json_extract 纯文本,+ * 不把整段 content 跨 worker RPC。autoResume 只检查 user 行的 agent_meta。+ */+const LATEST_MSG_EXTRACT_SQL = sql<string | null>`(+ CASE+ WHEN ${sessions.listPreview} IS NOT NULL THEN NULL+ ELSE (+ SELECT ${sql.raw(LIST_PREVIEW_EXTRACT_SQL)} FROM messages m+ WHERE m.session_id = ${OUTER_SESSION_ID_SQL}+ AND ${sql.raw(LATEST_VISIBLE_PREVIEW_FILTER_SQL)}+ AND (${OUTER_SESSION_CLEARED_AT_SQL} IS NULL OR m.created_at > ${OUTER_SESSION_CLEARED_AT_SQL})+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1+ )+ END+)`.as('latest_message_extract');+const LATEST_MSG_ROLE_SQL = sql<string | null>`(+ CASE+ WHEN ${sessions.listPreviewRole} IS NOT NULL THEN ${sessions.listPreviewRole}+ ELSE (+ SELECT m.role FROM messages m+ WHERE m.session_id = ${OUTER_SESSION_ID_SQL}+ AND ${sql.raw(LATEST_VISIBLE_PREVIEW_FILTER_SQL)}+ AND (${OUTER_SESSION_CLEARED_AT_SQL} IS NULL OR m.created_at > ${OUTER_SESSION_CLEARED_AT_SQL})+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT 1+ )+ END+)`.as('latest_message_role');++/** {@link selectSessionListRows} 的行形状——与 sessionToCamel 的入参对齐。 */+export interface SessionListRow {+ session: typeof sessions.$inferSelect;+ messageCount: number;+ latestMessageExtract: string | null;+ latestMessageRole: string | null;+}++function sessionReadSelection() {+ return {+ session: sessions,+ messageCount: SESSION_MESSAGE_COUNT_SQL,+ latestMessageExtract: LATEST_MSG_EXTRACT_SQL,+ latestMessageRole: LATEST_MSG_ROLE_SQL,+ };+}++export function flattenSessionReadRow(row: SessionListRow): SessionRowWithCount {+ return { ...row.session, messageCount: row.messageCount,+ latestMessageExtract: row.latestMessageExtract, latestMessageRole: row.latestMessageRole };+}++export function projectSessionReadResult(+ row: SessionRowWithCount,+ resolve?: (session: ContextWindowSession) => number | null,+) {+ return sessionToCamel(projectSessionContextWindow(row, resolve));+}++/** No settled cache: every read observes the database and uses the same projection. */+export async function selectSessionsByIds(db: DbClient['drizzle'], ids: readonly string[]): Promise<SessionRowWithCount[]> {+ const unique = [...new Set(ids)];+ const result = new Map<string, SessionRowWithCount>();+ for (let offset = 0; offset < unique.length; offset += 256) {+ const rows = await db.select(sessionReadSelection()).from(sessions)+ .where(inArray(sessions.id, unique.slice(offset, offset + 256)));+ for (const row of rows) result.set(row.session.id, flattenSessionReadRow(row));+ }+ return unique.flatMap((id) => { const row = result.get(id); return row ? [row] : []; });+}++export async function selectSessionWithCount(db: DbClient['drizzle'], id: string): Promise<SessionRowWithCount | undefined> {+ return (await selectSessionsByIds(db, [id]))[0];+}++/**+ * sessions:list 的行查询——**两段式**:CTE 先按排序取够 `cap` 个 id,主查询只对这批行算+ * messageCount 与 preview。+ *+ * 为什么不能沿用一段式的 `LEFT JOIN messages + GROUP BY`:那个形状下 `LIMIT` 在 GROUP BY+ * **之后**才生效,于是每个候选会话的全部消息都要参与聚合,成本与"最终只要 1000 行"无关。+ * 4.7GB / 111 万条消息的真实库上,把聚合面从 1743 个会话收窄到 1000 个,热缓存 104ms →+ * 54ms。会话越多、limit 占比越小,收益越大。+ *+ * 用单条 CTE 而不是"先查 id 再 IN (...)"两次往返,有两个理由:+ * 1. 一致性——两次查询之间会话可能被删/改状态,第二段就会比第一段少行,列表凭空少一条。+ * CTE 是单条语句、单一致性快照。+ * 2. 参数——`IN (...)` 要绑 cap 个参数(当前 MAX_LIMIT=1000),CTE 只绑一个 limit。+ *+ * messageCount 在这里是**标量子查询**里的 `count(*)`:无匹配行时聚合返回 0,不存在 LEFT JOIN+ * 那个"空会话数出 1"的坑。它同样只扫 idx_messages_session_created,不回表。+ *+ * @param where 行过滤条件,同时作用于 CTE 与主查询(CTE 决定取哪些、主查询决定算哪些)。+ * @param cap 取前 N 行;`null` = 不限(置顶补齐分支用,pinned 行数天然很少)。+ */+export function selectSessionListRows(+ db: DbClient['drizzle'],+ where: SQL | undefined,+ cap: number | null,+): Promise<SessionListRow[]> {+ const pickedBase = db.select({ id: sessions.id }).from(sessions).where(where);+ const picked = db+ .$with('picked')+ .as(+ cap === null+ ? pickedBase.orderBy(desc(sessions.updatedAt))+ : pickedBase.orderBy(desc(sessions.updatedAt)).limit(cap),+ );+ return db+ .with(picked)+ .select(sessionReadSelection())+ .from(sessions)+ .innerJoin(picked, eq(picked.id, sessions.id))+ .where(where)+ .orderBy(desc(sessions.updatedAt));+}diff --git a/apps/desktop/src/main/localDb/worker/dbWorker.ts b/apps/desktop/src/main/localDb/worker/dbWorker.tsindex 3b656fefc6..f17d09f8bc 100644--- a/apps/desktop/src/main/localDb/worker/dbWorker.ts+++ b/apps/desktop/src/main/localDb/worker/dbWorker.ts@@ -29,14 +29,17 @@ let initError: { code: string; message: string; stack?: string } | null = null;setDatabase(startupOptions);activeWorkerPort.on('message', async (req: RpcRequest) => {+ const startedAt = performance.timeOrigin + performance.now();+ const timing = () => ({ startedAt, finishedAt: performance.timeOrigin + performance.now() });try {const result = await dispatchRequest(req);- activeWorkerPort.postMessage({ id: req.id, ok: true, result } satisfies RpcResponse);+ activeWorkerPort.postMessage({ id: req.id, ok: true, result, timing: timing() } satisfies RpcResponse);} catch (err) {activeWorkerPort.postMessage({id: req.id,ok: false,error: serializeWorkerError(err),+ timing: timing(),} satisfies RpcResponse);}});diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex ab1d9d2454..14cdc0cdff 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -5250,6 +5250,7 @@ contextBridge.exposeInMainWorld('electronAPI', {create: (body?: unknown): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:create', body),get: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get', id),+ getMany: (ids: string[]): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get-many', ids),resolveReferences: (sessionIds: string[]): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:resolve-references', sessionIds),restoreIfArchived: (id: string, expected: unknown): Promise<unknown> =>diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.tsindex a8c00625a4..0800967498 100644--- a/apps/desktop/src/preload/sidebarWindowPreload.ts+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts@@ -420,6 +420,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// shared makerChatStore. Do not expose the primary window's full DB API.sessions: {get: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get', id),+ getMany: (ids: string[]): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get-many', ids),list: (limit?: number, status?: string, options?: unknown): Promise<unknown> =>ipcRenderer.invoke('local-db:sessions:list', limit, status, options),resolveReferences: (sessionIds: string[]): Promise<unknown> =>diff --git a/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.tsindex 567282be45..0cf59d4de5 100644--- a/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts+++ b/apps/desktop/src/renderer/__tests__/localCatalogSnapshot.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ProviderView } from '@cindy/model-providers';+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';const mocks = vi.hoisted(() => ({beginCapabilities: vi.fn(),@@ -88,6 +89,21 @@ describe('refreshLocalCatalogSnapshot', () => {expect(mocks.warn).toHaveBeenCalledOnce();});+ it('waits for sibling reads after a failure before starting the trailing round', async () => {+ const slow = deferred<unknown[]>();+ mocks.loadProviders.mockRejectedValueOnce(new Error('failed')).mockResolvedValue({ providers: [] });+ mocks.loadCapabilities.mockReturnValueOnce(slow.promise).mockResolvedValue([]);+ const first = refreshLocalCatalogSnapshot();+ await vi.waitFor(() => expect(mocks.loadProviders).toHaveBeenCalledOnce());+ const latest = refreshLocalCatalogSnapshot();+ await Promise.resolve();+ expect(mocks.loadProviders).toHaveBeenCalledOnce();+ slow.resolve([]);+ await Promise.all([first, latest]);+ expect(mocks.loadProviders).toHaveBeenCalledTimes(2);+ expect(mocks.commitProviders).toHaveBeenCalledOnce();+ });+it('does not commit capabilities when the provider snapshot owner is stale', async () => {const providers = {dataOwnerId: 'owner-b',@@ -104,7 +120,7 @@ describe('refreshLocalCatalogSnapshot', () => {expect(mocks.commitCapabilities).not.toHaveBeenCalled();});- it('drops an older refresh that finishes after a newer generation', async () => {+ it('coalesces repeated invalidations into one trailing read and never commits the stale round', async () => {const oldProviders = deferred<unknown[]>();const oldCapabilities = deferred<unknown[]>();const newProviders = deferred<unknown[]>();@@ -117,20 +133,43 @@ describe('refreshLocalCatalogSnapshot', () => {.mockReturnValueOnce(newCapabilities.promise);const oldRefresh = refreshLocalCatalogSnapshot();+ await vi.waitFor(() => expect(mocks.loadProviders).toHaveBeenCalledTimes(1));+ const duplicates = Array.from({ length: 20 }, () => refreshLocalCatalogSnapshot());const newRefresh = refreshLocalCatalogSnapshot();+ expect(mocks.loadProviders).toHaveBeenCalledTimes(1);+ oldProviders.resolve([{ id: 'old-provider' }]);+ oldCapabilities.resolve([['codex', { availableModels: [{ id: 'old-model' }] }]]);+ await vi.waitFor(() => expect(mocks.loadProviders).toHaveBeenCalledTimes(2));+ expect(mocks.commitProviders).not.toHaveBeenCalled();newProviders.resolve([{ id: 'new-provider' }]);newCapabilities.resolve([['codex', { availableModels: [{ id: 'new-model' }] }]]);await expect(newRefresh).resolves.toBe(true);- oldProviders.resolve([{ id: 'old-provider' }]);- oldCapabilities.resolve([['codex', { availableModels: [{ id: 'old-model' }] }]]);- await expect(oldRefresh).resolves.toBe(false);+ await expect(oldRefresh).resolves.toBe(true);+ await Promise.all(duplicates);+ expect(mocks.loadCapabilities).toHaveBeenCalledTimes(2);expect(mocks.commitProviders).toHaveBeenCalledTimes(1);expect(mocks.commitProviders.mock.calls[0]?.[1]).toEqual([{ id: 'new-provider' }]);expect(mocks.commitCapabilities).toHaveBeenCalledTimes(1);});+ it('does not make a new owner wait for the old owner and drops the old queued refresh', async () => {+ const old = deferred<unknown[]>();+ mocks.loadProviders.mockReturnValueOnce(old.promise).mockResolvedValue({ providers: [] });+ mocks.loadCapabilities.mockResolvedValue([]);+ const first = refreshLocalCatalogSnapshot();+ await vi.waitFor(() => expect(mocks.loadProviders).toHaveBeenCalledOnce());+ const obsolete = refreshLocalCatalogSnapshot();+ setDataOwnerGeneration('new-owner');+ await expect(refreshLocalCatalogSnapshot()).resolves.toBe(true);+ old.resolve([]);+ await Promise.all([first, obsolete]);+ expect(mocks.loadProviders).toHaveBeenCalledTimes(2);+ expect(mocks.commitProviders).toHaveBeenCalledOnce();+ setDataOwnerGeneration(null);+ });+it('waits for visibility initialization and rechecks ownership before publishing either snapshot', async () => {const initialization = deferred<boolean>();const providers = { dataOwnerId: 'owner-a', ownerGeneration: 1, providers: [], providerOrder: [] };diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.tsindex bd0fa9090a..1643a58206 100644--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts@@ -1407,9 +1407,12 @@ describe('Shared create project picker', () => {expect(addedHead).toContain('prefetchDeviceGitSafetySettings(target.deviceId)');// ③ 「设备已不可用」类的 evict 不需要配对 —— 那几处刻意不 prefetch,别被这条规则误改。// 这里只锁「本仓存在那个正确范例」,它是这条规则的出处。- expect(deviceLinkRemoteProjectsSource).toContain('evictDeviceProviders(push.deviceId);');- expect(deviceLinkRemoteProjectsSource).toContain(- 'void prefetchDeviceProviders(push.deviceId);',+ expect(deviceLinkRemoteProjectsSource).toContain('void refreshRemoteCatalogSnapshot(push.deviceId);');+ const refreshSource = readSource('lib', 'remoteCatalogSnapshot.ts');+ expect(refreshSource).toContain('evictDeviceProviders(deviceId)');+ expect(refreshSource).toContain('prefetchDeviceProviders(deviceId)');+ expect(refreshSource.indexOf('evictDeviceProviders(deviceId)')).toBeLessThan(+ refreshSource.indexOf('prefetchDeviceProviders(deviceId)'),);});diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex 6322a943de..ac110edefb 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -35,7 +35,11 @@ const noSleep = async () => {};beforeEach(() => {invoke.mockReset();- vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });+ // Existing cases exercise compatibility with hosts predating batch reconciliation.+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: (...args: unknown[]) => {+ if (args[1] === 'local-db:sessions:get-many') return Promise.reject(new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] old host'));+ return invoke(...args);+ } } } });});afterEach(() => {@@ -1063,3 +1067,72 @@ it('does not publish unchanged schedule snapshots or swallow revocation', asyncinvoke.mockResolvedValueOnce([session('s')]).mockRejectedValueOnce(new Error('DEVICE_LINK_ACCESS_REVOKED'));expect(await refreshRemoteDeviceSessions(device, undefined, { scope: 'both' })).toBe('revoked');});++describe('batch reconciliation', () => {+ it('uses one batch for eight missing rows and retains metadata and removal semantics', async () => {+ const d = did();+ const recent = Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));+ const outside = Array.from({ length: 8 }, (_, i) => session(`outside-${i}`));+ remoteProjectsStore.setDeviceSessions(d, 'Mac', outside);+ const batchInvoke = vi.fn(async (_device: string, channel: string) => {+ if (channel === 'local-db:sessions:list') return recent;+ if (channel === 'local-db:sessions:get-many') return outside.slice(1).map((s) => ({ ...s, title: 'updated', model: 'new-model', pinnedAt: '2026-09-12T00:00:00.000Z' }));+ throw new Error('unexpected individual read');+ });+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: batchInvoke } } });+ await refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });+ expect(batchInvoke).toHaveBeenCalledTimes(2);+ expect(batchInvoke).toHaveBeenLastCalledWith(d, 'local-db:sessions:get-many', [outside.map((s) => s.id)]);+ const result = remoteProjectsStore.getDeviceSessions(d);+ expect(result.find((s) => s.id === 'outside-0')).toBeUndefined();+ expect(result.find((s) => s.id === 'outside-1')).toMatchObject({ title: 'updated', model: 'new-model', pinnedAt: '2026-09-12T00:00:00.000Z' });+ });++ it.each(['timeout', 'malformed', 'revoked'])('does not multiply a %s batch failure into GET retries or erase cached rows', async (failure) => {+ const d = did();+ const outside = session('outside');+ remoteProjectsStore.setDeviceSessions(d, 'Mac', [outside]);+ const batchInvoke = vi.fn(async (_device: string, channel: string) => {+ if (channel === 'local-db:sessions:list') return Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));+ if (failure === 'malformed') return [{ id: 'not-requested', status: 'active' }];+ throw new Error(failure === 'timeout' ? '[DEVICE_LINK_TIMEOUT] slow' : '[DEVICE_LINK_ACCESS_REVOKED] revoked');+ });+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: batchInvoke } } });+ await refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });+ expect(batchInvoke).toHaveBeenCalledTimes(2);+ expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside')).toMatchObject({ title: 'outside' });+ });++ it('keeps newer pushes when a batch response arrives late', async () => {+ const d = did();+ remoteProjectsStore.setDeviceSessions(d, 'Mac', [session('outside')]);+ const response = deferred<Session[]>();+ const started = deferred<void>();+ const batchInvoke = vi.fn(async (_device: string, channel: string) => {+ if (channel === 'local-db:sessions:list') return Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));+ started.resolve();+ return response.promise;+ });+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: batchInvoke } } });+ const pending = refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });+ await started.promise;+ remoteProjectsStore.applyPatch(d, 'outside', { title: 'newer push' });+ response.resolve([session('outside', { title: 'old response' })]);+ await pending;+ expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside')?.title).toBe('newer push');+ });+});++it('falls back to bounded GETs for oversized batches', async () => {+ const d = did();+ remoteProjectsStore.setDeviceSessions(d, 'Mac', [session('outside')]);+ const calls = vi.fn(async (_device: string, channel: string) => {+ if (channel === 'local-db:sessions:list') return Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));+ if (channel === 'local-db:sessions:get-many') throw new Error('[PRECONDITION_FAILED] REMOTE_SESSION_BATCH_TOO_LARGE');+ return session('outside', { title: 'updated' });+ });+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: calls } } });+ await refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });+ expect(calls).toHaveBeenCalledTimes(3);+ expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside')?.title).toBe('updated');+});diff --git a/apps/desktop/src/renderer/__tests__/remoteCatalogSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/remoteCatalogSnapshot.test.tsnew file mode 100644index 0000000000..fe714cbf79--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/remoteCatalogSnapshot.test.ts@@ -0,0 +1,99 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++beforeEach(() => vi.resetModules());+afterEach(() => vi.unstubAllGlobals());++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++describe('remote catalog refresh scheduling', () => {+ it('lets another peer and a new link refresh while a retired link is still waiting', async () => {+ const old = deferred();+ let hold = true;+ const invoke = vi.fn(async (device: string, channel: string) => {+ if (device === 'old' && hold) await old.promise;+ return channel === 'maker:provider:list'+ ? { providers: [] }+ : {+ availableModels: [],+ hasFastMode: false,+ effortLevels: [],+ permissionModes: [],+ };+ });+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });+ const { refreshRemoteCatalogSnapshot: refresh } = await import('@/lib/remoteCatalogSnapshot');+ const providers = await import('@/hooks/useDeviceProviders');+ const first = refresh('old');+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(4));+ const obsolete = refresh('old');+ await refresh('healthy');+ expect(invoke).toHaveBeenCalledTimes(8);+ providers.evictDeviceProviders('old');+ hold = false;+ await refresh('old');+ expect(invoke).toHaveBeenCalledTimes(12);+ old.resolve();+ await Promise.all([first, obsolete]);+ expect(invoke).toHaveBeenCalledTimes(12);+ });++ it.each([false, true])(+ 'coalesces a burst and rejects stale results (disconnect: %s)',+ async (disconnect) => {+ const first = deferred();+ let revision = 'old';+ const invoke = vi.fn(async (_device: string, channel: string) => {+ const value = revision;+ if (value === 'old') await first.promise;+ return channel === 'maker:provider:list'+ ? { providers: [] }+ : {+ availableModels: [+ {+ id: value,+ displayName: value,+ contextWindow: 200000,+ efforts: [],+ defaultEffort: null,+ },+ ],+ hasFastMode: false,+ effortLevels: [],+ permissionModes: [],+ };+ });+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });+ const { refreshRemoteCatalogSnapshot } = await import('@/lib/remoteCatalogSnapshot');+ const providers = await import('@/hooks/useDeviceProviders');+ const capabilities = await import('@/hooks/useAgentCapabilities');+ const events = vi.fn();+ capabilities.subscribeDeviceCapabilities('test', 'codex', events);+ const initial = refreshRemoteCatalogSnapshot('test');+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(4));+ revision = 'new';+ const burst = Array.from({ length: 20 }, () => refreshRemoteCatalogSnapshot('test'));+ expect(invoke).toHaveBeenCalledTimes(4);+ if (disconnect) {+ providers.evictDeviceProviders('test');+ capabilities.evictDeviceCapabilities('test');+ }+ first.resolve();+ await Promise.all([initial, ...burst]);+ expect(invoke).toHaveBeenCalledTimes(disconnect ? 4 : 8);+ const ready = events.mock.calls+ .map(([event]) => event)+ .filter((event) => event.status === 'ready');+ expect(ready).toHaveLength(disconnect ? 0 : 1);+ if (!disconnect) expect(ready[0].capabilities.availableModels[0].id).toBe('new');+ // The completed coordinator does not cache results or suppress a later refresh.+ await refreshRemoteCatalogSnapshot('test');+ expect(invoke).toHaveBeenCalledTimes(disconnect ? 8 : 12);+ },+ );+});diff --git a/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsx b/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsxindex 8f353d755e..3a908f83a2 100644--- a/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/SplitGroup.tsx@@ -29,11 +29,9 @@ import {useRemoteBootstrapLoadingDeviceIds,useRemoteProjectSessions,} from '@/features/device-link/remoteProjectsStore';-import { ApiError } from '@/lib/httpClient';-import { getSessionFor } from '@/lib/makerTransport';+import { readSessionBatchFor } from '@/lib/sessionBatchRead';import { getSessionRouteOwnerId, resolveSessionRoute } from '@/lib/orcaSessionIdentity';import { toast } from '@/lib/toast';-import { extractIpcError } from '@/utils/ipcError';import { getSessionDisplayTitle } from './lib/sessionDisplayTitle';import { CCAgentSessionView } from './CCAgentSessionView';import { mergeSessionSources } from './lib/mergeSessionSources';@@ -230,19 +228,13 @@ function SplitGroupActive({// The merged catalog is eventually consistent while local refreshes and// device-link mirrors rebuild. Only prune after the session's owning side- // confirms the pane is no longer active or is absent; getSessionFor+ // confirms the pane is no longer active or is absent; readSessionBatchFor// preserves remote routing.- void Promise.all(- missingSessionIds.map(async (sessionId) => {- try {- const session = await getSessionFor(sessionId);- return session.status === 'archived' || session.status === 'deleted' ? sessionId : null;- } catch (error) {- const errorCode = error instanceof ApiError ? error.code : extractIpcError(error)?.code;- return errorCode === 'NOT_FOUND' ? sessionId : null;- }- }),- ).then((staleSessionIds) => {+ void readSessionBatchFor(missingSessionIds).then((results) => {+ const staleSessionIds = results.map(({ sessionId, value, errorCode }) =>+ errorCode === 'NOT_FOUND' || value?.status === 'archived' || value?.status === 'deleted'+ ? sessionId : null,+ );if (cancelled) return;const confirmedStaleSessionIds = staleSessionIds.filter((sessionId): sessionId is string =>Boolean(sessionId && !sessionsById.has(sessionId)),diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/SplitGroup.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/SplitGroup.test.tsxindex 75ccfd5407..b71ec473e9 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/SplitGroup.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/SplitGroup.test.tsx@@ -53,8 +53,11 @@ vi.mock('@/lib/orcaSessionIdentity', () => ({resolveSessionRoute: resolveSessionRouteMock,}));-vi.mock('@/lib/makerTransport', () => ({- getSessionFor: sessionGetMock,+vi.mock('@/lib/sessionBatchRead', () => ({+ readSessionBatchFor: (ids: string[]) => Promise.all(ids.map(async (sessionId) => {+ try { return { sessionId, value: await sessionGetMock(sessionId) }; }+ catch (error) { return { sessionId, errorCode: (error as { code?: string }).code }; }+ })),}));vi.mock('../CCAgentSessionView', () => ({diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex e95cf1b08f..aed914a42d 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -20,8 +20,7 @@ import type { ScheduleSidebarIndexSnapshot } from '../scheduler/lib/scheduleSideimport type { Session } from '@/lib/ccAgent.types';import { createLogger } from '@/lib/logger';import { extractIpcError } from '@/utils/ipcError';-import { DEVICE_LINK_RECONCILIATION_PROBE_MARKER } from '@cindy/maker-shared/device-link-contract';-import type { RemoteSessionListSessionLike } from '@cindy/maker-shared/session-list';+import { readSessionBatch, isSessionListRow as isRemoteSessionListSession } from '@/lib/sessionBatchRead';import { remoteProjectsStore, type RemoteSessionStatus } from './remoteProjectsStore';import { removeRemoteSessionActivityEntry } from './remoteSessionActivityStore';import type { CachedDeviceSessionsSnapshot } from './mirrorCacheClient';@@ -101,86 +100,6 @@ export function isTransientRemoteError(message: string): boolean {return TRANSIENT_MARKERS.some((m) => message.includes(m));}-function isNullableString(value: unknown): value is string | null {- return value === null || typeof value === 'string';-}--function isRecord(value: unknown): value is Record<string, unknown> {- return !!value && typeof value === 'object' && !Array.isArray(value);-}--function hasOptionalNullableString(record: Record<string, unknown>, key: string): boolean {- return record[key] === undefined || isNullableString(record[key]);-}--function hasOptionalBoolean(record: Record<string, unknown>, key: string): boolean {- return record[key] === undefined || typeof record[key] === 'boolean';-}--function hasOptionalFiniteNumber(record: Record<string, unknown>, key: string): boolean {- const value = record[key];- return (- value === undefined || value === null || (typeof value === 'number' && Number.isFinite(value))- );-}--function isRemoteSessionListSession(- value: unknown,- expectedStatus: RemoteSessionStatus,-): value is RemoteSessionListSessionLike {- if (!value || typeof value !== 'object' || Array.isArray(value)) return false;- const session = value as Record<string, unknown>;- const count = session._count;- return (- typeof session.id === 'string' &&- session.id.length > 0 &&- typeof session.title === 'string' &&- isNullableString(session.workingDir) &&- typeof session.model === 'string' &&- session.status === expectedStatus &&- typeof session.agentKind === 'string' &&- typeof session.createdAt === 'string' &&- typeof session.updatedAt === 'string' &&- (session.userId === undefined || typeof session.userId === 'string') &&- hasOptionalNullableString(session, 'workspaceKind') &&- hasOptionalNullableString(session, 'effort') &&- hasOptionalNullableString(session, 'permissionMode') &&- hasOptionalNullableString(session, 'sdkSessionId') &&- hasOptionalNullableString(session, 'clearedAt') &&- hasOptionalNullableString(session, 'pinnedAt') &&- hasOptionalNullableString(session, 'userSendAt') &&- hasOptionalNullableString(session, 'source') &&- hasOptionalNullableString(session, 'orcaRole') &&- hasOptionalNullableString(session, 'providerId') &&- hasOptionalNullableString(session, 'parentSessionId') &&- hasOptionalNullableString(session, 'forkedAtMessageId') &&- hasOptionalNullableString(session, 'worktreePath') &&- hasOptionalNullableString(session, 'remoteHostId') &&- hasOptionalNullableString(session, 'preview') &&- hasOptionalNullableString(session, 'summary') &&- hasOptionalBoolean(session, 'fastMode') &&- hasOptionalBoolean(session, 'planModeEnabled') &&- hasOptionalBoolean(session, 'usedProjectContext') &&- hasOptionalFiniteNumber(session, 'totalTokenUsage') &&- hasOptionalFiniteNumber(session, 'totalCostUsd') &&- hasOptionalFiniteNumber(session, 'contextTokens') &&- hasOptionalFiniteNumber(session, 'contextWindow') &&- hasOptionalFiniteNumber(session, 'activeTurnStartedAt') &&- hasOptionalFiniteNumber(session, 'lastTurnEndedAt') &&- (session.extraDirs === undefined ||- (Array.isArray(session.extraDirs) &&- session.extraDirs.every((dir) => typeof dir === 'string'))) &&- (session.writableDirs === undefined ||- (Array.isArray(session.writableDirs) &&- session.writableDirs.every((dir) => typeof dir === 'string'))) &&- (count === undefined ||- count === null ||- (isRecord(count) &&- (count.messages === undefined ||- (typeof count.messages === 'number' && Number.isFinite(count.messages)))))- );-}-function parseRemoteSessionList(value: unknown, expectedStatus: RemoteSessionStatus): Session[] {if (!Array.isArray(value) ||@@ -342,20 +261,7 @@ async function probeMissingSessionStatuses(const snapshots = new Map(remoteProjectsStore.getDeviceSessions(deviceId).map((session) => [session.id, session]),);- const results = await Promise.all(- candidates.map(async (sessionId) => {- try {- const value = await window.electronAPI.deviceLink.invoke(- deviceId,- 'local-db:sessions:get',- [sessionId, DEVICE_LINK_RECONCILIATION_PROBE_MARKER],- );- return { sessionId, value };- } catch (error) {- return { sessionId, errorCode: extractIpcError(error)?.code };- }- }),- );+ const results = await readSessionBatch(candidates, deviceId);// 更强的 refresh / remove / disconnect 已使本轮失效时,不应用迟到的补查结果。if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return;const terminalIds = new Set<string>();diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.tsindex 7c264ab20f..ac89098c14 100644--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts@@ -60,6 +60,7 @@ import {} from './mirrorCacheClient';import { prefetchDeviceCapabilities, evictDeviceCapabilities } from '@/hooks/useAgentCapabilities';import { prefetchDeviceProviders, evictDeviceProviders } from '@/hooks/useDeviceProviders';+import { refreshRemoteCatalogSnapshot } from '@/lib/remoteCatalogSnapshot';import {evictDeviceGitSafetySettings,prefetchDeviceGitSafetySettings,@@ -752,10 +753,7 @@ export function useDeviceLinkRemoteProjects(periodicReconcileActive = true, windreturn;}if (push.channel !== 'maker:provider:changed') return;- evictDeviceProviders(push.deviceId);- evictDeviceCapabilities(push.deviceId);- void prefetchDeviceProviders(push.deviceId);- void prefetchDeviceCapabilities(push.deviceId);+ void refreshRemoteCatalogSnapshot(push.deviceId);});// WS 重连后:presence 重新对齐 + 对每个已合格设备重新 subscribe + 重新 bootstrapdiff --git a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts b/apps/desktop/src/renderer/hooks/useAgentCapabilities.tsindex f0850dae9d..71385bdffa 100644--- a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts+++ b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts@@ -623,7 +623,7 @@ export function beginLocalCapabilitiesRefresh(): number {export async function loadLocalCapabilitiesSnapshot(): Promise<LocalCapabilitiesSnapshot> {const api = getMakerApi();if (!api) throw new Error('maker IPC not available');- const entries = await Promise.all(+ const results = await Promise.allSettled(ALL_AGENT_KINDS.map(async (agent): Promise<readonly [AgentKind, AgentCapabilities] | null> => {try {return [agent, await api.getCapabilities(agent)] as const;@@ -640,6 +640,10 @@ export async function loadLocalCapabilitiesSnapshot(): Promise<LocalCapabilities}}),);+ const entries = results.map((result) => {+ if (result.status === 'rejected') throw result.reason;+ return result.value;+ });return entries.filter((entry): entry is readonly [AgentKind, AgentCapabilities] => entry !== null,);diff --git a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts b/apps/desktop/src/renderer/hooks/useDeviceProviders.tsindex 4b35a84df7..4c605ed454 100644--- a/apps/desktop/src/renderer/hooks/useDeviceProviders.ts+++ b/apps/desktop/src/renderer/hooks/useDeviceProviders.ts@@ -378,9 +378,14 @@ export function getCachedDeviceProviders(deviceId: string): DeviceProvidersPayloreturn cache.get(deviceId) ?? null;}-export function evictDeviceProviders(deviceId: string): void {+export function isDeviceProvidersGenerationCurrent(deviceId: string, generation: number): boolean {+ return (deviceGen.get(deviceId) ?? 0) === generation;+}++export function evictDeviceProviders(deviceId: string): number {cache.delete(deviceId);inflight.delete(deviceId);deviceGen.set(deviceId, (deviceGen.get(deviceId) ?? 0) + 1);notifyDeviceProviders(deviceId, { status: 'loading' });+ return deviceGen.get(deviceId)!;}diff --git a/apps/desktop/src/renderer/lib/__tests__/coalescedRefresh.test.ts b/apps/desktop/src/renderer/lib/__tests__/coalescedRefresh.test.tsnew file mode 100644index 0000000000..0566c6ce88--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/coalescedRefresh.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from 'vitest';+import { createCoalescedRefresh } from '../coalescedRefresh';++describe('coalesced refresh', () => {+ it('combines same-turn notifications before starting a read', async () => {+ const schedule = createCoalescedRefresh<number>();+ const read = vi.fn(async () => 1);+ await Promise.all(Array.from({ length: 20 }, () => schedule(read)));+ expect(read).toHaveBeenCalledOnce();+ });++ it('runs the latest invalidation after failure without retrying a failed read', async () => {+ const schedule = createCoalescedRefresh<number>();+ let reject!: (error: Error) => void;+ const failing = vi.fn(+ () =>+ new Promise<number>((_, r) => {+ reject = r;+ }),+ );+ const first = schedule(failing);+ await Promise.resolve();+ const skipped = vi.fn(async () => 2);+ const intermediate = schedule(skipped);+ const latest = schedule(async () => 3);+ reject(new Error('failed'));+ expect(await Promise.all([first, intermediate, latest])).toEqual([3, 3, 3]);+ expect(skipped).not.toHaveBeenCalled();+ expect(failing).toHaveBeenCalledOnce();+ await expect(+ schedule(async () => {+ throw new Error('final failure');+ }),+ ).rejects.toThrow('final failure');+ await expect(schedule(async () => 4)).resolves.toBe(4);+ });+});diff --git a/apps/desktop/src/renderer/lib/__tests__/sessionBatchRead.test.ts b/apps/desktop/src/renderer/lib/__tests__/sessionBatchRead.test.tsnew file mode 100644index 0000000000..0036c56c9c--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/sessionBatchRead.test.ts@@ -0,0 +1,76 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { readSessionBatch, readSessionBatchFor } from '../sessionBatchRead';++const owners = vi.hoisted(() => new Map<string, string>());+vi.mock('@/features/device-link/stickySessionOrigin', () => ({+ getStickySessionDeviceId: (id: string) => owners.get(id) ?? null,+}));+const row = (id: string, status = 'active') => ({+ id, status, title: id, workingDir: null, model: 'model', agentKind: 'cc',+ createdAt: '2026-09-12T00:00:00Z', updatedAt: '2026-09-12T00:00:00Z',+ _count: { messages: 3 }, preview: 'preview',+});+const get = vi.fn();+const getMany = vi.fn();+const invoke = vi.fn();+beforeEach(() => {+ vi.resetAllMocks();+ owners.clear();+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: {+ localDb: { sessions: { get, getMany } }, deviceLink: { invoke },+ } });+ getMany.mockImplementation(async (ids: string[]) => ids.filter((id) => id !== 'missing').map((id) => row(id)));+ invoke.mockImplementation(async (_device: string, channel: string, [ids]: [string[]]) => {+ expect(channel).toBe('local-db:sessions:get-many');+ return ids.filter((id) => id !== 'missing').map((id) => row(id));+ });+});+afterEach(() => { delete (window as unknown as Record<string, unknown>).electronAPI; });++describe('shared local and remote metadata reads', () => {+ it('uses the same projection, missing semantics and deduplication for either transport', async () => {+ const ids = ['first', 'missing', 'first'];+ const local = await readSessionBatch(ids);+ const remote = await readSessionBatch(ids, 'desktop');+ expect(local).toEqual(remote);+ expect(local).toEqual([{ sessionId: 'first', value: row('first') }, { sessionId: 'missing', errorCode: 'NOT_FOUND' }]);+ expect(getMany).toHaveBeenCalledExactlyOnceWith(['first', 'missing']);+ expect(invoke).toHaveBeenCalledExactlyOnceWith('desktop', 'local-db:sessions:get-many', [['first', 'missing']]);+ expect(get).not.toHaveBeenCalled();+ });++ it.each([undefined, 'desktop'])('bounds batches identically for target %s', async (device) => {+ const ids = Array.from({ length: 70 }, (_, index) => `s${index}`);+ const result = await readSessionBatch(ids, device);+ expect(result.map((item) => item.sessionId)).toEqual(ids);+ const chunks = device ? invoke.mock.calls.map((call) => call[2][0]) : getMany.mock.calls.map((call) => call[0]);+ expect(chunks.map((chunk) => chunk.length)).toEqual([32, 32, 6]);+ });++ it.each([undefined, 'desktop'])('does not turn malformed replies or whole-batch errors into deletions for %s', async (device) => {+ const batch = device ? invoke : getMany;+ for (const value of [[row('unrequested')], [row('s'), row('s')], [{ id: 's' }]]) {+ batch.mockResolvedValueOnce(value);+ expect(await readSessionBatch(['s'], device)).toEqual([{ sessionId: 's' }]);+ }+ batch.mockRejectedValueOnce(new Error('[NOT_FOUND] Batch unavailable'));+ expect(await readSessionBatch(['s'], device)).toEqual([{ sessionId: 's', errorCode: undefined }]);+ expect(get).not.toHaveBeenCalled();+ });++ it('captures each target and keeps local ids out of remote requests and vice versa', async () => {+ owners.set('remote', 'desktop');+ const results = await readSessionBatchFor(['local', 'remote', 'remote']);+ expect(results).toHaveLength(2);+ expect(getMany).toHaveBeenCalledExactlyOnceWith(['local']);+ expect(invoke).toHaveBeenCalledExactlyOnceWith('desktop', 'local-db:sessions:get-many', [['remote']]);+ });++ it('does not cache settled rows across reads', async () => {+ await readSessionBatch(['s']);+ getMany.mockResolvedValueOnce([row('s', 'archived')]);+ expect((await readSessionBatch(['s']))[0].value?.status).toBe('archived');+ expect(getMany).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/desktop/src/renderer/lib/coalescedRefresh.ts b/apps/desktop/src/renderer/lib/coalescedRefresh.tsnew file mode 100644index 0000000000..6699c6a68c--- /dev/null+++ b/apps/desktop/src/renderer/lib/coalescedRefresh.ts@@ -0,0 +1,31 @@+/** Share one active read and retain only the latest invalidation for a trailing read.+ * Callers invalidate their own snapshot generation synchronously before scheduling.+ * No results, retries, timers or ownership decisions are retained here.+ */+export function createCoalescedRefresh<T>(): (read: () => Promise<T>) => Promise<T> {+ let active: Promise<T> | undefined;+ let latest: (() => Promise<T>) | undefined;+ return (read) => {+ latest = read;+ if (!active) {+ active = Promise.resolve().then(async () => {+ try {+ let result!: T;+ while (latest) {+ const next = latest;+ latest = undefined;+ try {+ result = await next();+ } catch (error) {+ if (!latest) throw error;+ }+ }+ return result;+ } finally {+ active = undefined;+ }+ });+ }+ return active;+ };+}diff --git a/apps/desktop/src/renderer/lib/localCatalogSnapshot.ts b/apps/desktop/src/renderer/lib/localCatalogSnapshot.tsindex 38d4375cd7..1a799c53d0 100644--- a/apps/desktop/src/renderer/lib/localCatalogSnapshot.ts+++ b/apps/desktop/src/renderer/lib/localCatalogSnapshot.ts@@ -7,6 +7,8 @@* device-link 的远端 capabilities 不经过这里,继续按 deviceId 独立缓存。*/import { createLogger } from '@/lib/logger';+import { createCoalescedRefresh } from '@/lib/coalescedRefresh';+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';import { migrateModelVisibilityDefaults } from '@/state/modelVisibilityPrefs';import {beginLocalCapabilitiesRefresh,@@ -23,37 +25,61 @@ import {const log = createLogger('localCatalogSnapshot');let refreshGeneration = 0;+let refreshOwner = getDataOwnerGeneration();+let scheduleRefresh = createCoalescedRefresh<boolean>();/** 联合刷新 providers + 可用 agent capabilities,并只提交最新的完整结果。 */export async function refreshLocalCatalogSnapshot(): Promise<boolean> {+ const owner = getDataOwnerGeneration();+ if (owner !== refreshOwner) {+ // A new owner must not wait for an old owner's outstanding IPC.+ refreshOwner = owner;+ scheduleRefresh = createCoalescedRefresh<boolean>();+ }const generation = ++refreshGeneration;const providersGeneration = beginProvidersRefresh();const capabilitiesGeneration = beginLocalCapabilitiesRefresh();- try {- const [providers, capabilities] = await Promise.all([- loadProvidersSnapshot(),- loadLocalCapabilitiesSnapshot(),- ]);- const isCurrent = (): boolean => refreshGeneration === generation- && isProvidersRefreshCurrent(providersGeneration, providers)- && isLocalCapabilitiesRefreshCurrent(capabilitiesGeneration);- if (!isCurrent()) return false;- const initialized = await migrateModelVisibilityDefaults(providers.dataOwnerId, providers.ownerGeneration, providers.providers, isCurrent);- // Failed persistence/locking must reach preload's retry loop. Waiting for another- // renderer's preference write must not publish a stale catalog either.- if (!initialized || !isCurrent()) return false;+ return scheduleRefresh(async () => {+ if (generation !== refreshGeneration) return false;+ try {+ // A failed member must not release the scheduling slot while its siblings+ // are still reading; otherwise the trailing round overlaps them again.+ const results = await Promise.allSettled([+ loadProvidersSnapshot(),+ loadLocalCapabilitiesSnapshot(),+ ]);+ const [providerResult, capabilitiesResult] = results;+ if (providerResult.status === 'rejected') throw providerResult.reason;+ if (capabilitiesResult.status === 'rejected') throw capabilitiesResult.reason;+ const providers = providerResult.value;+ const capabilities = capabilitiesResult.value;+ const isCurrent = (): boolean =>+ refreshGeneration === generation &&+ isProvidersRefreshCurrent(providersGeneration, providers) &&+ isLocalCapabilitiesRefreshCurrent(capabilitiesGeneration);+ if (!isCurrent()) return false;+ const initialized = await migrateModelVisibilityDefaults(+ providers.dataOwnerId,+ providers.ownerGeneration,+ providers.providers,+ isCurrent,+ );+ // Failed persistence/locking must reach preload's retry loop. Waiting for another+ // renderer's preference write must not publish a stale catalog either.+ if (!initialized || !isCurrent()) return false;- // 两次提交均为同步通知;React 会把同一事件循环内的 hook 更新批处理到同一帧。- commitLocalCapabilitiesSnapshot(capabilitiesGeneration, capabilities);- commitProvidersSnapshot(providersGeneration, providers);- return true;- } catch (error) {- if (refreshGeneration === generation) {- log.warn('local catalog snapshot refresh failed; keeping last valid snapshot', error);+ // 两次提交均为同步通知;React 会把同一事件循环内的 hook 更新批处理到同一帧。+ commitLocalCapabilitiesSnapshot(capabilitiesGeneration, capabilities);+ commitProvidersSnapshot(providersGeneration, providers);+ return true;+ } catch (error) {+ if (refreshGeneration === generation) {+ log.warn('local catalog snapshot refresh failed; keeping last valid snapshot', error);+ }+ return false;}- return false;- }+ });}/** 启动预热保留原有三次瞬时 IPC 重试语义;每次仍按可用快照原子提交。 */diff --git a/apps/desktop/src/renderer/lib/remoteCatalogSnapshot.ts b/apps/desktop/src/renderer/lib/remoteCatalogSnapshot.tsnew file mode 100644index 0000000000..45ad80663a--- /dev/null+++ b/apps/desktop/src/renderer/lib/remoteCatalogSnapshot.ts@@ -0,0 +1,41 @@+/** Remote catalog invalidations use the same refresh scheduling as local reads.+ * Existing device generations remain the authority for disconnect/owner changes.+ */+import { createCoalescedRefresh } from '@/lib/coalescedRefresh';+import { evictDeviceCapabilities, prefetchDeviceCapabilities } from '@/hooks/useAgentCapabilities';+import {+ evictDeviceProviders,+ isDeviceProvidersGenerationCurrent,+ prefetchDeviceProviders,+} from '@/hooks/useDeviceProviders';++const refreshes = new Map<+ string,+ {+ schedule: ReturnType<typeof createCoalescedRefresh<void>>;+ generation: number;+ }+>();++export async function refreshRemoteCatalogSnapshot(deviceId: string): Promise<void> {+ const generation = evictDeviceProviders(deviceId);+ evictDeviceCapabilities(deviceId);+ const previous = refreshes.get(deviceId);+ const refresh = {+ // An intervening eviction belongs to disconnect/ownership handling. Its new+ // link must not wait for requests still timing out on the retired link.+ schedule:+ previous?.generation === generation - 1 ? previous.schedule : createCoalescedRefresh<void>(),+ generation,+ };+ refreshes.set(deviceId, refresh);+ try {+ await refresh.schedule(async () => {+ // A queued refresh must not reopen reads after disconnect or account change.+ if (!isDeviceProvidersGenerationCurrent(deviceId, generation)) return;+ await Promise.all([prefetchDeviceProviders(deviceId), prefetchDeviceCapabilities(deviceId)]);+ });+ } finally {+ if (refreshes.get(deviceId) === refresh) refreshes.delete(deviceId);+ }+}diff --git a/apps/desktop/src/renderer/lib/sessionBatchRead.ts b/apps/desktop/src/renderer/lib/sessionBatchRead.tsnew file mode 100644index 0000000000..13f5000e12--- /dev/null+++ b/apps/desktop/src/renderer/lib/sessionBatchRead.ts@@ -0,0 +1,149 @@+/** Shared bounded metadata reads. Transport selection never changes query semantics. */+import type { Session } from './ccAgent.types';+import type { RemoteSessionListSessionLike } from '@cindy/maker-shared/session-list';+import { DEVICE_LINK_RECONCILIATION_PROBE_MARKER } from '@cindy/maker-shared/device-link-contract';+import { extractIpcError } from '@/utils/ipcError';+import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';++import { SESSION_READ_BATCH_LIMIT } from '../../shared/sessionRead';+export type SessionReadResult = { sessionId: string; value?: Session; errorCode?: string };++function isNullableString(value: unknown): value is string | null {+ return value === null || typeof value === 'string';+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === 'object' && !Array.isArray(value);+}++function hasOptionalNullableString(record: Record<string, unknown>, key: string): boolean {+ return record[key] === undefined || isNullableString(record[key]);+}++function hasOptionalBoolean(record: Record<string, unknown>, key: string): boolean {+ return record[key] === undefined || typeof record[key] === 'boolean';+}++function hasOptionalFiniteNumber(record: Record<string, unknown>, key: string): boolean {+ const value = record[key];+ return (+ value === undefined || value === null || (typeof value === 'number' && Number.isFinite(value))+ );+}++export function isSessionListRow(+ value: unknown,+ expectedStatus: 'active' | 'archived' | 'deleted',+): value is RemoteSessionListSessionLike {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const session = value as Record<string, unknown>;+ const count = session._count;+ return (+ typeof session.id === 'string' &&+ session.id.length > 0 &&+ typeof session.title === 'string' &&+ isNullableString(session.workingDir) &&+ typeof session.model === 'string' &&+ session.status === expectedStatus &&+ typeof session.agentKind === 'string' &&+ typeof session.createdAt === 'string' &&+ typeof session.updatedAt === 'string' &&+ (session.userId === undefined || typeof session.userId === 'string') &&+ hasOptionalNullableString(session, 'workspaceKind') &&+ hasOptionalNullableString(session, 'effort') &&+ hasOptionalNullableString(session, 'permissionMode') &&+ hasOptionalNullableString(session, 'sdkSessionId') &&+ hasOptionalNullableString(session, 'clearedAt') &&+ hasOptionalNullableString(session, 'pinnedAt') &&+ hasOptionalNullableString(session, 'userSendAt') &&+ hasOptionalNullableString(session, 'source') &&+ hasOptionalNullableString(session, 'orcaRole') &&+ hasOptionalNullableString(session, 'providerId') &&+ hasOptionalNullableString(session, 'parentSessionId') &&+ hasOptionalNullableString(session, 'forkedAtMessageId') &&+ hasOptionalNullableString(session, 'worktreePath') &&+ hasOptionalNullableString(session, 'remoteHostId') &&+ hasOptionalNullableString(session, 'preview') &&+ hasOptionalNullableString(session, 'summary') &&+ hasOptionalBoolean(session, 'fastMode') &&+ hasOptionalBoolean(session, 'planModeEnabled') &&+ hasOptionalBoolean(session, 'usedProjectContext') &&+ hasOptionalFiniteNumber(session, 'totalTokenUsage') &&+ hasOptionalFiniteNumber(session, 'totalCostUsd') &&+ hasOptionalFiniteNumber(session, 'contextTokens') &&+ hasOptionalFiniteNumber(session, 'contextWindow') &&+ hasOptionalFiniteNumber(session, 'activeTurnStartedAt') &&+ hasOptionalFiniteNumber(session, 'lastTurnEndedAt') &&+ (session.extraDirs === undefined ||+ (Array.isArray(session.extraDirs) &&+ session.extraDirs.every((dir) => typeof dir === 'string'))) &&+ (session.writableDirs === undefined ||+ (Array.isArray(session.writableDirs) &&+ session.writableDirs.every((dir) => typeof dir === 'string'))) &&+ (count === undefined ||+ count === null ||+ (isRecord(count) &&+ (count.messages === undefined ||+ (typeof count.messages === 'number' && Number.isFinite(count.messages)))))+ );+}+++async function readChunk(ids: string[], deviceId?: string): Promise<SessionReadResult[]> {+ const getMany = window.electronAPI.localDb?.sessions?.getMany;+ if (deviceId || getMany) {+ try {+ const value = deviceId+ ? await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:get-many', [ids])+ : await getMany(ids);+ if (!Array.isArray(value) || value.some((row) => !isRecord(row)+ || typeof row.id !== 'string' || !ids.includes(row.id)+ || !(row.status === 'active' || row.status === 'archived' || row.status === 'deleted')+ || !isSessionListRow(row, row.status))) return ids.map((sessionId) => ({ sessionId }));+ const rows = new Map(value.map((row) => [row.id, row as Session]));+ if (rows.size !== value.length) return ids.map((sessionId) => ({ sessionId }));+ return ids.map((sessionId) => rows.has(sessionId)+ ? { sessionId, value: rows.get(sessionId) } : { sessionId, errorCode: 'NOT_FOUND' });+ } catch (error) {+ const ipcError = extractIpcError(error);+ const code = ipcError?.code;+ const oversized = code === 'PRECONDITION_FAILED' && ipcError?.message === 'REMOTE_SESSION_BATCH_TOO_LARGE';+ // Only transport compatibility failures permit bounded single-read fallback.+ if (!deviceId || (code !== 'DEVICE_LINK_CHANNEL_NOT_ALLOWED' && !oversized)) {+ return ids.map((sessionId) => ({ sessionId, errorCode: code === 'NOT_FOUND' ? undefined : code }));+ }+ }+ }+ return Promise.all(ids.map(async (sessionId) => {+ try {+ const value = deviceId+ ? await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:get', [sessionId, DEVICE_LINK_RECONCILIATION_PROBE_MARKER])+ : await window.electronAPI.localDb.sessions.get(sessionId);+ return { sessionId, value: value as Session };+ } catch (error) {+ return { sessionId, errorCode: extractIpcError(error)?.code };+ }+ }));+}++/** One target per batch, sequential bounded chunks, no persistent result cache. */+export async function readSessionBatch(ids: readonly string[], deviceId?: string): Promise<SessionReadResult[]> {+ const unique = [...new Set(ids)];+ const results: SessionReadResult[] = [];+ for (let offset = 0; offset < unique.length; offset += SESSION_READ_BATCH_LIMIT) {+ results.push(...await readChunk(unique.slice(offset, offset + SESSION_READ_BATCH_LIMIT), deviceId));+ }+ return results;+}++/** Capture ownership before starting I/O; never read a remote id from the local database. */+export async function readSessionBatchFor(ids: readonly string[]): Promise<SessionReadResult[]> {+ const groups = new Map<string | undefined, string[]>();+ for (const id of new Set(ids)) {+ const device = getStickySessionDeviceId(id) ?? undefined;+ const group = groups.get(device) ?? [];+ group.push(id);+ groups.set(device, group);+ }+ return (await Promise.all([...groups].map(([device, group]) => readSessionBatch(group, device)))).flat();+}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 0596d489ce..fc632713cb 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -4577,6 +4577,7 @@ interface ElectronAPI {source?: 'cindy-make';}) => Promise<import('@/lib/ccAgent.types').Session>;get: (id: string) => Promise<import('@/lib/ccAgent.types').Session>;+ getMany: (ids: string[]) => Promise<import('@/lib/ccAgent.types').Session[]>;resolveReferences: (sessionIds: string[],) => Promise<import('../shared/sessionReference').SessionReference[]>;diff --git a/apps/desktop/src/shared/sessionRead.ts b/apps/desktop/src/shared/sessionRead.tsnew file mode 100644index 0000000000..dd71298d30--- /dev/null+++ b/apps/desktop/src/shared/sessionRead.ts@@ -0,0 +1,2 @@+/** Shared local/remote IPC batch contract; transport frame limits may still require fallback. */+export const SESSION_READ_BATCH_LIMIT = 32;diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 60baac9cc3..0452d1635c 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -108,6 +108,53 @@ enum 编译分支,也不接受任意 HTML、React 或无限 UI DSL。结构化 Session 内容必须携带可读 `fallbackMarkdown`,旧客户端至少能阅读并继续任务。只有新增移动端此前无法表达的内容或交互原语时,才要求客户端发版。+## 本机与远程共用查询策略++本机独立使用、远程操作、两端同时使用应共享数据语义与通用查询策略;远程连接状态+不得改变本机的业务规则。数据库优化落在共享数据访问层,远程边界只承担授权、协议+兼容和传输约束,不另建一套查询、缓存或调度策略。++`localDb/sessionQueries.ts` 统一单条、批量、列表的字段选择、消息计数、预览与结果整理;+单条读取委托批量读取,列表保留同一语句内先限量再取详情的查询形状。Renderer 的+`sessionBatchRead.ts` 统一按所属设备路由、去重、分批、结果验证与缺失判定;本机分屏+补读与远程列表补读都复用它。现有列表在途合并和数据库 Worker 调度继续由本机与远程+共用;不增加已完成结果缓存。远程权限结论仍只在授权边界处理。++### 远程边界与延迟诊断++远程列表复用本地查询,返回前额外执行伙伴可见性过滤。过滤按本次授权阶段批量查询,+每条 SQL 最多 200 个 ID;不跨请求缓存授权结论。缓存回复与离线重放仍重新检查,账号+变化时丢弃旧结果。控制端补齐列表外任务时优先使用 `local-db:sessions:get-many`+(最多 32 个 ID,当前每轮补读最多 8 个),保留单条 GET 的元数据、预览和计数语义。+旧被控端不支持或批量回复超帧预算时回退到原有有界 GET;超时、撤权、损坏回复不触发+成倍重试,迟到回复不能覆盖更新的 push。++Debug 日志区分两层耗时:++- `remote invoke slow execution`(至少 1 秒)包含 `stagesMs`:调用前授权、业务 handler、+ 调用后授权、设置持久化、返回投影。总耗时还包含调度和序列化,不等于 SQL 执行时间。+- `db-rpc` 的 `rpc.slow`(至少 250 毫秒)包含 `queueMs`(主线程待发送队列)、+ `workerWaitMs`(投递到 Worker 开始处理)、`workerExecutionMs`(整个 Worker 操作)、+ `deliveryMs`(结果传输及主线程调度)。事务操作的执行时间覆盖整个事务;结果传输时间+ 也不能直接称为主线程阻塞。旧 Worker 未附计时信息时只记录可测部分。++诊断只记录本地 RPC 序号、操作类别、数量与耗时,不记录 SQL、参数、消息内容或结果。+性能复测应同时包含前台发送、另一控制端刷新与补读、本地读取;分别报告请求数量和延迟,+不能把内存数据库基准当成真机网络端到端改善。++`device-link request slow/failed/timeout` 另记录 `firstWriteWaitMs`(请求建立到首次+WebSocket 写入成功)与 `afterFirstWriteMs`(首次写入到结束);从未写出时记录+`firstWrite=none`。写入成功不是送达回执,后半段仍包含 socket/relay/网络、对端处理和+接收端调度。可靠层在至少 250ms 的等待或重发时记录发送 `queueMs`(首次写出)/+`ageMs`(重发时消息年龄),以及接收 `assemblyMs`(首分片到重组完成)/+`orderedWaitMs`(重组完成到按序交付)。新增阶段时长使用各端单调时钟,以 requestId 关联,+不相减不同设备的墙钟,也不改变 wire、ACK、重试或授权语义。++本地目录联合刷新和远程目录变化推送共用 `coalescedRefresh.ts`:同轮通知合并,+在途期间只保留最新一次补读;失效立即推进已有代次,旧结果不提交。整组读取结束+(包括失败后的其它成员)才释放刷新位置。账号切换或远程断连后的新代次独立刷新,+不等待旧请求超时;已经取消的补读不重新打开连接。该合并不引入结果缓存或定时重试。+## PR 门禁功能类 PR 的 Description 必须写明上述每一项的结论,三选一:diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex dee0caa8b0..5e00a29141 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -1264,6 +1264,56 @@ describe('DeviceLinkClient', () => {} finally { h.client.stop(); }});+ it('separates fragment assembly from ordered delivery wait without logging payloads', async () => {+ const debug = vi.fn();+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 },+ logger: { debug, info: vi.fn(), warn: vi.fn(), error: vi.fn() } });+ let now = 100;+ const clock = vi.spyOn(h.client as unknown as { monotonicNow(): number }, 'monotonicNow').mockImplementation(() => now);+ try {+ h.client.start(); await tick(); h.current().ack();+ await establishInboundReliableLink(h, 'timing-stream');+ const received = vi.fn();+ h.client.onFrame(received);+ const tail = encodeReliableFrames({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-b', id: 'timing-request',+ payload: { ok: true, result: 'PRIVATE-PAYLOAD'.repeat(12_000) },+ }, 'timing-stream', 2);+ expect(tail.length).toBeGreaterThan(1);+ h.current().push(tail[0]);+ now += 300;+ tail.slice(1).forEach(frame => h.current().push(frame));+ await tick();+ expect(received).not.toHaveBeenCalled();+ now += 400;+ encodeReliableFrames({ v: PROTOCOL_VERSION, kind: 'invoke', src: 'dev-b', id: 'head',+ payload: { channel: 'local-db:sessions:list', args: [] },+ }, 'timing-stream', 1).forEach(frame => h.current().push(frame));+ await tick();+ expect(received).toHaveBeenCalledTimes(2);+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('assemblyMs=300 orderedWaitMs=400'));+ expect(debug.mock.calls.flat().join(' ')).not.toContain('PRIVATE-PAYLOAD');+ } finally { h.client.stop(); clock.mockRestore(); }+ });++ it('records first socket write separately from the response wait for legacy peers', async () => {+ const debug = vi.fn();+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 },+ logger: { debug, info: vi.fn(), warn: vi.fn(), error: vi.fn() } });+ let now = 100;+ const clock = vi.spyOn(h.client as unknown as { monotonicNow(): number }, 'monotonicNow').mockImplementation(() => now);+ const wall = vi.spyOn(Date, 'now').mockImplementation(() => now);+ try {+ h.client.start(); await tick(); h.current().ack();+ const result = h.client.invoke('dev-b', { channel: 'local-db:sessions:list', args: [] });+ const request = h.current().sent.at(-1)!;+ now += 1500;+ h.current().push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-b', id: request.id,+ payload: { ok: true, result: [] } });+ await result;+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('firstWriteWaitMs=0 afterFirstWriteMs=1500'));+ } finally { h.client.stop(); clock.mockRestore(); wall.mockRestore(); }+ });+it('bounds recovery stage logs, measures with monotonic time and records a fresh outbound handshake', async () => {const debug = vi.fn();const h = makeHarness({ timing: { pingIntervalMs: 60_000 },diff --git a/packages/device-link/src/__tests__/invokePolicy.test.ts b/packages/device-link/src/__tests__/invokePolicy.test.tsindex 70a874d44e..25478d4f9e 100644--- a/packages/device-link/src/__tests__/invokePolicy.test.ts+++ b/packages/device-link/src/__tests__/invokePolicy.test.ts@@ -7,7 +7,7 @@ import {} from '../index.js';describe('remote invoke policy boundaries', () => {- it.each(['local-db:sessions:list', 'local-db:sessions:get', 'local-db:sessions:interrupted-pending', 'maker:list-active'])(+ it.each(['local-db:sessions:list', 'local-db:sessions:get', 'local-db:sessions:get-many', 'local-db:sessions:interrupted-pending', 'maker:list-active'])('explicitly permits retrying completed %s reads', (channel) => {expect(isCompletedInvokeRetryableReadChannel(channel)).toBe(true);},@@ -25,6 +25,8 @@ describe('remote invoke policy boundaries', () => {it('allows retrying a read without sharing a snapshot from before a write', () => {expect(isPeerResetRetryableReadChannel('local-db:sessions:get')).toBe(true);+ expect(isPeerResetRetryableReadChannel('local-db:sessions:get-many')).toBe(true);+ expect(canCoalesceRemoteListing({ channel: 'local-db:sessions:get-many', args: [['id']] })).toBe(false);expect(canCoalesceRemoteListing({ channel: 'local-db:sessions:get', args: ['id'] })).toBe(false);expect(isPeerResetRetryableReadChannel('local-db:sessions:list')).toBe(true);expect(canCoalesceRemoteListing({ channel: 'local-db:sessions:list', args: [] })).toBe(true);diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex e9ea116ffb..022cc30815 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -264,6 +264,8 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [// —— 读模型(被控端本地 DB 是数据真相)——'local-db:sessions:list','local-db:sessions:get',+ // Bounded metadata reconciliation. Old hosts reject this; controllers fall back to GET.+ 'local-db:sessions:get-many',// Read-only indexed task search for the remote Composer @ palette and the// controller sidebar task search. Older controlled clients reject this// channel and the controller falls back to the bounded legacy sessions:list@@ -729,6 +731,7 @@ export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {// 不吃满超时),不会误伤首拉重试。'local-db:sessions:list': 12_000,'local-db:sessions:get': 12_000,+ 'local-db:sessions:get-many': 12_000,};/**diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex 165359098b..ee268e4ad8 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -472,6 +472,8 @@ export function classifyConnectionIssue(export type InboundFrameHandler = (env: Envelope) => unknown | Promise<unknown>;interface PendingRequest {+ /** Diagnostics only: first successful socket write, not a delivery receipt. */+ noteFirstWrite?: () => void;resolve(env: Envelope): void;reject(err: DeviceLinkError): void;timer: ReturnType<typeof setTimeout>;@@ -617,6 +619,8 @@ interface PendingInboundLinkOffer {}interface ReceiveAssembly {+ /** Local monotonic time of the first fragment; diagnostics only. */+ receivedAt: number;kind: Envelope['kind'];id?: string;src?: string;@@ -632,7 +636,7 @@ interface ReceiveStreamState {requestedBaseSeq: number;deliveringSeq: number | null;assemblies: Map<number, ReceiveAssembly>;- ready: Map<number, { env: Envelope; json: string }>;+ ready: Map<number, { env: Envelope; json: string; receivedAt: number; readyAt: number }>;bufferedBytes: number;drain: Promise<void> | null;/** drain 已在途时又有新帧入队;当前轮结束前必须再检查一次队头。 */@@ -1459,24 +1463,29 @@ export class DeviceLinkClient {const id = createRequestId();const timeout = timeoutMs ?? this.timing.requestTimeoutMs;const startedAt = Date.now();+ const startedMonotonicAt = this.monotonicNow();+ let firstWriteAt: number | undefined;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;+ const stages = firstWriteAt === undefined ? ' firstWrite=none'+ : ` firstWriteWaitMs=${Math.round(firstWriteAt - startedMonotonicAt)}`+ + ` afterFirstWriteMs=${Math.round(this.monotonicNow() - firstWriteAt)}`;if (outcome === 'timeout') {- this.log.warn(`device-link request timeout ${requestDescription} elapsed=${elapsedMs}ms`);+ this.log.warn(`device-link request timeout ${requestDescription} elapsed=${elapsedMs}ms${stages}`);return;}if (outcome === 'error') {if (err?.code !== 'NOT_CONNECTED' || elapsedMs >= SLOW_REQUEST_WARN_MS) {this.log.debug(- `device-link request failed ${requestDescription} code=${err?.code ?? 'UNKNOWN'} elapsed=${elapsedMs}ms`,+ `device-link request failed ${requestDescription} code=${err?.code ?? 'UNKNOWN'} elapsed=${elapsedMs}ms${stages}`,);}return;}if (elapsedMs >= SLOW_REQUEST_WARN_MS) {- this.log.debug(`device-link request slow ${requestDescription} elapsed=${elapsedMs}ms`);+ this.log.debug(`device-link request slow ${requestDescription} elapsed=${elapsedMs}ms${stages}`);}};@@ -1490,6 +1499,7 @@ export class DeviceLinkClient {}, timeout);const pendingRequest: PendingRequest = {+ noteFirstWrite: () => { firstWriteAt ??= this.monotonicNow(); },resolve: (frame) => {clearTimeout(timer);logFinished('ok');@@ -2550,7 +2560,8 @@ export class DeviceLinkClient {this.log.warn(`dropping invalid reliable payload seq=${meta.seq}`);return { handled: true };}- stream.ready.set(meta.seq, { env, json: parsed.data });+ const receivedAt = this.monotonicNow();+ stream.ready.set(meta.seq, { env, json: parsed.data, receivedAt, readyAt: receivedAt });stream.bufferedBytes += bytes;} else {if (segment.totalBytes > MAX_TRANSPORT_REASSEMBLY_BYTES) {@@ -2559,6 +2570,7 @@ export class DeviceLinkClient {}const current = stream.assemblies.get(meta.seq);const assembly = current ?? {+ receivedAt: this.monotonicNow(),kind: env.kind,id: env.id,src: env.src,@@ -2610,7 +2622,7 @@ export class DeviceLinkClient {this.sendTransportAck(env.src, meta.streamId, stream.lastDeliveredSeq);return { handled: true };}- stream.ready.set(meta.seq, { env, json });+ stream.ready.set(meta.seq, { env, json, receivedAt: assembly.receivedAt, readyAt: this.monotonicNow() });}}@@ -2649,6 +2661,14 @@ export class DeviceLinkClient {}stream.deliveringSeq = nextSeq;+ const assemblyMs = Math.round(ready.readyAt - ready.receivedAt);+ const orderedWaitMs = Math.round(this.monotonicNow() - ready.readyAt);+ if ((logical.kind === 'invoke' || logical.kind === 'invoke-result')+ && (assemblyMs >= 250 || orderedWaitMs >= 250)) {+ this.log.debug(`device-link receive timing kind=${logical.kind} request=${logical.id?.slice(0, 8) ?? 'none'}`+ + ` src=${src.slice(0, 8)} seq=${nextSeq}`+ + ` assemblyMs=${assemblyMs} orderedWaitMs=${orderedWaitMs}`);+ }let handled: boolean;try {handled = isTransportSkipPayload(logical.payload)@@ -2981,6 +3001,15 @@ export class DeviceLinkClient {} finally {congestionBudget?.refund(pending.envelope.dst!, frames.length - sent);if (sent > 0) {+ const ageMs = Math.round(this.monotonicNow() - pending.enqueuedAt);+ if ((pending.envelope.kind === 'invoke' || pending.envelope.kind === 'invoke-result')+ && (ageMs >= 250 || pending.attempts > 0)) {+ this.log.debug(`device-link send timing kind=${pending.envelope.kind} request=${pending.envelope.id?.slice(0, 8) ?? 'none'}`+ + ` dst=${pending.envelope.dst!.slice(0, 8)} seq=${pending.seq}`+ + ` ${pending.attempts === 0 ? 'queueMs' : 'ageMs'}=${ageMs}`+ + ` attempt=${pending.attempts + 1} frames=${sent} bytes=${pending.bytes}`+ + ` pending=${peer.pending.size} congestion=${this.congestionCloseStreak}`);+ }pending.sent = true;pending.attempts++;pending.lastSentAt = Date.now();@@ -3064,6 +3093,7 @@ export class DeviceLinkClient {this.rememberOutboundRouteGeneration(routed.id!, env.dst, generation);try {this.sendEnvelope(routed);+ this.pending.get(routed.id!)?.noteFirstWrite?.();} catch (err) {this.rollbackOutboundRouteGeneration(routed.id!, env.dst, generation);throw err;diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.tsindex 3f136329aa..b959e8cb5a 100644--- a/packages/device-link/src/invokePolicy.ts+++ b/packages/device-link/src/invokePolicy.ts@@ -89,6 +89,7 @@ export function resolveRemoteInvokeTimeoutMs(const PEER_RESET_RETRYABLE_READ_CHANNELS = new Set(['local-db:sessions:list','local-db:sessions:get',+ 'local-db:sessions:get-many','local-db:conversations:search','local-db:history:messages','local-db:messages:list',@@ -124,6 +125,7 @@ export function isPeerResetRetryableReadChannel(channel: string): boolean {const COMPLETED_INVOKE_RETRYABLE_READ_CHANNELS: ReadonlySet<string> = new Set(['local-db:sessions:list','local-db:sessions:get',+ 'local-db:sessions:get-many','local-db:sessions:interrupted-pending','maker:list-active',]);