Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(device-link): 远程发送少走往返、记录发送耗时,打字时预热 Agent (#6610)

Dasha0ccbd7f7c51
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index 8301d22aff..6805cbb796 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -673,7 +673,7 @@ describe('sendToSession ordering', () => {
const makerSendCreateDbMessageBlock = extractBetween(
source,
'const createUserMessageDurably:',
- 'const { sendToAgentAccepted: sendToAgentAcceptedUnlocked }',
+ ' sendToAgentAccepted: sendToAgentAcceptedUnlocked,',
);
const makerSendPreviewHookBlock = extractBetween(
source,
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index e35e6f4354..dff8788699 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -51,6 +51,7 @@ import { compactToolCardResult } from '../../shared/toolResultPersistCap.js';
*/
import { RemoteInvokeTiming } from './remoteInvokeTiming.js';
+import { observeRemoteSendPush } from './remoteSendTrace.js';
import {
computeAllowlistHash,
canCoalesceRemoteListing,
@@ -2305,6 +2306,8 @@ function sendPushBestEffortAuthorized(
try {
if (ownerStamp === undefined) activeClient.sendPush(dst, channel, payload);
else activeClient.sendPush(dst, channel, payload, ownerStamp);
+ // Telemetry reads "pushed" only where a frame was actually handed to the link.
+ observeRemoteSendPush(channel, payload);
return;
} catch (err) {
if (!isPayloadTooLargeError(err)) {
@@ -2323,6 +2326,7 @@ function sendPushBestEffortAuthorized(
try {
if (ownerStamp === undefined) activeClient.sendPush(dst, channel, compactPayload);
else activeClient.sendPush(dst, channel, compactPayload, ownerStamp);
+ observeRemoteSendPush(channel, compactPayload);
log.warn(`forwardPush to ${shortId(dst)} sent compact payload after oversized ${channel} frame`);
} catch (retryErr) {
markForRecovery();
@@ -3128,7 +3132,8 @@ async function handleInvoke(
try {
result = normalizeInvokeResultForWire(await resultPromise);
const executionWaitMs = Math.round(performance.now() - handlerStartedAt);
- if (executionWaitMs >= 1_000) {
+ // debug only: 300ms already shows up as a visible send delay over the relay.
+ if (executionWaitMs >= 300) {
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} stagesMs=${JSON.stringify(timing.stages)}`);
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 1dfdb0c5ee..bba8d1cc27 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -18,6 +18,7 @@ import { tryPeerInvoke, stopFilePeers } from './filePeer';
import { assertBackgroundLinkAccepted, linkOpenCapabilities } from './backgroundLink';
import { deviceName, initializeDeviceName } from './deviceName';
import { desktopTransferCodec } from './transferCodec';
+import { desktopInvokeTransferMetrics } from './invokeTransferMetrics';
import { watchNetworkChanges } from './networkChanges';
import path from 'node:path';
import { app, BrowserWindow } from 'electron';
@@ -751,6 +752,8 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
// peer ACK 耗尽时,幂等的 local-db 读请求交给 linkRecovery 快速重开并只重试一次;
// 写请求与长执行请求保持原有 in-flight 语义,避免重复副作用。
peerResetReadRetry: true,
+ // debug 日志开启时按 channel 统计回包字节,作为流量治理前后的对照。
+ invokeMetrics: desktopInvokeTransferMetrics,
});
responsivenessTracker = createResponsivenessTracker({
diff --git a/apps/desktop/src/main/device-link/invokeTransferMetrics.ts b/apps/desktop/src/main/device-link/invokeTransferMetrics.ts
new file mode 100644
index 0000000000..c1c51a3978
--- /dev/null
+++ b/apps/desktop/src/main/device-link/invokeTransferMetrics.ts
@@ -0,0 +1,72 @@
+/**
+ * 控制端 invoke 回包字节统计(debug 级,每 30s 一行)。
+ *
+ * 只在 debug 日志开启时计数:统计需要把回包再序列化一次,默认 info 级别不付这份开销。
+ * 只记 channel(allowlist 内的固定名)与字节数,不记参数、内容或对端身份。
+ */
+import { REMOTE_INVOKE_ALLOWLIST } from '@cindy/device-link';
+import { createLogger, getLogLevel } from '../logger';
+
+const log = createLogger('device-link-transfer');
+
+const FLUSH_MS = 30_000;
+const TOP_CHANNELS = 8;
+
+interface Counters {
+ results: number;
+ bytes: number;
+ notModified: number;
+ gzip: number;
+}
+
+const counters = new Map<string, Counters>();
+let startedAt = 0;
+let timer: ReturnType<typeof setTimeout> | undefined;
+
+function flush(): void {
+ timer = undefined;
+ if (counters.size === 0) return;
+ const ranked = [...counters].sort((a, b) => b[1].bytes - a[1].bytes);
+ let totalBytes = 0;
+ let totalResults = 0;
+ for (const [, c] of ranked) {
+ totalBytes += c.bytes;
+ totalResults += c.results;
+ }
+ log.debug('transport bytes', {
+ elapsedMs: Date.now() - startedAt,
+ results: totalResults,
+ bytes: totalBytes,
+ channels: Object.fromEntries(ranked.slice(0, TOP_CHANNELS)),
+ ...(ranked.length > TOP_CHANNELS ? { channelsOmitted: ranked.length - TOP_CHANNELS } : {}),
+ });
+ counters.clear();
+}
+
+export const desktopInvokeTransferMetrics = {
+ enabled(): boolean {
+ const level = getLogLevel();
+ return level === 'debug' || level === 'trace';
+ },
+ record(event: {
+ channel: string;
+ phase: 'sent' | 'result';
+ payloadBytes?: number;
+ notModified?: boolean;
+ gzip?: boolean;
+ }): void {
+ if (event.phase !== 'result') return;
+ const channel = REMOTE_INVOKE_ALLOWLIST.has(event.channel) ? event.channel : 'UNKNOWN';
+ const entry = counters.get(channel) ?? { results: 0, bytes: 0, notModified: 0, gzip: 0 };
+ entry.results++;
+ entry.bytes += event.payloadBytes ?? 0;
+ if (event.notModified) entry.notModified++;
+ if (event.gzip) entry.gzip++;
+ counters.set(channel, entry);
+ if (!timer) {
+ startedAt = Date.now();
+ timer = setTimeout(flush, FLUSH_MS);
+ timer.unref?.();
+ }
+ },
+};
diff --git a/apps/desktop/src/main/device-link/remoteSendTrace.ts b/apps/desktop/src/main/device-link/remoteSendTrace.ts
new file mode 100644
index 0000000000..c4faa3873f
--- /dev/null
+++ b/apps/desktop/src/main/device-link/remoteSendTrace.ts
@@ -0,0 +1,101 @@
+/**
+ * 被控端远程发送耗时追踪(只写 debug 日志,不参与任何投递判定)。
+ *
+ * 一条远程消息在被控端经过四个点:enqueue 收到 → coordinator 收下 → 用户行落库 →
+ * messages:created 推送发出。前两点在 enqueue handler 内,后两点发生在队列派发
+ * 之后,已经脱离那次 invoke 的调用栈,所以按 clientId 记一张有界表,在推送转发处
+ * 收尾输出一行。clientId 只记前 8 位;不记正文、设备名或会话内容。
+ */
+import { createLogger } from '../logger';
+
+const log = createLogger('remote-send-trace');
+
+const MAX_TRACES = 200;
+const TRACE_TTL_MS = 5 * 60_000;
+
+interface Trace {
+ sessionId: string;
+ receivedAt: number;
+ acceptedAt?: number;
+ stages: Record<string, number>;
+}
+
+const traces = new Map<string, Trace>();
+
+function shortId(value: string): string {
+ return value.slice(0, 8);
+}
+
+function prune(now: number): void {
+ for (const [clientId, trace] of traces) {
+ if (traces.size <= MAX_TRACES && now - trace.receivedAt < TRACE_TTL_MS) break;
+ traces.delete(clientId);
+ }
+}
+
+/** enqueue handler 入口:返回打点函数与收尾函数,调用方只在远程调用时使用。 */
+export function beginRemoteSendTrace(
+ sessionId: string,
+ clientId: string,
+): {
+ stage(name: string): void;
+ accepted(): void;
+ finish(outcome: string): void;
+} {
+ const startedAt = performance.now();
+ const stages: Record<string, number> = {};
+ let last = startedAt;
+ let done = false;
+ return {
+ stage(name) {
+ const now = performance.now();
+ stages[name] = Math.round(now - last);
+ last = now;
+ },
+ accepted() {
+ const now = Date.now();
+ prune(now);
+ traces.delete(clientId);
+ traces.set(clientId, {
+ sessionId,
+ receivedAt: now - Math.round(performance.now() - startedAt),
+ acceptedAt: now,
+ stages: { ...stages },
+ });
+ },
+ finish(outcome) {
+ if (done) return;
+ done = true;
+ log.debug(
+ `remote enqueue timing client=${shortId(clientId)} outcome=${outcome}` +
+ ` totalMs=${Math.round(performance.now() - startedAt)} stagesMs=${JSON.stringify(stages)}`,
+ );
+ },
+ };
+}
+
+/** 推送转发处调用:远程发送的用户行第一次推出去时输出整条链路的耗时。 */
+export function observeRemoteSendPush(channel: string, payload: unknown): void {
+ if (channel !== 'local-db:messages:created' || traces.size === 0) return;
+ if (!payload || typeof payload !== 'object') return;
+ const message = (payload as { message?: unknown }).message;
+ if (!message || typeof message !== 'object') return;
+ const { clientId, role } = message as { clientId?: unknown; role?: unknown };
+ if (role !== 'user' || typeof clientId !== 'string') return;
+ const trace = traces.get(clientId);
+ if (!trace) return;
+ traces.delete(clientId);
+ const now = Date.now();
+ log.debug(
+ `remote send pushed client=${shortId(clientId)}` +
+ ` enqueueMs=${(trace.acceptedAt ?? trace.receivedAt) - trace.receivedAt}` +
+ ` acceptedToPushMs=${now - (trace.acceptedAt ?? trace.receivedAt)}` +
+ ` totalMs=${now - trace.receivedAt}` +
+ ` stagesMs=${JSON.stringify(trace.stages)}`,
+ );
+}
+
+/** 测试与账号切换时清空。 */
+export function resetRemoteSendTraces(): void {
+ traces.clear();
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index f14a7c69a2..394c28827e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -389,6 +389,7 @@ describe('INPUT_ENQUEUE crash-restored remote Worker pause', () => {
getResolvedMainLocale: () => 'zh-CN',
getInputSessionRow: async () => ({ clearedAt: null }),
getMakerIfReady: () => null,
+ beginRemoteSendTrace: noop,
remoteInputClientIdWasPersisted: () => false,
hasInputDeliveryCancellation: () => false,
materializeQueuedOssAttachmentsDeferred: (_sid: string, item: AgentInputQueuedMessage) => ({ item }),
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentPrewarm.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentPrewarm.test.ts
new file mode 100644
index 0000000000..edcb7aaa04
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentPrewarm.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createAgentPrewarmer,
+ isAgentPrewarmEligible,
+ type AgentPrewarmDeps,
+ type AgentPrewarmSessionRow,
+} from '../agentPrewarm.js';
+
+function harness(maxWarm = 2) {
+ const timers = new Map<number, () => void>();
+ let nextTimer = 0;
+ const start = vi.fn<AgentPrewarmDeps['start']>(async () => true);
+ const closeIfUnused = vi.fn<AgentPrewarmDeps['closeIfUnused']>(async () => {});
+ const prewarmer = createAgentPrewarmer(
+ {
+ start,
+ closeIfUnused,
+ setTimer: (fn) => {
+ const id = ++nextTimer;
+ timers.set(id, fn);
+ return id;
+ },
+ clearTimer: (id) => timers.delete(id as number),
+ log: { info: vi.fn(), warn: vi.fn() },
+ },
+ { maxWarm, idleMs: 1_000 },
+ );
+ const fireAll = () => {
+ const pending = [...timers.values()];
+ timers.clear();
+ for (const fn of pending) fn();
+ };
+ return { prewarmer, start, closeIfUnused, fireAll, timers };
+}
+
+describe('Agent prewarm lifecycle', () => {
+ it('keeps at most the newest unused runtimes and closes the oldest', async () => {
+ const { prewarmer, closeIfUnused } = harness(2);
+ for (const id of ['a', 'b', 'c']) await prewarmer.request(id, {});
+ expect(prewarmer.warmSessionIds()).toEqual(['b', 'c']);
+ expect(closeIfUnused.mock.calls.map(([id]) => id)).toEqual(['a']);
+ });
+
+ it('closes an unused runtime after the idle window but never one a send has used', async () => {
+ const { prewarmer, closeIfUnused, fireAll, start } = harness();
+ await prewarmer.request('idle', {});
+ await prewarmer.request('used', {});
+ // Typing again in a warm task only extends its window; it does not start twice.
+ await expect(prewarmer.request('idle', {})).resolves.toBe('warm');
+ prewarmer.markUsed('used');
+ fireAll();
+ await Promise.resolve();
+ expect(start).toHaveBeenCalledTimes(2);
+ expect(closeIfUnused.mock.calls.map(([id]) => id)).toEqual(['idle']);
+ expect(prewarmer.warmSessionIds()).toEqual([]);
+ });
+
+ it('does not track a task whose runtime was not started by prewarm', async () => {
+ const { prewarmer, start, timers } = harness();
+ start.mockResolvedValueOnce(false);
+ start.mockRejectedValueOnce(new Error('credential switch busy'));
+ await expect(prewarmer.request('live', {})).resolves.toBe('skipped');
+ await expect(prewarmer.request('broken', {})).resolves.toBe('skipped');
+ expect(prewarmer.warmSessionIds()).toEqual([]);
+ expect(timers.size).toBe(0);
+ });
+ it('does not hand a runtime to idle reclaim when a send took it over while it was starting', async () => {
+ const { prewarmer, closeIfUnused, fireAll, start, timers } = harness();
+ let finishStart!: (started: boolean) => void;
+ start.mockImplementationOnce(() => new Promise<boolean>((resolve) => (finishStart = resolve)));
+ const pending = prewarmer.request('racing', {});
+ prewarmer.markUsed('racing');
+ finishStart(true);
+ await pending;
+ expect(prewarmer.warmSessionIds()).toEqual([]);
+ expect(timers.size).toBe(0);
+ fireAll();
+ await Promise.resolve();
+ expect(closeIfUnused).not.toHaveBeenCalled();
+ // A later prewarm of the same task starts tracking normally again.
+ await prewarmer.request('racing', {});
+ expect(prewarmer.warmSessionIds()).toEqual(['racing']);
+ });
+ it('counts runtimes that are still starting against the cap', async () => {
+ const { prewarmer, start } = harness(2);
+ const finish: Array<(started: boolean) => void> = [];
+ start.mockImplementation(() => new Promise<boolean>((resolve) => finish.push(resolve)));
+ const outcomes = ['a', 'b', 'c', 'd'].map((id) => prewarmer.request(id, {}));
+ // Only two may be launched at once; the rest are skipped, not queued behind them.
+ expect(start).toHaveBeenCalledTimes(2);
+ await expect(outcomes[2]).resolves.toBe('skipped');
+ await expect(outcomes[3]).resolves.toBe('skipped');
+ finish.forEach((resolve) => resolve(true));
+ await Promise.all(outcomes);
+ expect(prewarmer.warmSessionIds()).toEqual(['a', 'b']);
+ });
+ describe('eligibility', () => {
+ const row = (patch: Partial<AgentPrewarmSessionRow> = {}): AgentPrewarmSessionRow => ({
+ status: 'active',
+ source: 'desktop',
+ workingDir: '/repo',
+ remoteHostId: null,
+ agentDeviceId: null,
+ orcaRole: null,
+ sdkSessionId: 'native-1',
+ ...patch,
+ });
+
+ it('prewarms only a task the user has already sent in, so typing alone never runs a directory\'s hooks', () => {
+ expect(isAgentPrewarmEligible(row())).toBe(true);
+ expect(isAgentPrewarmEligible(row({ sdkSessionId: null }))).toBe(false);
+ });
+
+ it.each([
+ { status: 'archived' },
+ { source: 'scheduler' },
+ { workingDir: null },
+ { remoteHostId: 'ssh-1' },
+ { agentDeviceId: 'other-computer' },
+ { orcaRole: 'worker' },
+ ])('skips %o', (patch) => {
+ expect(isAgentPrewarmEligible(row(patch))).toBe(false);
+ });
+
+ it('skips a missing task', () => {
+ expect(isAgentPrewarmEligible(undefined)).toBe(false);
+ });
+ });
+ it('lets a send that arrives while the close is queued keep the runtime', async () => {
+ const { prewarmer, closeIfUnused, fireAll } = harness();
+ let stillUnused!: () => boolean;
+ closeIfUnused.mockImplementationOnce(async (_id, check) => {
+ stillUnused = check;
+ });
+ await prewarmer.request('racing', {});
+ fireAll();
+ await Promise.resolve();
+ // The idle close is queued behind the send lock; the send marks the runtime used first.
+ expect(stillUnused()).toBe(true);
+ prewarmer.markUsed('racing');
+ expect(stillUnused()).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index cbce21219e..60ad976382 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -4193,3 +4193,28 @@ describe('repeatable environment notes are sent only when they change', () => {
expect(sentAt(session, 1)).toBe(withUiLanguageNote('b'));
});
});
+
+describe('Agent prewarm', () => {
+ it('starts the runtime a first send would start, and the send then reuses it', async () => {
+ let live: ReturnType<typeof createSession> | undefined;
+ const { deps } = createDeps({
+ getSession: vi.fn(() => live),
+ bootstrapSession: vi.fn(async (opts: MakerSessionCreateOpts) => {
+ live = createSession({ id: opts.id, agentKind: opts.agentKind as AgentKind, workDir: opts.workingDir });
+ return { session: live, didInjectOrcaInstructions: false, didInjectProjectContext: false };
+ }),
+ });
+ const transaction = createMakerSendTransaction(deps);
+ const createOpts = { id: 'session-1', agentKind: 'claude-code', workingDir: '/repo', userPrompt: 'mine' } as MakerSessionCreateOpts;
+
+ await expect(transaction.prewarmSession('session-1', createOpts)).resolves.toBe(true);
+ // Already warm: nothing new to start.
+ await expect(transaction.prewarmSession('session-1', createOpts)).resolves.toBe(false);
+ await expect(transaction.sendToAgentAccepted('session-1', 'hello', createOpts))
+ .resolves.toMatchObject({ accepted: true });
+
+ expect(deps.bootstrapSession).toHaveBeenCalledOnce();
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({ userPrompt: 'mine', workingDir: '/repo' }));
+ expect(live?.send).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/agentPrewarm.ts b/apps/desktop/src/main/maker-ipc/agentPrewarm.ts
new file mode 100644
index 0000000000..c08bad791a
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/agentPrewarm.ts
@@ -0,0 +1,182 @@
+/**
+ * Agent 预热:用户在任务输入框开始打字时,提前启动这个任务的 Agent 进程,把
+ * 1–4 秒的冷启动藏进打字时间里。本机任务与远程控制端的任务走同一入口。
+ *
+ * 只管理「预热出来、还没被真正发送用过」的进程:
+ * - 同时最多保留 MAX_WARM 个,超出时关掉最早的那个;
+ * - 预热后 IDLE_MS 内没有发送就关掉(用户继续打字会顺延);
+ * - 一旦有真实发送(markUsed),进程归正常生命周期管理,这里不再碰它。
+ * 启动本身复用发送路径的懒创建,失败只记日志,下一次发送照常冷启动。
+ */
+
+export const AGENT_PREWARM_MAX_WARM = 2;
+/** Ordinary user-owned tasks only; other sources keep their own start-up routing and checks. */
+export const AGENT_PREWARM_SESSION_SOURCES: ReadonlySet<string> = new Set([
+ 'user',
+ 'desktop',
+ 'plugin',
+ 'side-chat',
+]);
+
+export interface AgentPrewarmSessionRow {
+ status: string | null;
+ source: string | null;
+ workingDir: string | null;
+ remoteHostId: string | null;
+ agentDeviceId: string | null;
+ orcaRole: string | null;
+ sdkSessionId: string | null;
+}
+
+/**
+ * Whether a task's runtime may be started before the user sends.
+ *
+ * Starting a runtime loads the project's own settings (hooks, MCP servers), which is
+ * what a send does too — but a send is the user's explicit act. Typing alone is not
+ * consent to run a directory's code, so only tasks the user has already sent in
+ * (they have a native session id from a real turn) are prewarmed; a task that was
+ * never sent, e.g. one pointing at a freshly cloned or imported directory, waits
+ * for its first real send.
+ */
+export function isAgentPrewarmEligible(row: AgentPrewarmSessionRow | undefined): boolean {
+ return (
+ !!row &&
+ row.status === 'active' &&
+ !!row.workingDir &&
+ !row.remoteHostId &&
+ !row.agentDeviceId &&
+ !row.orcaRole &&
+ AGENT_PREWARM_SESSION_SOURCES.has(row.source ?? 'user') &&
+ !!row.sdkSessionId
+ );
+}
+
+export const AGENT_PREWARM_IDLE_MS = 10 * 60_000;
+
+export type AgentPrewarmOutcome = 'started' | 'warm' | 'skipped';
+
+export interface AgentPrewarmDeps {
+ /** Start the runtime if this task has none; true only when a new one was started. */
+ start(sessionId: string, createOpts: unknown): Promise<boolean>;
+ /** Close an unused prewarmed runtime; must leave a runtime that is doing work alone. */
+ closeIfUnused(sessionId: string, stillUnused: () => boolean): Promise<void>;
+ setTimer(fn: () => void, ms: number): unknown;
+ clearTimer(handle: unknown): void;
+ log: {
+ info(message: string, fields?: Record<string, unknown>): void;
+ warn(message: string, fields?: Record<string, unknown>): void;
+ };
+}
+
+export function createAgentPrewarmer(
+ deps: AgentPrewarmDeps,
+ opts: { maxWarm?: number; idleMs?: number } = {},
+) {
+ const maxWarm = opts.maxWarm ?? AGENT_PREWARM_MAX_WARM;
+ const idleMs = opts.idleMs ?? AGENT_PREWARM_IDLE_MS;
+ /** Insertion order is age order: the first key is the oldest unused runtime. */
+ const warm = new Map<string, unknown>();
+ const starting = new Map<string, Promise<AgentPrewarmOutcome>>();
+ /** A real send took over while this task's prewarm was still starting. */
+ const usedWhileStarting = new Set<string>();
+ /** Released but not yet closed: the close may still lose to a send that arrives first. */
+ const releasing = new Set<string>();
+
+ const untrack = (sessionId: string): boolean => {
+ const timer = warm.get(sessionId);
+ if (!warm.delete(sessionId)) return false;
+ deps.clearTimer(timer);
+ return true;
+ };
+
+ const release = (sessionId: string, reason: 'idle' | 'evicted') => {
+ if (!untrack(sessionId)) return;
+ releasing.add(sessionId);
+ // The caller closes under the task's send lock and rechecks `stillUnused` there,
+ // so a send either wins (the runtime is kept) or the close finishes first.
+ void deps
+ .closeIfUnused(sessionId, () => releasing.has(sessionId))
+ .then(
+ () => deps.log.info('agent prewarm released', { sessionId, reason }),
+ (error: unknown) =>
+ deps.log.warn('agent prewarm release failed', {
+ sessionId,
+ reason,
+ error: error instanceof Error ? error.message : String(error),
+ }),
+ )
+ .finally(() => releasing.delete(sessionId));
+ };
+
+ const arm = (sessionId: string) => {
+ const previous = warm.get(sessionId);
+ if (previous !== undefined) deps.clearTimer(previous);
+ warm.delete(sessionId);
+ warm.set(
+ sessionId,
+ deps.setTimer(() => release(sessionId, 'idle'), idleMs),
+ );
+ };
+
+ return {
+ request(sessionId: string, createOpts: unknown): Promise<AgentPrewarmOutcome> {
+ const pending = starting.get(sessionId);
+ if (pending) return pending;
+ if (warm.has(sessionId)) {
+ // Still typing in the same task: keep its runtime for another full window.
+ arm(sessionId);
+ return Promise.resolve('warm');
+ }
+ // Tasks that are still starting count against the cap too, so a burst of
+ // requests can never launch more than `maxWarm` runtimes at once: make room
+ // by releasing the oldest unused one, or skip when only starts are in flight.
+ while (warm.size + starting.size >= maxWarm) {
+ const oldest = warm.keys().next().value;
+ if (oldest === undefined) return Promise.resolve('skipped');
+ release(oldest, 'evicted');
+ }
+ const run = (async (): Promise<AgentPrewarmOutcome> => {
+ try {
+ if (!(await deps.start(sessionId, createOpts))) return 'skipped';
+ } catch (error) {
+ deps.log.warn('agent prewarm failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return 'skipped';
+ }
+ if (usedWhileStarting.delete(sessionId)) {
+ // The send already owns this runtime; never hand it to idle reclaim.
+ deps.log.info('agent prewarm taken over by send', { sessionId });
+ return 'started';
+ }
+ arm(sessionId);
+ deps.log.info('agent prewarm started', { sessionId, warm: warm.size });
+ while (warm.size > maxWarm) {
+ const oldest = warm.keys().next().value;
+ if (oldest === undefined || oldest === sessionId) break;
+ release(oldest, 'evicted');
+ }
+ return 'started';
+ })().finally(() => {
+ usedWhileStarting.delete(sessionId);
+ if (starting.get(sessionId) === run) starting.delete(sessionId);
+ });
+ starting.set(sessionId, run);
+ return run;
+ },
+ /** A real send now owns this runtime; prewarm bookkeeping must not close it. */
+ markUsed(sessionId: string): void {
+ untrack(sessionId);
+ releasing.delete(sessionId);
+ if (starting.has(sessionId)) usedWhileStarting.add(sessionId);
+ },
+ /** Account switch: the old owner's runtimes are torn down elsewhere. */
+ reset(): void {
+ for (const sessionId of [...warm.keys()]) untrack(sessionId);
+ },
+ warmSessionIds(): string[] {
+ return [...warm.keys()];
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 95df22c4b5..e7454e0928 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -33,6 +33,11 @@ export const MAKER_INVOKE = {
SESSION_DISABLE_ORCA: 'maker:session:disable-orca',
/** renderer 回填「该会话是否真的在 turn 中」的权威运行态(#4513 中断横幅假阳性)。 */
SESSION_TURN_ACTIVE: 'maker:session:turn-active',
+ /**
+ * 输入框开始打字时提前启动该任务的 Agent(尽力而为,无返回约定之外的副作用)。
+ * 本机 renderer 与 device-link 控制端共用;旧被控端没有该 channel 时控制端静默忽略。
+ */
+ SESSION_PREWARM: 'maker:session:prewarm',
CLOSE_SESSION: 'maker:close-session',
/**
* 单条 user / assistant 消息本地内容删除。保留后续可见消息,但清当前原生
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index e6b552ded2..531eb5d24c 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -586,6 +586,13 @@ export interface MakerSendTransaction {
createOpts?: unknown,
sendOpts?: unknown,
): Promise<DesktopMakerSendResult>;
+ /**
+ * Start the Agent runtime the next send would otherwise start lazily, using
+ * the same bootstrap path. `createOpts` must already be reconciled with the
+ * task row. Returns false when a runtime already exists or startup failed;
+ * the next send then follows its normal path.
+ */
+ prewarmSession(sessionId: string, createOpts: CreateOpts): Promise<boolean>;
}
type ResolveSessionResult =
@@ -1009,6 +1016,11 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
}
return {
+ async prewarmSession(sessionId, createOpts) {
+ if (deps.getSession(sessionId)) return false;
+ const lazy = await lazyCreateSession(sessionId, createOpts);
+ return lazy.kind === 'session';
+ },
async sendToAgentAccepted(
sessionId,
message,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 2132346b9b..c29a61c2b8 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -920,6 +920,7 @@ import {
stampTrustedDesktopQueuedOrigin,
TRUSTED_DESKTOP_QUEUE_ORIGIN,
} from './makerSendTransaction.js';
+import { createAgentPrewarmer, isAgentPrewarmEligible } from './agentPrewarm.js';
import { findLatestAssistantTranscriptUuid } from './latestAssistantTranscriptUuid.js';
import {
installDesktopInteractionHandler,
@@ -1332,6 +1333,7 @@ import {
readDeviceLinkInvokeSourceDevice,
runOutsideDeviceLinkInvokeContext,
} from '../device-link/invoke-context.js';
+import { beginRemoteSendTrace } from '../device-link/remoteSendTrace.js';
import { stampSharedTaskInput } from './sharedTaskInput.js';
import { createSharedTaskContextUsageGuard } from './sharedTaskContextUsage.js';
import { createSharedTaskSettingGuard } from './sharedTaskSetting.js';
@@ -16747,7 +16749,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
}));
- const { sendToAgentAccepted: sendToAgentAcceptedUnlocked } = createMakerSendTransaction({
+ const {
+ sendToAgentAccepted: sendToAgentAcceptedUnlocked,
+ prewarmSession: prewarmSessionRuntime,
+ } = createMakerSendTransaction({
restoreArchivedSessionForSend,
prepareProductTurn: (sessionId) => {
const dispatch = prepareUpstreamMergeTurn(sessionId);
@@ -17057,6 +17062,54 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
log,
});
+ // 输入框开始打字时预热 Agent(本机与 device-link 控制端共用)。只覆盖用户自己的普通
+ // 任务、且 Agent 在本机运行;Bot / IM / 定时 / 审查 / 共享 / 协同 / 远程主机等任务的
+ // 启动另有专门的路由与权限检查,仍由真实发送处理。启动走发送路径的同一个懒创建,
+ // 并在同一把会话发送锁里执行,真实发送不会与预热并发重复启动。
+ const agentPrewarmer = createAgentPrewarmer({
+ start: (sessionId, createOpts) => withSendToSessionLock(sessionId, async () => {
+ if (maker.getSession(sessionId)) return false;
+ if (agentSwitchPending.get(sessionId) || cindyMakeManager.isTaskPreparing(sessionId)) return false;
+ // Queued work starts the runtime itself through the normal drain.
+ if (agentInputCoordinatorHolder?.hasPendingQueuedWork(sessionId)) return false;
+ const [row] = await getDbClient().drizzle
+ .select({
+ status: sessions.status,
+ source: sessions.source,
+ workingDir: sessions.workingDir,
+ remoteHostId: sessions.remoteHostId,
+ agentDeviceId: sessions.agentDeviceId,
+ orcaRole: sessions.orcaRole,
+ sdkSessionId: sessions.sdkSessionId,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (!isAgentPrewarmEligible(row)) return false;
+ const co = buildCreateOptsWithStderr({ ...(createOpts as CreateOpts), id: sessionId });
+ await reconcileCreateOptsAgainstDb(sessionId, co);
+ if (co.remoteHostId || co.agentDeviceId) return false;
+ return prewarmSessionRuntime(sessionId, co);
+ }),
+ // Runs under the send lock: a send that got there first has marked the runtime used
+ // (and its turn is running), one that arrives later waits for the close to finish and
+ // then cold-starts, instead of meeting a runtime that is half closed.
+ closeIfUnused: (sessionId, stillUnused) => withSendToSessionLock(sessionId, async () => {
+ if (!stillUnused()) return;
+ if (agentInputCoordinatorHolder?.hasPendingQueuedWork(sessionId)) return;
+ const live = maker.getSession(sessionId);
+ if (!live || live.isTurnRunning()) return;
+ await live.closeIfIdle();
+ }),
+ setTimer: (fn, ms) => {
+ const timer = setTimeout(fn, ms);
+ timer.unref?.();
+ return timer;
+ },
+ clearTimer: (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),
+ log,
+ });
+
// Host-only hints belong to the dispatched input, not a persistent session cache.
// The fallback transaction still rechecks the authoritative Bot link and chain.
const botFallbackInputs = new WeakSet<object>();
@@ -17067,6 +17120,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const sendToAgentAccepted: typeof sendToAgentAcceptedUnlocked = async (...args) => {
const [sessionId] = args;
if (typeof sessionId !== 'string') return await sendToAgentAcceptedUnlocked(...args);
+ agentPrewarmer.markUsed(sessionId);
if (cindyMakeManager.isTaskPreparing(sessionId) && (args[3] as Record<PropertyKey, unknown> | undefined)?.[CINDY_MAKE_TASK_DISPATCH] !== true) {
throwIpcError('PRECONDITION_FAILED', 'Cindy Make is still preparing this task');
}
@@ -17871,6 +17925,21 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
);
+ // 尽力而为:立即返回,启动在后台进行;不支持、已在运行或启动失败都只是下一次发送照常冷启动。
+ ipcMain.handle(
+ MAKER_INVOKE.SESSION_PREWARM,
+ async (event, sessionId: unknown, createOpts?: unknown): Promise<{ accepted: boolean }> => {
+ const sid = requireSessionId(sessionId);
+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);
+ if (getDeviceLinkInvokeContext()?.sharedTask) return { accepted: false };
+ if (!createOpts || typeof createOpts !== 'object' || Array.isArray(createOpts)) {
+ throwIpcError('INVALID_PARAMS', 'createOpts required');
+ }
+ void agentPrewarmer.request(sid, createOpts);
+ return { accepted: true };
+ },
+ );
+
/**
* Reconcile the in-memory turn boundary after a vendor abort/close when the
* normal terminal event was lost. The vendor Session is authoritative for
@@ -19824,6 +19893,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await withSessionPermissionChange(sid, async () => undefined);
if (!inputOwner || inputOwner !== getCurrentDbClientSnapshot()) throwIpcError('PRECONDITION_FAILED', 'Account changed before input');
const parsed = await prepareSharedTaskInput(sid, requireQueuedMessage(item));
+ // debug 日志:远程发送在被控端各阶段的耗时,不影响任何判定。
+ const sendTrace = deviceLinkInvoke ? beginRemoteSendTrace(sid, parsed.clientId) : undefined;
if (parsed.durableDelivery) await awaitAgentInputQueueSnapshotPersistence(sid);
assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);
const clearBoundaryPrecondition = readRemoteInputClearBoundaryPrecondition(opts);
@@ -19847,6 +19918,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, inputSessionRow);
}
assertCurrentInputGeneration();
+ sendTrace?.stage('gate');
// 恢复先于入队:普通新输入保持 FIFO;「继续任务」由 coordinator 在完整旧队列
// 恢复后再明确插到队首,避免恢复竞态把它重新压到后面。
const restoreQueue = inputCoordinator.ensureQueueRestored(sid);
@@ -19862,17 +19934,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
inputSessionRow = await getInputSessionRow(sid);
inputCoordinator.observeClearBoundary(sid, inputSessionRow.clearedAt);
assertExpectedRemoteInputClearBoundary(sid, clearBoundaryPrecondition, inputSessionRow);
+ sendTrace?.finish('already-persisted');
return inputCoordinator.getProjection(sid);
}
} else {
await restoreQueue.catch(() => undefined);
}
assertCurrentInputGeneration();
+ sendTrace?.stage('restore');
// A concurrent weak-link resend may already own this clientId in the
// coordinator. Return the current projection before materialising a new
// copy of its attachments.
if (inputCoordinator.hasKnownClientId(sid, parsed.clientId)) {
if (parsed.durableDelivery) await awaitAgentInputQueueSnapshotPersistence(sid);
+ sendTrace?.finish('known');
return inputCoordinator.getProjection(sid);
}
const materialized = await materializeQueuedOssAttachmentsDeferred(sid, parsed);
@@ -19913,6 +19988,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
);
assertCurrentInputGeneration();
+ sendTrace?.stage('prepare');
const commitAutoTitle = await prepareDeviceLinkAutoTitle(sid, queued);
assertCurrentInputGeneration();
if (deviceLinkInvoke) {
@@ -19923,6 +19999,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
assertCurrentInputGeneration();
assertRemoteInputClearNotInFlight(sid, deviceLinkInvoke);
+ sendTrace?.stage('recheck');
if (parsed.durableDelivery) {
await awaitAgentInputQueueSnapshotPersistence(sid);
@@ -19933,8 +20010,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await materialized.cleanupBeforeAcceptance?.();
if (attachmentOwnerId) await discardSpecificQueuedAttachmentOwnership(sid, parsed.clientId, attachmentOwnerId);
await awaitAgentInputQueueSnapshotPersistence(sid);
+ sendTrace?.finish(persisted ? 'already-persisted' : 'cancelled');
return inputCoordinator.getProjection(sid);
}
+ sendTrace?.stage('dedupe');
}
// 「继续任务」durable ack 延后到 vendor dispatch 成功(onDispatchedUserTurn):
@@ -19957,15 +20036,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await discardSpecificQueuedAttachmentOwnership(sid, parsed.clientId, attachmentOwnerId);
}
if (parsed.durableDelivery) await awaitAgentInputQueueSnapshotPersistence(sid);
+ sendTrace?.finish('duplicate');
return projection;
}
acceptedByCoordinator = true;
+ sendTrace?.stage('coordinator');
+ sendTrace?.accepted();
if (attachmentOwnerId) {
queuedAttachmentOwnership.activateCurrentOwner(sid, parsed.clientId, attachmentOwnerId);
}
markQueuedAttachmentDurableAfterSnapshot(sid, parsed.clientId, attachmentOwnerId);
commitAutoTitle();
if (parsed.durableDelivery) await awaitAgentInputQueueSnapshotPersistence(sid);
+ sendTrace?.stage('snapshot');
+ sendTrace?.finish('accepted');
return projection;
} catch (err) {
if (!acceptedByCoordinator) {
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 008cc9e452..df811c2a28 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -7242,6 +7242,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
// preload 不重复枚举 (避免 capabilities 加新值时这里也要改)。
setEffort: (sessionId: string, effort: string): Promise<void> =>
ipcRenderer.invoke('maker:set-effort', sessionId, effort),
+ // 输入框开始打字时提前启动 Agent;尽力而为,main 决定是否真的启动。
+ prewarmSession: (sessionId: string, createOpts: unknown): Promise<{ accepted: boolean }> =>
+ ipcRenderer.invoke('maker:session:prewarm', sessionId, createOpts),
setPermissionMode: (sessionId: string, mode: string): Promise<void> =>
ipcRenderer.invoke('maker:set-permission-mode', sessionId, mode),
getPluginWriteAccessRecovery: (sessionId: string): Promise<{available: boolean}> =>
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index a82ae08f64..497479db67 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -526,6 +526,11 @@ interface ChatInputProps {
annotationBurnFailure?: 'abort';
},
) => boolean | void | Promise<boolean | void>;
+ /**
+ * 用户在已有任务的输入框里输入了内容(不含草稿恢复、语音回填、发送后清空等程序写入)。
+ * 父组件据此提前启动 Agent;每次按键都会调用,节流由接收方负责。
+ */
+ onComposerTyping?: () => void;
/** Session ID for binding workingDir. When absent, folder picker is hidden. */
sessionId?: string;
/**
@@ -1191,6 +1196,7 @@ function deriveSyntheticAtQuery(editor: Editor, anchor: number, rangeEnd: number
export function ChatInput({
onSend,
+ onComposerTyping,
sessionId,
runtimeAgentKind,
runtimeEffective,
@@ -1348,6 +1354,9 @@ export function ChatInput({
// handleKeyDown 与硬件动作订阅都是稳定闭包,经 ref 读当前值。
const promptPreviewInputGuardRef = useRef<() => boolean>(() => false);
const acceptPromptRecommendationRef = useRef<() => boolean>(() => false);
+ // 编辑器配置只创建一次,按键回调读最新的父组件回调。
+ const onComposerTypingRef = useRef(onComposerTyping);
+ onComposerTypingRef.current = onComposerTyping;
// session 切换时 ChatInput/Editor 会复用;推荐资格必须等目标草稿完成水合后再判断。
const [, setComposerHydrationGeneration] = useState(0);
// 完整输入框空判断:不仅检查 ProseMirror 文档是否为空,还检查附件、浏览器评论和语音稿。
@@ -2302,6 +2311,7 @@ export function ChatInput({
// dispatch / 语音回填时触发);IME 组合输入在 onUpdate 里补(见该处注释)。
handleTextInput: () => {
markComposerTypingActivity();
+ onComposerTypingRef.current?.();
return false; // 不拦截默认插入
},
attributes: {
@@ -2885,6 +2895,7 @@ export function ChatInput({
(ed.view.composing || transaction.getMeta('composition') === true)
) {
markComposerTypingActivity();
+ onComposerTypingRef.current?.();
}
// composer-draft-mount-race 修复 (issue #40):hydration 还没跑过 → 这次
// onUpdate 是 Tiptap mount 期间的初始触发(空 editor),不能写 store。
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 32d15222fe..ad70be0709 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -3864,6 +3864,18 @@ function CCAgentSessionContent({
[fastMode, insertSystemCard, remoteDeviceId, session, sessionId, t, updateSystemCardData],
);
+ // 开始打字时提前启动 Agent,把冷启动藏进打字时间(本机与远程任务相同)。
+ const handleComposerTyping = useCallback(() => {
+ if (readOnly || cindyMakeInputLocked || !sessionId || !session?.workingDir) return;
+ makerChatStore.prewarmSession(
+ sessionId,
+ session.model,
+ session.effort,
+ session.permissionMode,
+ session.workingDir,
+ );
+ }, [cindyMakeInputLocked, readOnly, session, sessionId]);
+
const handleSend = useCallback(
async (
message: string,
@@ -5786,6 +5798,7 @@ function CCAgentSessionContent({
/>
) : remoteMakeCards.handlesSession ? <SessionResourceCards state={remoteMakeCards} /> : undefined}
onSend={handleSend}
+ onComposerTyping={handleComposerTyping}
onBeforeVoiceInputStart={handleBeforeVoiceInputStart}
sessionId={sessionId}
ownsHardwareComposerActions={ownsHardwareTaskActions}
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 37612e3189..89339f208f 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -152,6 +152,7 @@ import {
dismissErrorMessageFor,
isRemoteSession,
isRemoteSessionSticky,
+ prewarmSessionFor,
type RoutableMaker,
} from '@/lib/makerTransport';
import {
@@ -177,6 +178,13 @@ import type { Effort } from '@/lib/userPreferences.types';
import { emitAutoTitlePreview, emitAutoTitlePreviewCleared, emitPatch } from '@/lib/sessionsBus';
import { clearSessionStarting, markSessionStarting } from '@/lib/sessionStartingStore';
import { createLogger } from '@/lib/logger';
+import {
+ traceRemoteSendAccepted,
+ traceRemoteSendDispatching,
+ traceRemoteSendDropped,
+ traceRemoteSendEcho,
+ traceRemoteSendRegistered,
+} from '@/lib/remoteSendTrace';
import {
markSessionAutomaticHistoryLoadCompleted,
readSessionScroll,
@@ -1676,6 +1684,7 @@ function registerRemoteOptimisticSend(
composerResolvedOptimistically: false,
};
remoteOptimisticSendRecords(sessionId, true)!.set(queued.clientId, record);
+ traceRemoteSendRegistered(queued.clientId);
const composerTransition = findRemoteOptimisticComposerTransition(
sessionId,
opts?.onRemoteOptimisticFailure,
@@ -1843,6 +1852,7 @@ function markRemoteOptimisticSendAccepted(
): void {
const record = remoteOptimisticSendRecords(sessionId)?.get(clientId);
if (!record) return;
+ traceRemoteSendAccepted(clientId);
record.accepted = true;
record.currentlyQueued = true;
record.phase = 'accepted';
@@ -8851,6 +8861,7 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
if (isBeforeOrAtRendererClearBoundary(sessionId, message.createdAt)) return;
const [mapped] = mapServerMessages([message]);
if (!mapped) return;
+ traceRemoteSendEcho(mapped.clientId, mapped.role);
clearRemoteOptimisticSend(sessionId, mapped.clientId);
const current = getOrCreateState(sessionId);
const existing = current.messages.find((candidate) => candidate.clientId === mapped.clientId);
@@ -11184,6 +11195,7 @@ async function dispatchRemoteOptimisticSend(
record.dispatching = true;
record.phase = 'dispatching';
record.attempt += 1;
+ traceRemoteSendDispatching(record.queued.clientId);
clearRemoteOptimisticRetryTimer(sessionId);
const operation = beginInputProjectionOperation(sessionId, record.deviceId);
@@ -11310,6 +11322,7 @@ async function dispatchRemoteOptimisticSend(
}
function settleRemoteOptimisticFailure(sessionId: string, clientId: string, error?: unknown): void {
+ traceRemoteSendDropped(clientId);
const record = remoteOptimisticSendRecords(sessionId)?.get(clientId);
if (record?.composerResolvedOptimistically && isDataOwnerGenerationCurrent(record.dataOwner)) {
try {
@@ -14154,6 +14167,47 @@ export function buildCreateOptsForCurrentSession(
};
}
+/** 同一任务连续打字只需偶尔提醒一次;任务所在电脑会在提醒时顺延预热进程的空闲回收。 */
+const PREWARM_REQUEST_INTERVAL_MS = 30_000;
+const lastPrewarmRequestAt = new Map<string, number>();
+
+/**
+ * 输入框开始打字:请任务所在电脑(本机或被控电脑)提前启动 Agent。只在任务空闲、
+ * 没有排队或在途发送时请求;createOpts 与下一次发送构造的相同,执行字段由任务所在
+ * 电脑按数据库校正。尽力而为,结果不影响发送。
+ */
+function prewarmSession(
+ sessionId: string,
+ model: string,
+ effort: string,
+ permissionMode: string,
+ workingDir: string,
+): void {
+ if (!sessionId || !workingDir) return;
+ const current = getOrCreateState(sessionId);
+ if (
+ current.agentStatus.isRunning ||
+ current.isStreaming ||
+ current.pendingQueue.length > 0 ||
+ current.agentSwitchIntent ||
+ remoteOptimisticSendRecords(sessionId)?.size
+ ) {
+ return;
+ }
+ const now = Date.now();
+ const last = lastPrewarmRequestAt.get(sessionId);
+ if (last !== undefined && now - last < PREWARM_REQUEST_INTERVAL_MS) return;
+ lastPrewarmRequestAt.set(sessionId, now);
+ const createOpts = buildCreateOptsForCurrentSession(
+ sessionId,
+ model,
+ effort,
+ permissionMode,
+ workingDir,
+ );
+ void prewarmSessionFor(sessionId, createOpts).catch(() => undefined);
+}
+
function touchSessionUserSend(sessionId: string, workingDir: string, wasFirst: boolean): void {
const sendAt = new Date();
const userSendAtIso = sendAt.toISOString();
@@ -18181,6 +18235,7 @@ export const makerChatStore = {
loadAroundMessage,
loadAroundMessageClientId,
sendMessage,
+ prewarmSession,
/** #2194: MessageStream 强 pin 门控——区分本端发送与外部注入的 user 消息。 */
isLocalSentUserMessage,
beginRemoteOptimisticComposerTransition,
diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.ts
index ff43d05308..cdb0079cef 100644
--- a/apps/desktop/src/renderer/lib/makerTransport.ts
+++ b/apps/desktop/src/renderer/lib/makerTransport.ts
@@ -390,6 +390,16 @@ export function makerApiFor(sessionId: string): RoutableMaker {
return deviceId ? makerApiForDevice(deviceId) : window.electronAPI.maker;
}
+/**
+ * 输入框开始打字时请任务所在电脑提前启动 Agent。尽力而为:旧被控端没有该 channel、
+ * 断线或拒绝都只意味着下一次发送照常冷启动,调用方不需要处理结果。
+ */
+export function prewarmSessionFor(sessionId: string, createOpts: unknown): Promise<unknown> {
+ const deviceId = getSessionDeviceId(sessionId);
+ if (deviceId) return invokeRemote(deviceId, 'maker:session:prewarm', [sessionId, createOpts]);
+ return window.electronAPI.maker.prewarmSession?.(sessionId, createOpts) ?? Promise.resolve(undefined);
+}
+
/**
* 粘滞归属版 maker 入口:曾解析到 deviceId 的会话,在 relay 瞬时重连清空注册表的窗口内
* 仍走隧道,不会退回本机。
diff --git a/apps/desktop/src/renderer/lib/remoteSendTrace.ts b/apps/desktop/src/renderer/lib/remoteSendTrace.ts
new file mode 100644
index 0000000000..3116d8c366
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/remoteSendTrace.ts
@@ -0,0 +1,72 @@
+/**
+ * 控制端远程发送耗时(debug 日志,不参与任何发送判定)。
+ *
+ * 一条远程消息记三个点:点击发送(乐观记录登记)→ 被控端收下(enqueue 成功)→
+ * 被控端落库的用户行回显。clientId 只记前 8 位,不记正文或设备身份。
+ */
+import { createLogger } from '@/lib/logger';
+
+const log = createLogger('remote-send-trace');
+
+const MAX_TRACES = 200;
+
+interface Trace {
+ registeredAt: number;
+ acceptedAt?: number;
+ dispatchStartedAt?: number;
+ attempts: number;
+}
+
+const traces = new Map<string, Trace>();
+
+function shortId(clientId: string): string {
+ return clientId.slice(0, 8);
+}
+
+export function traceRemoteSendRegistered(clientId: string): void {
+ traces.delete(clientId);
+ traces.set(clientId, { registeredAt: performance.now(), attempts: 0 });
+ while (traces.size > MAX_TRACES) {
+ const oldest = traces.keys().next().value;
+ if (oldest === undefined) break;
+ traces.delete(oldest);
+ }
+}
+
+export function traceRemoteSendDispatching(clientId: string): void {
+ const trace = traces.get(clientId);
+ if (!trace) return;
+ trace.attempts += 1;
+ trace.dispatchStartedAt = performance.now();
+}
+
+export function traceRemoteSendAccepted(clientId: string): void {
+ const trace = traces.get(clientId);
+ if (!trace || trace.acceptedAt !== undefined) return;
+ const now = performance.now();
+ trace.acceptedAt = now;
+ log.debug(
+ `remote send accepted client=${shortId(clientId)}` +
+ ` clickToAcceptedMs=${Math.round(now - trace.registeredAt)}` +
+ ` lastDispatchMs=${trace.dispatchStartedAt === undefined ? -1 : Math.round(now - trace.dispatchStartedAt)}` +
+ ` attempts=${trace.attempts}`,
+ );
+}
+
+/** 被控端落库的用户行回显到达:输出点击到回显的总耗时并结束追踪。 */
+export function traceRemoteSendEcho(clientId: string, role: string): void {
+ if (role !== 'user') return;
+ const trace = traces.get(clientId);
+ if (!trace) return;
+ traces.delete(clientId);
+ const now = performance.now();
+ log.debug(
+ `remote send echoed client=${shortId(clientId)}` +
+ ` clickToEchoMs=${Math.round(now - trace.registeredAt)}` +
+ ` acceptedToEchoMs=${trace.acceptedAt === undefined ? -1 : Math.round(now - trace.acceptedAt)}`,
+ );
+}
+
+export function traceRemoteSendDropped(clientId: string): void {
+ traces.delete(clientId);
+}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 9b9ca408e2..9aef9f4fd1 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -6481,6 +6481,8 @@ interface ElectronAPI {
} | null>;
// effort/mode 透传 string —— 合法值由 maker capabilities 决定, vite-env 不重复枚举
setEffort: (sessionId: string, effort: string) => Promise<void>;
+ /** 输入框开始打字时提前启动 Agent;尽力而为。 */
+ prewarmSession?: (sessionId: string, createOpts: unknown) => Promise<{ accepted: boolean }>;
setPermissionMode: (sessionId: string, mode: string) => Promise<void>;
getPluginWriteAccessRecovery: (sessionId: string) => Promise<{available: boolean}>;
retryPluginWriteAccess: (sessionId: string) => Promise<{granted: boolean; mode?: 'acceptEdits' | 'auto'}>;
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 38b67cb860..8a77db70fa 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -870,6 +870,8 @@ const ENQUEUE_RECONNECT_BACKOFF_MS = 300;
* 闪一下、计时还被重置回 0s。真停了推迟这点时间熄灭无感,交接空隙则被吃掉。
*/
const COMPOSER_ACTIVITY_SETTLE_MS = 600;
+/** 打字预热提醒的最短间隔;被控端每次提醒都会顺延预热进程的空闲回收。 */
+const MOBILE_AGENT_PREWARM_INTERVAL_MS = 30_000;
/** 另一台电脑的目录还没读到时的空供应商列表(稳定引用,不触发下游 memo 重算)。 */
const EMPTY_PROVIDER_VIEWS: readonly ProviderView[] = [];
@@ -3226,6 +3228,28 @@ function SessionScreenContent() {
applyComposerDraft(value, queueEditingRef.current ? { persist: false } : undefined);
}, [applyComposerDraft]);
+ // 开始打字时请被控端提前启动 Agent,把冷启动藏进打字时间。同一任务 30 秒最多提醒一次;
+ // 任务在跑、在排队编辑或旧被控端不支持时什么都不做。
+ const lastAgentPrewarmAtRef = useRef(0);
+ const prewarmAgentOnTyping = useCallback(() => {
+ if (queueEditingRef.current) return;
+ const now = Date.now();
+ if (now - lastAgentPrewarmAtRef.current < MOBILE_AGENT_PREWARM_INTERVAL_MS) return;
+ const session = remoteSessionStore.getSessions().find((item) => item.id === sessionId) ?? currentSession;
+ if (!session?.workingDir || remoteSessionStore.isSessionRunning(sessionId)) return;
+ lastAgentPrewarmAtRef.current = now;
+ const { createOpts } = buildQueuedTextMessage(session, '', new Date(now));
+ void maker.prewarmSession(sessionId, createOpts).catch(() => undefined);
+ }, [currentSession, maker, sessionId]);
+ const applyTypedComposerChange = useCallback((value: ComposerDocument) => {
+ applyRichComposerChange(value);
+ prewarmAgentOnTyping();
+ }, [applyRichComposerChange, prewarmAgentOnTyping]);
+ const setTypedComposerDraft = useCallback((next: SetStateAction<string>) => {
+ setComposerDraft(next);
+ prewarmAgentOnTyping();
+ }, [prewarmAgentOnTyping, setComposerDraft]);
+
const writeVoiceDraft = useComposerVoiceDraftWriter(sessionId, (update: ComposerVoiceDraftUpdate) => {
applyRichComposerChange(reconcileComposerVoiceDraft(composerDocumentRef.current, update));
});
@@ -10767,8 +10791,8 @@ function SessionScreenContent() {
keyboardState={keyboardState}
attachmentError={attachmentError}
visualFocusComposer={visualFocusComposer}
- applyRichComposerChange={applyRichComposerChange}
- setComposerDraft={setComposerDraft}
+ applyRichComposerChange={applyTypedComposerChange}
+ setComposerDraft={setTypedComposerDraft}
handleComposerInputPressIn={handleComposerInputPressIn}
beginPastePlaceholders={beginPastePlaceholders}
failPastePlaceholders={failPastePlaceholders}
diff --git a/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts b/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts
index ca7db5d963..5446287d9f 100644
--- a/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts
+++ b/apps/mobile/src/__tests__/cindyMakeOutboxBridge.test.ts
@@ -10,7 +10,7 @@ import type { OutboxSessionPolicy } from '@/session/durableOutboxDelivery';
const source = ts.createSourceFile('MobileOutboxBridge.tsx', readFileSync(resolve(
process.cwd(), 'src/session/MobileOutboxBridge.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const expressions = new Map<string, string>();
-const names = ['knownSession', 'hidden', 'invokeOwned', 'canRun', 'sessionPolicy'];
+const names = ['knownSession', 'hidden', 'invokeOwned', 'readSessionOnce', 'canRun', 'sessionPolicy'];
function visit(node: ts.Node) {
if ((ts.isVariableDeclaration(node) || ts.isPropertyAssignment(node)
&& ['canRun', 'sessionPolicy'].includes(node.name.getText(source))) && node.initializer
@@ -21,7 +21,8 @@ visit(source);
for (const name of names) if (!expressions.has(name)) throw new Error('Missing outbox callback: ' + name);
const compiled = ts.transpileModule(
'function create(deps) { const { remoteSessionStore, mobileDurableOutbox, latest, guard, AppState, CINDY_MAKE_ENABLED, isCindyMakeSource, isDurableOutboxSettled, isDurableOutboxHandedOff, cindyMakeOutboxPolicy, isCurrent } = deps;'
- + ['knownSession', 'hidden', 'invokeOwned'].map(name => 'const ' + name + ' = ' + expressions.get(name) + ';').join('')
+ + 'const sessionReads = new Map(); const SESSION_READ_REUSE_MS = 2000;'
+ + ['knownSession', 'hidden', 'invokeOwned', 'readSessionOnce'].map(name => 'const ' + name + ' = ' + expressions.get(name) + ';').join('')
+ 'const needsReconciliation = () => true; const isDurableOutboxCreationHeld = () => false; const getNewSessionCreationTask = () => null;'
+ 'const maker = (record) => ({ getSession: (sessionId) => invokeOwned(record)(record.deviceId, "local-db:sessions:get", [sessionId]) });'
+ 'return { hidden, invokeOwned, canRun: ' + expressions.get('canRun') + ', sessionPolicy: ' + expressions.get('sessionPolicy') + ' }; }',
diff --git a/apps/mobile/src/__tests__/durableOutbox.test.ts b/apps/mobile/src/__tests__/durableOutbox.test.ts
index d9ebf5af62..bb6eace70a 100644
--- a/apps/mobile/src/__tests__/durableOutbox.test.ts
+++ b/apps/mobile/src/__tests__/durableOutbox.test.ts
@@ -1234,3 +1234,67 @@ it('cancels an enqueue if its page-independent resource check spans an account o
deactivate(); check.resolve(); await run;
expect(deps.enqueue).not.toHaveBeenCalled(); expect(store.getSnapshot()[0].enqueueStarted).toBe(false);
});
+
+describe('known projection first send', () => {
+ const known = (): DeliveryProjection =>
+ ({ pendingQueue: [], inputDeliveryVersion: 1, clearBoundaryMs: 5 }) as unknown as DeliveryProjection;
+
+ it('makes the enqueue the only round trip for a never-sent message', async () => {
+ const { store, deps } = await setup();
+ await store.add(message());
+ await createDurableOutboxDelivery({ ...deps, knownProjection: known }).run();
+ expect(deps.projection).not.toHaveBeenCalled();
+ expect(deps.enqueue).toHaveBeenCalledOnce();
+ expect(store.getSnapshot()[0]).toMatchObject({
+ state: 'host-owned', clearBoundaryMs: 5, retrySafe: true, prepared: { durableDelivery: true },
+ });
+ });
+
+ it('asks the host once after it refuses a stale known clear boundary', async () => {
+ const { store, deps } = await setup();
+ await store.add(message());
+ const cleared = new Error('REMOTE_OPTIMISTIC_INPUT_CLEARED: expectedClearBoundaryMs=5; currentClearBoundaryMs=9');
+ deps.enqueue.mockRejectedValueOnce(cleared);
+ deps.projection.mockResolvedValue({ ...projection('id-1'), clearBoundaryMs: 9 } as DeliveryProjection);
+ const knownProjection = vi.fn(known);
+ await createDurableOutboxDelivery({
+ ...deps, knownProjection, staleClearBoundary: (error) => error === cleared,
+ }).run();
+ await vi.waitFor(() => expect(deps.enqueue).toHaveBeenCalledTimes(2));
+ expect(knownProjection).toHaveBeenCalledOnce();
+ expect(deps.projection).toHaveBeenCalledOnce();
+ expect(deps.enqueue.mock.calls[1]?.[0]).toMatchObject({ clearBoundaryMs: 9, enqueueStarted: true });
+ await vi.waitFor(() => expect(store.getSnapshot()[0]).toMatchObject({ state: 'host-owned' }));
+ });
+});
+
+it('starts a newly added message while another task is still being delivered', async () => {
+ const { store, deps, runner } = await setup();
+ await store.add(message('slow', 'session-a'));
+ const slow = deferred<DeliveryProjection>();
+ deps.enqueue.mockImplementationOnce(() => slow.promise);
+ const first = runner.run();
+ await vi.waitFor(() => expect(deps.enqueue).toHaveBeenCalledOnce());
+ await store.add(message('fresh', 'session-b'));
+ await runner.run();
+ expect(deps.enqueue.mock.calls.map(([r]) => r.item.clientId)).toEqual(['slow', 'fresh']);
+ slow.resolve(projection('slow'));
+ await first;
+});
+
+it('frees each delivery slot as soon as that delivery settles, not when its whole batch does', async () => {
+ const { store, deps, runner } = await setup();
+ await store.add(message('slow', 'session-a'));
+ await store.add(message('fast', 'session-b'));
+ const slow = deferred<DeliveryProjection>();
+ deps.enqueue.mockImplementation((r: DurableOutboxRecord) =>
+ r.item.clientId === 'slow' ? slow.promise : Promise.resolve(projection(r.item.clientId)));
+ const batch = runner.run();
+ await vi.waitFor(() => expect(store.getSnapshot().find((r) => r.item.clientId === 'fast')?.state).toBe('host-owned'));
+ await store.add(message('third', 'session-c'));
+ await runner.run();
+ await vi.waitFor(() =>
+ expect(deps.enqueue.mock.calls.map(([r]) => r.item.clientId)).toContain('third'));
+ slow.resolve(projection('slow'));
+ await batch;
+});
diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
index 44d354389b..1eb72124a6 100644
--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
@@ -131,7 +131,9 @@ describe('mobile optimistic composer while session is not ready', () => {
const bridge = readSource('src/session/MobileOutboxBridge.tsx');
expect(bridge).toContain('getNewSessionCreationTask(r.item.sessionId) === null');
expect(bridge).toContain('!isDurableOutboxCreationHeld(r.item.sessionId)');
- expect(bridge).toContain('const session = await maker(r).getSession(r.item.sessionId)');
+ // Preparation reads the Host's row; the policy check of the same message may share that read.
+ expect(bridge).toContain('const read = maker(r).getSession(r.item.sessionId)');
+ expect(bridge).toContain('const session = await readSessionOnce(r)');
expect(bridge).toContain('if (!session?.workingDir)');
expect(bridge).toContain('}, [link.status, link.connectionEpoch])');
});
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 23e82249dc..203e003c20 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -520,6 +520,11 @@ export interface MobileMakerTransport {
modelVisibilityOverrides?: Record<string, boolean>;
}>;
getSession(sessionId: string): Promise<RemoteSession>;
+ /**
+ * 输入框开始打字时请被控端提前启动该任务的 Agent。尽力而为:旧被控端返回
+ * CHANNEL_NOT_ALLOWED,调用方忽略即可。
+ */
+ prewarmSession(sessionId: string, createOpts: unknown): Promise<unknown>;
createSideChat(sessionId: string): Promise<RemoteSession>;
listSideChats(sessionId: string): Promise<Array<{ id: string }>>;
searchConversations(
@@ -1231,6 +1236,8 @@ export function createMobileMakerTransport({
},
]),
getSession: (sessionId) => call("local-db:sessions:get", [sessionId]),
+ prewarmSession: (sessionId, createOpts) =>
+ call("maker:session:prewarm", [sessionId, createOpts]),
createSideChat: (sessionId) => call("maker:side-chat:v1", [sessionId]),
listSideChats: (sessionId) => call("maker:side-chat:list:v1", [sessionId]),
searchConversations: (request) =>
diff --git a/apps/mobile/src/session/MobileOutboxBridge.tsx b/apps/mobile/src/session/MobileOutboxBridge.tsx
index 74431331cf..6e2e2798a4 100644
--- a/apps/mobile/src/session/MobileOutboxBridge.tsx
+++ b/apps/mobile/src/session/MobileOutboxBridge.tsx
@@ -38,7 +38,9 @@ import {
uploadMobileAttachmentFromFile,
discardMobileUploadedAttachment,
} from "./mobileAttachmentUpload";
-import { buildQueuedTextMessage } from "./inputProjection";
+import { buildQueuedTextMessage, EMPTY_INPUT_PROJECTION } from "./inputProjection";
+import { mobileDebugLog } from "@/debug/mobileDebugLog";
+import type { RemoteSession } from "./types";
import { outboxItemAttachments } from "./sessionOutbox";
import { sessionFromCreateResult } from "./newSession";
import { dismissRecoveredPrecreatedSession, getNewSessionCreationTask, restoreNewSessionDurableEdit } from "./newSessionCreation";
@@ -56,6 +58,9 @@ import {
type DurableOutboxRecord,
} from "./durableOutbox";
+/** One authoritative session read serves the policy check and preparation of the same attempt. */
+const SESSION_READ_REUSE_MS = 2_000;
+
/** Runs only while the OS gives the app execution time; foreground/reconnect resume the same ledger. */
export function MobileOutboxBridge() {
const auth = useAuth();
@@ -126,6 +131,49 @@ export function MobileOutboxBridge() {
deviceId: r.deviceId,
invoke: invokeOwned(r),
});
+ // The policy check and message preparation both need the authoritative
+ // session row; one read serves both within a single delivery attempt.
+ // Keyed per message: each read runs under that message's ownership guard.
+ const sessionReads = new Map<string, { at: number; read: Promise<RemoteSession> }>();
+ const readSessionOnce = (r: DurableOutboxRecord): Promise<RemoteSession> => {
+ const key = JSON.stringify([r.deviceId, r.item.sessionId, r.item.clientId]);
+ const now = Date.now();
+ // Only reads inside the reuse window are useful; drop the rest so the map stays tiny.
+ for (const [other, entry] of sessionReads)
+ if (now - entry.at >= SESSION_READ_REUSE_MS) sessionReads.delete(other);
+ const cached = sessionReads.get(key);
+ if (cached) return cached.read;
+ const read = maker(r).getSession(r.item.sessionId);
+ sessionReads.set(key, { at: now, read });
+ read.catch(() => {
+ if (sessionReads.get(key)?.read === read) sessionReads.delete(key);
+ });
+ return read;
+ };
+ // Learned from this host's own projection / enqueue replies. A first send in
+ // a task whose boundary is known needs no projection round trip.
+ const durableHosts = new Set<string>();
+ const knownClearBoundaries = new Map<string, number | null>();
+ // What a host answered belongs to the connection it answered on: a host that
+ // restarted or was replaced by an older build must be asked again.
+ let learnedEpoch = latest.current.link.connectionEpoch;
+ const forgetStaleLearning = () => {
+ const epoch = latest.current.link.connectionEpoch;
+ if (epoch === learnedEpoch) return;
+ learnedEpoch = epoch;
+ durableHosts.clear();
+ knownClearBoundaries.clear();
+ };
+ const learnProjection = (r: DurableOutboxRecord, projection: unknown) => {
+ forgetStaleLearning();
+ if (!projection || typeof projection !== 'object') return;
+ const value = projection as { inputDeliveryVersion?: unknown; clearBoundaryMs?: unknown };
+ if (value.inputDeliveryVersion === 1) durableHosts.add(r.deviceId);
+ if (value.clearBoundaryMs === null
+ || (typeof value.clearBoundaryMs === 'number' && Number.isFinite(value.clearBoundaryMs))) {
+ knownClearBoundaries.set(leaseKey(r), value.clearBoundaryMs);
+ }
+ };
const epochs = new Map<string, { authority: number; remote: number }>();
const leases = new Map<
string,
@@ -133,6 +181,16 @@ export function MobileOutboxBridge() {
>();
const leaseKey = (r: DurableOutboxRecord) =>
JSON.stringify([r.deviceId, r.item.sessionId]);
+ const captureProjectionEpoch = (r: DurableOutboxRecord) => {
+ epochs.set(leaseKey(r), {
+ authority: remoteSessionStore.captureInputProjectionAuthorityEpoch(
+ r.item.sessionId,
+ ),
+ remote: remoteSessionStore.captureInputProjectionRemoteEpoch(
+ r.item.sessionId,
+ ),
+ });
+ };
// Accepted sends remain durable in the outbox while hidden. Neither poll
// their history nor pin their raw message windows just for display handoff.
const needsReconciliation = (r: DurableOutboxRecord) =>
@@ -199,18 +257,11 @@ export function MobileOutboxBridge() {
getNewSessionCreationTask(r.item.sessionId) === null)),
sessionPolicy: (record) => cindyMakeOutboxPolicy(record, {
knownSession: () => knownSession(record),
- readSession: () => maker(record).getSession(record.item.sessionId),
+ readSession: () => readSessionOnce(record),
isCurrent: () => isCurrent() && mobileDurableOutbox.getSnapshot().includes(record),
}),
projection: async (r) => {
- epochs.set(leaseKey(r), {
- authority: remoteSessionStore.captureInputProjectionAuthorityEpoch(
- r.item.sessionId,
- ),
- remote: remoteSessionStore.captureInputProjectionRemoteEpoch(
- r.item.sessionId,
- ),
- });
+ captureProjectionEpoch(r);
return invoke<DeliveryProjection>(
r.deviceId,
"maker:input:get-projection",
@@ -222,9 +273,28 @@ export function MobileOutboxBridge() {
],
);
},
+ knownProjection: (r) => {
+ forgetStaleLearning();
+ const clearBoundaryMs = knownClearBoundaries.get(leaseKey(r));
+ if (!durableHosts.has(r.deviceId) || clearBoundaryMs === undefined) return undefined;
+ // The enqueue reply is applied with the epoch captured here, exactly as
+ // it would be after a fetched projection.
+ captureProjectionEpoch(r);
+ return {
+ ...EMPTY_INPUT_PROJECTION,
+ sessionId: r.item.sessionId,
+ inputDeliveryVersion: 1,
+ clearBoundaryMs,
+ };
+ },
+ staleClearBoundary: (error) =>
+ formatRemoteError(error).includes("REMOTE_OPTIMISTIC_INPUT_CLEARED"),
+ trace: (event, fields) => mobileDebugLog("debug", "device-link", event, fields),
session: (r) => maker(r).getSession(r.item.sessionId),
applyProjection: (r, projection) => {
guard();
+ // Every fetched projection and enqueue reply passes through here.
+ learnProjection(r, projection);
const epoch = epochs.get(leaseKey(r));
if (epoch)
remoteSessionStore.setInputProjectionIfCurrent(
@@ -235,7 +305,7 @@ export function MobileOutboxBridge() {
);
},
prepare: async (r) => {
- const session = await maker(r).getSession(r.item.sessionId);
+ const session = await readSessionOnce(r);
guard();
if (!session?.workingDir)
throw new Error(i18n.t("session.screen.missingWorkingDir"));
diff --git a/apps/mobile/src/session/durableOutboxDelivery.ts b/apps/mobile/src/session/durableOutboxDelivery.ts
index edc55bdb50..a9b46a1eb7 100644
--- a/apps/mobile/src/session/durableOutboxDelivery.ts
+++ b/apps/mobile/src/session/durableOutboxDelivery.ts
@@ -23,6 +23,16 @@ export interface DurableOutboxDeliveryDeps {
canRun(record: DurableOutboxRecord): boolean;
sessionPolicy?(record: DurableOutboxRecord): Promise<OutboxSessionPolicy>;
projection(record: DurableOutboxRecord): Promise<DeliveryProjection>;
+ /**
+ * A never-sent record may skip the pre-enqueue projection RPC when this host
+ * is already known to support durable delivery and the task's clear boundary
+ * is known. Return undefined to use the projection RPC.
+ */
+ knownProjection?(record: DurableOutboxRecord): DeliveryProjection | undefined;
+ /** Host rejected a clear-boundary precondition that came from `knownProjection`. */
+ staleClearBoundary?(error: unknown): boolean;
+ /** Phone-local timing diagnostics only; never receives message content. */
+ trace?(event: string, fields: Record<string, number | string | boolean>): void;
session(record: DurableOutboxRecord): Promise<{ id: string; status: string } | null>;
prepare(record: DurableOutboxRecord): Promise<QueuedRemoteMessage>;
upload(
@@ -52,17 +62,33 @@ export interface DurableOutboxDeliveryDeps {
/** One owner for writes; pages only add records or request retry/cancellation. */
export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
- let running = false;
+ let scanning = false;
+ let rescan = false;
let stopped = false;
let cursor = 0;
const due = new Map<string, number>();
const attempts = new Map<string, number>();
+ /** Records currently inside `deliver`; a later run never starts the same record twice. */
+ const inFlight = new Set<string>();
+ /** A stale known boundary was rejected once; this record must ask the host instead. */
+ const requireProjection = new Set<string>();
const id = (r: DurableOutboxRecord) =>
JSON.stringify([r.deviceId, r.item.sessionId, r.item.clientId]);
const current = (r: DurableOutboxRecord) =>
!stopped && deps.isCurrent() && deps.store.getSnapshot().includes(r);
const hasDurableOwnership = (r: DurableOutboxRecord) =>
r.state === "host-owned" && isDurableOutboxHandedOff(r);
+ /** Nothing has been sent or prepared, so no host receipt can matter yet. */
+ const neverSent = (r: DurableOutboxRecord) =>
+ r.state === "queued" && isDurableOutboxUnsent(r) && !r.prepared
+ && !r.cancelRequested && !r.refreshUploads && !requireProjection.has(id(r));
+ const trace = (event: string, fields: Record<string, number | string | boolean>) => {
+ try {
+ deps.trace?.(event, fields);
+ } catch {
+ /* diagnostics never affect delivery */
+ }
+ };
const hasHistory = async (record: DurableOutboxRecord): Promise<boolean> => {
try {
return await deps.history(record);
@@ -76,6 +102,14 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
async function deliver(initial: DurableOutboxRecord) {
let record = initial;
due.set(id(record), Date.now() + 5_000);
+ const startedAt = Date.now();
+ let markAt = startedAt;
+ const stagesMs: Record<string, number> = {};
+ const stage = (name: string) => {
+ const now = Date.now();
+ stagesMs[name] = now - markAt;
+ markAt = now;
+ };
const update = async (patch: Partial<DurableOutboxRecord>) => {
if (!current(record)) throw new Error("OUTBOX_STALE_WRITE");
record = await deps.store.update(record, patch);
@@ -91,9 +125,14 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
await deps.store.remove(record);
due.delete(id(record));
attempts.delete(id(record));
+ requireProjection.delete(id(record));
};
const finishHistory = async () => {
if (!current(record)) return;
+ trace("send history confirmed", {
+ client: record.item.clientId.slice(0, 8),
+ clickToHistoryMs: Date.now() - record.createdAt,
+ });
if (deps.cacheHistory && !await deps.cacheHistory(record)) {
// Even a legacy host has durably accepted this row. Retaining its local
// bubble must not block later sends or make the old message retryable.
@@ -108,6 +147,7 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
const policy = await deps.sessionPolicy(record);
if (!current(record) || policy === 'wait') return;
if (policy === 'discard') return await finish(isDurableOutboxUnsent(record));
+ stage('policy');
}
if (record.draftHandoff) {
await deps.store.reconcileDrafts(record.item.sessionId);
@@ -126,8 +166,14 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
return;
}
if (!current(record)) return;
+ // A first attempt has no receipt to reconcile. When the host's durable
+ // delivery support and the task's clear boundary are already known, the
+ // enqueue itself is the only round trip; the host still enforces the
+ // boundary and a stale one is retried once through the projection below.
+ const knownProjection = neverSent(record) ? deps.knownProjection?.(record) : undefined;
let projection: DeliveryProjection;
- try {
+ if (knownProjection) projection = knownProjection;
+ else try {
projection = await deps.projection(record);
} catch (error) {
if (!current(record)) return;
@@ -145,7 +191,8 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
throw error;
}
if (!current(record)) return;
- deps.applyProjection(record, projection);
+ if (!knownProjection) deps.applyProjection(record, projection);
+ stage('projection');
const receipt = projection.deliveryReceipts?.find(
(r) => r.clientId === record.item.clientId,
);
@@ -296,12 +343,36 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
? projection.clearBoundaryMs : record.clearBoundaryMs,
sendAtMs: record.sendAtMs ?? Date.now(),
});
+ stage('prepare');
}
await deps.beforeEnqueue?.(record);
if (!current(record) || !deps.canRun(record)) return;
// This write precedes every external enqueue. Crash recovery therefore knows it must reconcile.
await update({ state: "sending", enqueueStarted: true, error: undefined });
- const result = await deps.enqueue(record);
+ let result: InputProjection;
+ try {
+ result = await deps.enqueue(record);
+ } catch (error) {
+ // The host refused the known boundary before accepting anything. Undo
+ // only that local preparation and ask the host once, like the first send
+ // would have; a second refusal follows the ordinary cleared-task path.
+ if (knownProjection && current(record) && deps.staleClearBoundary?.(error)) {
+ requireProjection.add(id(record));
+ await update({
+ state: "queued",
+ prepared: undefined,
+ retrySafe: undefined,
+ clearBoundaryMs: undefined,
+ enqueueStarted: false,
+ error: undefined,
+ });
+ due.delete(id(record));
+ rescan = true;
+ trace("send known boundary rejected", { client: record.item.clientId.slice(0, 8) });
+ return;
+ }
+ throw error;
+ }
if (!current(record)) return;
deps.applyProjection(record, result);
const durableEnqueue = record.prepared?.durableDelivery === true &&
@@ -312,6 +383,15 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
: { state: "confirming", error: deps.confirmationMessage });
attempts.delete(id(record));
due.set(id(record), Date.now() + 1_000);
+ stage('enqueue');
+ trace("send accepted", {
+ client: record.item.clientId.slice(0, 8),
+ knownProjection: knownProjection !== undefined,
+ durable: durableEnqueue,
+ clickToAcceptedMs: Date.now() - record.createdAt,
+ deliverMs: Date.now() - startedAt,
+ ...stagesMs,
+ });
} catch (error) {
if (!current(record)) return;
const count = (attempts.get(id(record)) ?? 0) + 1;
@@ -337,6 +417,69 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
}).catch(() => undefined);
}
}
+ // Bound aggregate replay as well as concurrency; reconnecting many tasks must not
+ // recreate a relay backpressure burst.
+ const MAX_IN_FLIGHT = 2;
+ async function run(): Promise<void> {
+ if (stopped || !deps.isCurrent()) return;
+ // A request that arrives while another run is choosing work, or while every
+ // delivery slot is busy, is remembered and replayed as soon as a slot frees.
+ // A new message therefore never waits for the periodic tick behind an
+ // unrelated reconciliation.
+ if (scanning || inFlight.size >= MAX_IN_FLIGHT) {
+ rescan = true;
+ return;
+ }
+ scanning = true;
+ rescan = false;
+ const work: DurableOutboxRecord[] = [];
+ try {
+ await deps.store.ready();
+ if (stopped || !deps.isCurrent()) return;
+ const groups = new Map<string, DurableOutboxRecord[]>();
+ for (const record of deps.store.getSnapshot()) {
+ const key = JSON.stringify([record.deviceId, record.item.sessionId]);
+ const group = groups.get(key) ?? [];
+ group.push(record);
+ groups.set(key, group);
+ }
+ // Session FIFO, while one unavailable computer never blocks a different task.
+ // A head already being delivered still holds its session's place in line.
+ const candidates = [...groups.values()]
+ .flatMap((group) => {
+ const head = group.find((r) => !isDurableOutboxHandedOff(r));
+ return [
+ ...(head ? [head] : []),
+ ...group.filter(isDurableOutboxHandedOff),
+ ];
+ })
+ .filter((r) => !inFlight.has(id(r)) && deps.canRun(r) && (due.get(id(r)) ?? 0) <= Date.now());
+ // Round robin prevents one failed head starving peers.
+ const capacity = Math.min(MAX_IN_FLIGHT - inFlight.size, candidates.length);
+ for (let n = 0; n < capacity; n++) {
+ work.push(candidates[(cursor + n) % candidates.length]!);
+ }
+ cursor = candidates.length
+ ? (cursor + work.length) % candidates.length
+ : 0;
+ for (const record of work) inFlight.add(id(record));
+ } finally {
+ scanning = false;
+ }
+ // Each delivery frees its own slot as soon as it settles, so a message added
+ // while a slow peer is still replying can use that slot immediately.
+ await Promise.all(
+ work.map((record) =>
+ deliver(record).finally(() => {
+ inFlight.delete(id(record));
+ if (rescan && !stopped) {
+ rescan = false;
+ void run().catch(() => undefined);
+ }
+ }),
+ ),
+ );
+ }
return {
stop() {
stopped = true;
@@ -344,42 +487,6 @@ export function createDurableOutboxDelivery(deps: DurableOutboxDeliveryDeps) {
wake() {
due.clear();
},
- async run() {
- if (running || stopped || !deps.isCurrent()) return;
- running = true;
- try {
- await deps.store.ready();
- if (stopped || !deps.isCurrent()) return;
- const groups = new Map<string, DurableOutboxRecord[]>();
- for (const record of deps.store.getSnapshot()) {
- const key = JSON.stringify([record.deviceId, record.item.sessionId]);
- const group = groups.get(key) ?? [];
- group.push(record);
- groups.set(key, group);
- }
- // Session FIFO, while one unavailable computer never blocks a different task.
- const candidates = [...groups.values()]
- .flatMap((group) => {
- const head = group.find((r) => !isDurableOutboxHandedOff(r));
- return [
- ...(head ? [head] : []),
- ...group.filter(isDurableOutboxHandedOff),
- ];
- })
- .filter((r) => deps.canRun(r) && (due.get(id(r)) ?? 0) <= Date.now());
- // Bound aggregate replay as well as concurrency; reconnecting many tasks must not
- // recreate a relay backpressure burst. Round robin prevents one failed head starving peers.
- const work: DurableOutboxRecord[] = [];
- for (let n = 0; n < Math.min(2, candidates.length); n++) {
- work.push(candidates[(cursor + n) % candidates.length]!);
- }
- cursor = candidates.length
- ? (cursor + work.length) % candidates.length
- : 0;
- await Promise.all(work.map(deliver));
- } finally {
- running = false;
- }
- },
+ run,
};
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 31a88e83c5..e8ec8d5b53 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1,5 +1,25 @@
# 跨端协议兼容
+## Agent 预热与远程发送路径
+
+新增 invoke `maker:session:prewarm(sessionId, createOpts)`,Desktop 本机 Renderer 与 device-link
+控制端共用,登记在 `REMOTE_INVOKE_ALLOWLIST` 并归入后台调度档;共享任务访客不在其准入表内。
+控制端在已有任务的输入框里开始打字时调用(同一任务 30 秒最多一次),`createOpts` 与下一次发送
+构造的相同;被控端立即回 `{ accepted }`,在同一把会话发送锁里复用发送路径的懒创建启动 Agent,
+执行字段(agentKind、model、resume、provider、权限、Agent 所在电脑)照常按数据库校正。只对来源为
+user / desktop / plugin / side-chat、状态 active、非协同、Agent 在本机且非 SSH 工作区、且用户已在该任务里真实发送过(有原生会话 ID)的任务生效——启动会加载目录自带的设置与钩子,只打字不构成同意,从未发送过的任务等第一次真实发送;
+已有运行时、待切换引擎、已有排队输入时不做任何事。预热出来、尚未发送使用的运行时最多 2 个,
+10 分钟未发送即关闭;任何真实发送会接管它。旧被控端返回 CHANNEL_NOT_ALLOWED,控制端静默忽略,
+下一次发送照常冷启动;旧控制端不调用,行为不变。
+
+`maker:input:enqueue` 与 `maker:input:get-projection` 的 wire 不变。Mobile 已从同一被控端的
+projection 见过 `inputDeliveryVersion: 1`、并从 projection / enqueue 回包得知该任务的
+`clearBoundaryMs` 时,首次发送跳过发送前的 projection,直接带该边界 enqueue;被控端仍按原规则
+校验,若以 `REMOTE_OPTIMISTIC_INPUT_CLEARED` 拒绝,Mobile 撤回本地准备并按原流程查询一次
+projection 后重发(被控端拒绝时尚未收下,不产生重复)。旧被控端不回 `inputDeliveryVersion`,
+Mobile 始终走原流程。Mobile 学到的这些结论绑定 device-link 连接代次,重连后清空并重新确认。
+没有新的 push、数据库迁移或 Mobile 原生指纹变化。
+
## 伙伴个人聊天全文搜索
既有 `local-db:conversations:search` 的结果 `session` 增加可选
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 173778de3c..354a480764 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -444,7 +444,7 @@ Mobile 伙伴任务卡的列表外补读由 `companionTaskReads.ts` 按账号、
Debug 日志区分两层耗时:
-- `remote invoke slow execution`(至少 1 秒)包含 `stagesMs`:调用前授权、业务 handler、
+- `remote invoke slow execution`(至少 300 毫秒)包含 `stagesMs`:调用前授权、业务 handler、
调用后授权、设置持久化、返回投影。总耗时还包含调度和序列化,不等于 SQL 执行时间。
- `db-rpc` 的 `rpc.slow`(至少 250 毫秒)包含 `queueMs`(主线程待发送队列)、
`workerWaitMs`(投递到 Worker 开始处理)、`workerExecutionMs`(整个 Worker 操作)、
@@ -455,6 +455,20 @@ Debug 日志区分两层耗时:
性能复测应同时包含前台发送、另一控制端刷新与补读、本地读取;分别报告请求数量和延迟,
不能把内存数据库基准当成真机网络端到端改善。
+远程发送的端到端耗时按同一 clientId(只记前 8 位)在三端分别记 debug 日志,各端只用本机时钟:
+
+- 被控端 `remote enqueue timing`:enqueue handler 内 `gate`(准入与清除边界)、`restore`、
+ `prepare`(附件物化与引用水合)、`recheck`、`dedupe`、`coordinator`、`snapshot` 各阶段耗时;
+ `remote send pushed`:coordinator 收下到用户行 `messages:created` 推出的耗时(含 Agent 冷启动)。
+- Desktop 控制端 `remote send accepted`(点击到被控端收下、最后一次派发耗时、尝试次数)与
+ `remote send echoed`(点击到回显)。
+- Mobile 控制端(调试记录开启时)`send accepted`:`policy` / `projection` / `prepare` / `enqueue`
+ 各阶段、是否跳过发送前 projection、点击到收下;`send history confirmed`:点击到落库确认。
+- Desktop 控制端在 debug 级别每 30 秒输出 `transport bytes`:按 channel 统计 invoke 回包数与字节数
+ (只在 debug 开启时为统计再序列化一次回包)。
+
+这些日志不改变 wire、ACK、重试或授权语义。
+
`device-link request slow/failed/timeout` 另记录 `firstWriteWaitMs`(请求建立到首次
WebSocket 写入成功)与 `afterFirstWriteMs`(首次写入到结束);从未写出时记录
`firstWrite=none`。写入成功不是送达回执,后半段仍包含 socket/relay/网络、对端处理和
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index f530c23117..5af9c20e8f 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -189,6 +189,9 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [
'maker:mcp-apps:v1',
DL_SESSION_HANDOFF_CHANNEL,
'maker:steer',
+ // 控制端输入框开始打字时,请被控端提前启动该任务的 Agent。被控端只对普通任务、
+ // 本机运行的 Agent 生效,限量并空闲回收;旧被控端 CHANNEL_NOT_ALLOWED → 控制端静默忽略。
+ 'maker:session:prewarm',
'maker:list-active',
'maker:any-session-in-turn',
'maker:session-in-turn',
diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.ts
index 6e4eea8d6d..e8cb21ddfb 100644
--- a/packages/device-link/src/invokePolicy.ts
+++ b/packages/device-link/src/invokePolicy.ts
@@ -18,6 +18,8 @@ const BACKGROUND_INVOKE_CHANNELS = new Set([
// 远程任务状态栏的定时复查(每 15 秒两次只读);后台任务面板挂载水合同用,可让位于用户操作。
'maker:session-background-activity',
'maker:session-background-tasks:list',
+ // 打字时的 Agent 预热是尽力而为的提示,排在用户正在等待的请求之后。
+ 'maker:session:prewarm',
]);
export function isBackgroundInvoke(channel: string): boolean {