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): 远程链路流量治理——交互优先名额、历史修复读去重、Subagent 变更推送与 PR 状态 SWR (#6613)

Dash01d51d7532ee
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index a5ca1f9cb3..8d7a927851 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -1245,6 +1245,40 @@ describe('被控端控制链路生命周期', () => {
expect(handler).toHaveBeenCalledTimes(1);
});
+ // 控制端把 16 个名额填满历史 / 列表读取后,用户正在等的发送以前会被 BACKPRESSURE 打回、
+ // 再等 ≥2s 重试;交互类写入另有少量名额,读取仍按原上限拒绝。
+ it('交互类 invoke 在 per-controller 名额用满后仍被执行,读取照旧 BACKPRESSURE', async () => {
+ remoteControlEnabled = true;
+ let resolveList: ((value: unknown[]) => void) | undefined;
+ registry.register('local-db:sessions:list', vi.fn(() => new Promise<unknown[]>((resolve) => {
+ resolveList = resolve;
+ })));
+ const enqueue = vi.fn(() => ({ accepted: true }));
+ registry.register('maker:input:enqueue', enqueue);
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+ const limit = dispatchTesting.remoteInvokeInFlightPerControllerLimit;
+ const extra = dispatchTesting.remoteInvokeInteractiveExtraPerController;
+ for (let index = 0; index < limit; index += 1) {
+ feed({ v: 1, kind: 'invoke', id: `list-${index}`, src: 'ctrl-a', payload: {
+ channel: 'local-db:sessions:list', args: [20, 'all', { fresh: true, index }],
+ } });
+ }
+ for (let index = 0; index < extra + 1; index += 1) {
+ feed({ v: 1, kind: 'invoke', id: `send-${index}`, src: 'ctrl-a', payload: {
+ channel: 'maker:input:enqueue', args: ['s1', { text: `hello ${index}` }],
+ } });
+ }
+ await vi.waitFor(() => expect(enqueue).toHaveBeenCalledTimes(extra));
+ const busy = { ok: false, error: { code: 'BACKPRESSURE', message: 'remote invoke execution queue is full' } };
+ await vi.waitFor(() => expect(calls.invokeResult).toContainEqual({ dst: 'ctrl-a', requestId: `send-${extra}`, payload: busy }));
+ feed({ v: 1, kind: 'invoke', id: 'list-late', src: 'ctrl-a', payload: {
+ channel: 'local-db:sessions:list', args: [20, 'all', { fresh: true, index: 'late' }],
+ } });
+ await vi.waitFor(() => expect(calls.invokeResult).toContainEqual({ dst: 'ctrl-a', requestId: 'list-late', payload: busy }));
+ resolveList?.([]);
+ });
+
it('sessions:list fresh 请求不并入已有 listing 单飞', async () => {
remoteControlEnabled = true;
let resolvers: Array<(value: unknown[]) => void> = [];
@@ -1450,6 +1484,34 @@ describe('被控端控制链路生命周期', () => {
expect(handler).not.toHaveBeenCalled();
});
+ // 准入给交互类请求多放了名额,它们的回包也得有位置:否则已生效的发送因回包入不了 outbox
+ // 而让控制端超时、用户重试。
+ it('交互类 invoke 的结果在 per-controller outbox 用满后仍有预留位置,读取结果照旧被拒', () => {
+ const client = {
+ sendInvokeResult: () => {
+ throw new DeviceLinkError('BACKPRESSURE', 'socket buffer full');
+ },
+ } as never;
+ const limit = dispatchTesting.remoteInvokeResultOutboxPerControllerLimit;
+ const extra = dispatchTesting.remoteInvokeInteractiveExtraPerController;
+ for (let index = 0; index < limit; index++) {
+ expect(dispatchTesting.sendInvokeResultSafe(
+ client, 'ctrl-a', `invoke-reserve-read-${index}`, { ok: true, result: index }, 'maker:list-active',
+ )).toBe(true);
+ }
+ expect(dispatchTesting.sendInvokeResultSafe(
+ client, 'ctrl-a', 'invoke-reserve-read-over', { ok: true, result: 'x' }, 'maker:list-active',
+ )).toBe(false);
+ for (let index = 0; index < extra; index++) {
+ expect(dispatchTesting.sendInvokeResultSafe(
+ client, 'ctrl-a', `invoke-reserve-send-${index}`, { ok: true, result: index }, 'maker:input:enqueue',
+ )).toBe(true);
+ }
+ expect(dispatchTesting.sendInvokeResultSafe(
+ client, 'ctrl-a', 'invoke-reserve-send-over', { ok: true, result: 'x' }, 'maker:input:enqueue',
+ )).toBe(false);
+ });
+
it('多个控制端的 invoke-result outbox 仍受全局消息上限保护', () => {
const client = {
sendInvokeResult: () => {
diff --git a/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts b/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts
index 87ba9b0950..236cf8d441 100644
--- a/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts
+++ b/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts
@@ -117,6 +117,33 @@ describe('PrStatusService', () => {
expect(fetchPr).toHaveBeenCalledTimes(2);
});
+ // 过期但未超 stale 窗:立即用旧值回答,后台复核一次;下一次查询拿到新值。
+ // 修复前每 60s 过期都让一次 ~1.2s 的 GitHub 往返挡在侧栏 / 手机的状态查询前面。
+ it('过期后先回旧值再后台复核,超过 stale 窗才同步等待', async () => {
+ let now = 0;
+ let resolveFetch!: (v: PrRemoteState) => void;
+ const fetchPr = vi.fn(async () => remote({}));
+ const svc = new PrStatusService({
+ readToken: TOKEN_OK, fetchPr, cacheTtlMs: 100, staleTtlMs: 1_000, now: () => now,
+ });
+ expect((await svc.getStatuses([Q]))[0]).toMatchObject({ ok: true, status: 'open' });
+ now = 200;
+ fetchPr.mockImplementation(() => new Promise<PrRemoteState>((res) => (resolveFetch = res)));
+ // Stale answer returns without waiting for the slow revalidation.
+ expect((await svc.getStatuses([Q]))[0]).toMatchObject({ ok: true, status: 'open' });
+ await vi.waitFor(() => expect(fetchPr).toHaveBeenCalledTimes(2));
+ // A second stale read joins the same in-flight revalidation.
+ expect((await svc.getStatuses([Q]))[0]).toMatchObject({ status: 'open' });
+ expect(fetchPr).toHaveBeenCalledTimes(2);
+ resolveFetch(remote({ merged: true, state: 'closed' }));
+ await vi.waitFor(async () => expect((await svc.getStatuses([Q]))[0]).toMatchObject({ status: 'merged' }));
+ // Beyond the stale window the read waits for GitHub again.
+ now = 5_000;
+ fetchPr.mockImplementation(async () => remote({ state: 'closed' }));
+ expect((await svc.getStatuses([Q]))[0]).toMatchObject({ status: 'closed' });
+ expect(fetchPr).toHaveBeenCalledTimes(3);
+ });
+
it('并发同一 PR 只发一次请求(in-flight 去重)', async () => {
let resolveFetch!: (v: PrRemoteState) => void;
const fetchPr = vi.fn(() => new Promise<PrRemoteState>((res) => (resolveFetch = res)));
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index dff8788699..b370e94d66 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -55,6 +55,7 @@ import { observeRemoteSendPush } from './remoteSendTrace.js';
import {
computeAllowlistHash,
canCoalesceRemoteListing,
+ isInteractiveInvoke,
isCompletedInvokeRetryableReadChannel,
INVOKE_TIMEOUT_OVERRIDES_MS,
ACTION_INVOKE_TIMEOUTS_MS,
@@ -919,6 +920,15 @@ const REMOTE_SCHEDULE_INDEX_MAX_BYTES = 2 * 1024 * 1024;
* guarantees admission for other linked controllers.
*/
const REMOTE_INVOKE_IN_FLIGHT_PER_CONTROLLER_LIMIT = 16;
+/**
+ * Interactive writes (send / steer / stop / answer, see isInteractiveInvoke) may exceed the
+ * message limits by this much. A controller that fills its slice with history and list
+ * reads otherwise gets BACKPRESSURE on the one request its user is waiting for, and the
+ * ≥2 s controller retry turns a 0.5 s round trip into several seconds. Byte limits are not
+ * relaxed: an interactive request is small, and bytes are what protect the host.
+ */
+const REMOTE_INVOKE_INTERACTIVE_EXTRA_PER_CONTROLLER = 2;
+const REMOTE_INVOKE_INTERACTIVE_EXTRA_GLOBAL = 4;
const REMOTE_INVOKE_IN_FLIGHT_BYTES = 16 * 1024 * 1024;
const REMOTE_INVOKE_IN_FLIGHT_PER_CONTROLLER_BYTES = 4 * 1024 * 1024;
const REMOTE_INVOKE_RESULT_CACHE_LIMIT = 128;
@@ -3002,12 +3012,15 @@ async function handleInvoke(
const joiningExisting = !!(existingListing && existingListing.linkEpoch === invokeLinkEpoch);
const controllerAdmission = remoteInvokeAdmissionState(src);
+ const interactive = !!payload?.channel && isInteractiveInvoke(payload.channel);
const controllerAtLimit = (
controllerAdmission.messages >= REMOTE_INVOKE_IN_FLIGHT_PER_CONTROLLER_LIMIT
+ + (interactive ? REMOTE_INVOKE_INTERACTIVE_EXTRA_PER_CONTROLLER : 0)
|| controllerAdmission.bytes + invokeBytes > REMOTE_INVOKE_IN_FLIGHT_PER_CONTROLLER_BYTES
);
const globalAtLimit = (
inFlightRemoteInvokeResults.size + remoteInvokeResultOutbox.size >= REMOTE_INVOKE_IN_FLIGHT_LIMIT
+ + (interactive ? REMOTE_INVOKE_INTERACTIVE_EXTRA_GLOBAL : 0)
|| inFlightRemoteInvokeBytes + remoteInvokeResultOutboxBytes + invokeBytes
> REMOTE_INVOKE_IN_FLIGHT_BYTES
);
@@ -3592,11 +3605,17 @@ function enqueueRemoteInvokeResult(entry: QueuedRemoteInvokeResult): boolean {
return true;
}
const controllerOutbox = remoteInvokeResultOutboxState(entry.src);
+ // Admission lets an interactive request run beyond the message limits; its reply
+ // must have a slot too, or the controller times out on a write that already took
+ // effect. Reserve exactly the admission headroom (bytes stay unrelaxed).
+ const interactive = !!entry.channel && isInteractiveInvoke(entry.channel);
if (
entry.bytes <= 0
- || controllerOutbox.messages >= REMOTE_INVOKE_RESULT_OUTBOX_PER_CONTROLLER_LIMIT
+ || controllerOutbox.messages
+ >= REMOTE_INVOKE_RESULT_OUTBOX_PER_CONTROLLER_LIMIT + (interactive ? REMOTE_INVOKE_INTERACTIVE_EXTRA_PER_CONTROLLER : 0)
|| controllerOutbox.bytes + entry.bytes > REMOTE_INVOKE_RESULT_OUTBOX_PER_CONTROLLER_BYTES
- || remoteInvokeResultOutbox.size >= REMOTE_INVOKE_RESULT_OUTBOX_LIMIT
+ || remoteInvokeResultOutbox.size
+ >= REMOTE_INVOKE_RESULT_OUTBOX_LIMIT + (interactive ? REMOTE_INVOKE_INTERACTIVE_EXTRA_GLOBAL : 0)
|| remoteInvokeResultOutboxBytes + entry.bytes > REMOTE_INVOKE_RESULT_OUTBOX_BYTES
) {
log.error(
@@ -4926,6 +4945,7 @@ export const __testing = {
canCoalesceRemoteListing,
remoteInvokeInFlightLimit: REMOTE_INVOKE_IN_FLIGHT_LIMIT,
remoteInvokeInFlightPerControllerLimit: REMOTE_INVOKE_IN_FLIGHT_PER_CONTROLLER_LIMIT,
+ remoteInvokeInteractiveExtraPerController: REMOTE_INVOKE_INTERACTIVE_EXTRA_PER_CONTROLLER,
remoteInvokeOrphanTimeoutMs: REMOTE_INVOKE_ORPHAN_TIMEOUT_MS,
remoteInvokeOrphanTimeoutForChannelMs: remoteInvokeOrphanTimeoutMs,
remoteInvokeResultOutboxLimit: REMOTE_INVOKE_RESULT_OUTBOX_LIMIT,
diff --git a/apps/desktop/src/main/git-context/prStatusService.ts b/apps/desktop/src/main/git-context/prStatusService.ts
index fd4bcff897..54fba53d5a 100644
--- a/apps/desktop/src/main/git-context/prStatusService.ts
+++ b/apps/desktop/src/main/git-context/prStatusService.ts
@@ -100,6 +100,12 @@ export interface PrStatusServiceDeps {
fetchPr: (token: string, q: PrStatusQuery) => Promise<PrRemoteState>;
/** 缓存 TTL,默认 60s。测试可注小值。 */
cacheTtlMs?: number;
+ /**
+ * 过期后仍可直接回答的时长,默认 10 分钟:过期条目先原样返回,再后台向 GitHub 复核,
+ * 下一次查询拿到新值。PR 状态变化以分钟计,但每次 60s 过期都让侧栏 / 手机等一次
+ * ~1.2s 的 GitHub 往返(并占住远程调用名额)并不值得;超过此窗才同步等待。
+ */
+ staleTtlMs?: number;
now?: () => number;
}
@@ -114,9 +120,12 @@ export function mapRemoteToStatus(remote: PrRemoteState): PrStatusKind {
interface CacheEntry {
result: PrStatusResult;
expiresAt: number;
+ /** 过期后到此刻之前仍可直接回答(后台复核);之后必须同步重查。 */
+ staleUntil: number;
}
const DEFAULT_TTL_MS = 60_000;
+const DEFAULT_STALE_TTL_MS = 10 * 60_000;
/** 单次批量查询上限——renderer 正常只显示前几条,防御异常调用。 */
const MAX_BATCH = 10;
@@ -124,6 +133,7 @@ export class PrStatusService {
private readonly deps: Required<Pick<PrStatusServiceDeps, 'readToken' | 'fetchPr'>> &
PrStatusServiceDeps;
private readonly ttlMs: number;
+ private readonly staleTtlMs: number;
private readonly now: () => number;
private readonly cache = new Map<string, CacheEntry>();
private readonly inFlight = new Map<string, Promise<PrStatusResult>>();
@@ -138,6 +148,7 @@ export class PrStatusService {
constructor(deps: PrStatusServiceDeps) {
this.deps = deps;
this.ttlMs = deps.cacheTtlMs ?? DEFAULT_TTL_MS;
+ this.staleTtlMs = Math.max(0, deps.staleTtlMs ?? DEFAULT_STALE_TTL_MS);
this.now = deps.now ?? Date.now;
}
@@ -163,8 +174,18 @@ export class PrStatusService {
private async getOne(q: PrStatusQuery): Promise<PrStatusResult> {
const key = `${q.owner.toLowerCase()}/${q.repo.toLowerCase()}#${q.prNumber}`;
const cached = this.cache.get(key);
- if (cached && cached.expiresAt > this.now()) return cached.result;
+ const now = this.now();
+ if (cached && cached.expiresAt > now) return cached.result;
+ if (cached && cached.staleUntil > now) {
+ // Stale-while-revalidate: answer now, refresh once in the background.
+ void this.revalidate(key, q).catch(() => undefined);
+ return cached.result;
+ }
+ return this.revalidate(key, q);
+ }
+ /** One GitHub read per key at a time; both the stale and the cold path join it. */
+ private revalidate(key: string, q: PrStatusQuery): Promise<PrStatusResult> {
const inflight = this.inFlight.get(key);
if (inflight) return inflight;
@@ -175,9 +196,11 @@ export class PrStatusService {
// - gh-missing / gh-not-logged-in / no-token:用户装完 gh 或登录后,
// 下一次查询应立即生效(token source 自带 30s 负缓存兜底);
// - fetch-failed:瞬时网络抖动 / 临时 5xx 不该把失败钉死满 TTL,
- // 下次渲染触发查询时立即重试(review 反馈)。
+ // 下次渲染触发查询时立即重试(review 反馈)。过期条目遇到这类失败时
+ // 保留原值继续作为 stale 回答,直到 staleUntil。
if (generation === this.generation && (result.ok || result.reason === 'not-found')) {
- this.cache.set(key, { result, expiresAt: this.now() + this.ttlMs });
+ const fetchedAt = this.now();
+ this.cache.set(key, { result, expiresAt: fetchedAt + this.ttlMs, staleUntil: fetchedAt + this.ttlMs + this.staleTtlMs });
}
return result;
})
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/subagentRunsBroadcast.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/subagentRunsBroadcast.test.ts
index 7d0dc643dd..01a05cf89e 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/subagentRunsBroadcast.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/subagentRunsBroadcast.test.ts
@@ -28,6 +28,8 @@ const h = vi.hoisted(() => {
scopeCurrent: true,
activeStamp: { dataOwnerId: 'active-owner', ownerGeneration: 2 },
deviceLinkInvoke: false,
+ sharedTask: false,
+ tapWindowBroadcast: vi.fn(),
ownerScopeKey: 'owner-a:1',
};
});
@@ -56,9 +58,11 @@ vi.mock('../../../appSessionState.js', () => ({
}));
vi.mock('../../../device-link/invoke-context.js', () => ({
isDeviceLinkInvoke: () => h.deviceLinkInvoke,
+ getDeviceLinkInvokeContext: () => (h.deviceLinkInvoke ? { sharedTask: h.sharedTask ? {} : undefined } : null),
}));
vi.mock('../../../device-link/broadcast-tap.js', () => ({
isDataOwnerBroadcastScopeCurrent: () => h.scopeCurrent,
+ tapWindowBroadcast: h.tapWindowBroadcast,
}));
vi.mock('../../../security/trustedAppRenderer.js', () => ({
assertTrustedAppRendererEvent: vi.fn(),
@@ -93,6 +97,7 @@ describe('Subagent runs broadcast boundary', () => {
h.persistSubagentTaskUpdate.mockResolvedValue(null);
h.scopeCurrent = true;
h.deviceLinkInvoke = false;
+ h.sharedTask = false;
h.ownerScopeKey = 'owner-a:1';
__resetSubagentReconcileFingerprintsForTests();
});
@@ -757,6 +762,15 @@ describe('Subagent runs broadcast boundary', () => {
);
});
+ it('forwards the change to device-link controllers with the same owner stamp', () => {
+ broadcastSubagentRunsInvalidated('session-1');
+
+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith(
+ SUBAGENT_RUNS_CHANGED_CHANNEL,
+ { sessionId: 'session-1', runId: null, created: false, firstForSession: false },
+ );
+ });
+
it('broadcasts a session-level invalidation for clear and rewind boundaries', () => {
broadcastSubagentRunsInvalidated('session-1');
@@ -980,6 +994,18 @@ describe('Subagent runs broadcast boundary', () => {
expect(h.getSubagentRunDetail).not.toHaveBeenCalled();
});
+ it.each([[false, true], [true, undefined]])(
+ 'declares the change push only to peers that can receive it (sharedTask=%s)', async (sharedTask, expected) => {
+ h.deviceLinkInvoke = true;
+ h.sharedTask = sharedTask;
+ h.listSubagentRuns.mockResolvedValue({ runs: [] });
+ registerSubagentRunsIpc();
+ const list = h.ipcHandlers.get('local-db:subagent-runs:list')!;
+ const response = await list({}, { sessionId: 'session-1' }) as { changePush?: boolean };
+ expect(response.changePush).toBe(expected);
+ },
+ );
+
it('validates and forwards provider-scoped detail lookups', async () => {
registerSubagentRunsIpc();
const detail = h.ipcHandlers.get('local-db:subagent-runs:detail');
diff --git a/apps/desktop/src/main/localDb/ipc/subagentRuns.ts b/apps/desktop/src/main/localDb/ipc/subagentRuns.ts
index 0c52a8b7cc..8a56162778 100644
--- a/apps/desktop/src/main/localDb/ipc/subagentRuns.ts
+++ b/apps/desktop/src/main/localDb/ipc/subagentRuns.ts
@@ -23,9 +23,10 @@ import {
} from '@cindy/maker-shared/subagent-workspace';
import { activeOwnerScopeKey, getActiveDataOwnerPushStamp } from '../../appSessionState.js';
-import { isDeviceLinkInvoke } from '../../device-link/invoke-context.js';
+import { getDeviceLinkInvokeContext, isDeviceLinkInvoke } from '../../device-link/invoke-context.js';
import {
isDataOwnerBroadcastScopeCurrent,
+ tapWindowBroadcast,
type DataOwnerBroadcastScope,
} from '../../device-link/broadcast-tap.js';
import {
@@ -331,6 +332,10 @@ export function broadcastSubagentRunsChanged(
const ownerStamp = hasCapturedScope
? ownerScope.ownerStamp
: getActiveDataOwnerPushStamp();
+ // Controllers of this task receive the same change over device-link (session topic),
+ // so their Subagent tab discovery can stop polling the list every few seconds.
+ if (hasCapturedScope) tapWindowBroadcast(SUBAGENT_RUNS_CHANGED_CHANNEL, payload, ownerStamp);
+ else tapWindowBroadcast(SUBAGENT_RUNS_CHANGED_CHANNEL, payload);
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed() && isTrustedAppRendererWindow(window)) {
try {
@@ -417,6 +422,10 @@ export function registerSubagentRunsIpc(
supported: page !== null,
runs: (page?.runs ?? []).map((run) => maskUnavailableResume(run, sessionId)),
...(page?.nextCursor ? { nextCursor: page.nextCursor } : {}),
+ // This Host forwards local-db:subagent-runs:changed to the task's controllers.
+ // Shared-task guests may read the list but their capture fence does not admit
+ // the push channel, so declaring it would only slow their polling down.
+ ...(getDeviceLinkInvokeContext()?.sharedTask ? {} : { changePush: true }),
} satisfies SubagentRunsListResponse;
});
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
index 8599661a31..f6b6c96671 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts
@@ -284,6 +284,110 @@ describe('device-link controller mirror — end-to-end scenarios', () => {
},
);
+ // A durable push both invalidates the view (page read at +500 ms) and arms the
+ // lost-push repair (+1.5 s). The repair must only read when nothing read the
+ // latest page after the push: a running turn used to cost two page reads plus an
+ // interaction snapshot per notice on the host.
+ it.each(['covered', 'uncovered'])('reads the latest page once per durable push (%s)', async (scenario) => {
+ vi.useFakeTimers();
+ const s = sid();
+ let leave: (() => void) | undefined;
+ try {
+ host.enableHistoryView();
+ host.seedSession(s, {}, [dbMessage(s, 'answer', 'answer', '2026-06-15T00:00:00Z')]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ leave = makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getRemoteHistoryView(s)!.getSnapshot().ready).toBe(true);
+ const reads = () => host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view').length;
+ const interactions = () => host.invoke.mock.calls.filter(([, channel]) => channel === 'maker:get-pending-interactions').length;
+ // The initial read and the push must not share a millisecond: only a read
+ // issued strictly after the push counts as covering it.
+ await vi.advanceTimersByTimeAsync(10);
+ const readsBefore = reads();
+ const interactionsBefore = interactions();
+ const next = dbMessage(s, 'next', 'next answer', '2026-06-15T00:00:01Z');
+ if (scenario === 'covered') {
+ // messages:created invalidates the view; that read covers the repair.
+ host.hostMessage(s, next);
+ await vi.advanceTimersByTimeAsync(600);
+ expect(reads()).toBe(readsBefore + 1);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(reads()).toBe(readsBefore + 1);
+ expect(interactions()).toBe(interactionsBefore);
+ } else {
+ // The created push was lost; a later sealed text event is durable but does
+ // not invalidate the view, so the repair is the only read of the row.
+ host.hostMessage(s, next, { lossy: true });
+ host.push('maker:event', { sessionId: s, persistId: 'client-next',
+ event: { type: 'text', source: 'claude-code', data: { text: 'next answer', isFinal: true } } });
+ await vi.advanceTimersByTimeAsync(600);
+ expect(reads()).toBe(readsBefore);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(reads()).toBe(readsBefore + 1);
+ expect(interactions()).toBe(interactionsBefore + 1);
+ }
+ expect(getRemoteHistoryView(s)!.getSnapshot().items.flatMap((item) => item.type === 'messages' ? item.messages : [])
+ .map((row) => row.content)).toContain('next answer');
+ } finally {
+ leave?.();
+ makerChatStore.purgeSession(s);
+ vi.useRealTimers();
+ }
+ });
+
+ // A read that began after the push but failed, or that began before a later push
+ // in the same repair window, certifies nothing: the repair must still read.
+ it.each(['read-failed', 'later-push'])('repairs when the covering read cannot certify the push (%s)', async (scenario) => {
+ vi.useFakeTimers();
+ const s = sid();
+ let leave: (() => void) | undefined;
+ try {
+ host.enableHistoryView();
+ host.seedSession(s, {}, [dbMessage(s, 'answer', 'answer', '2026-06-15T00:00:00Z')]);
+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);
+ leave = makerChatStore.enterView(s);
+ makerChatStore.ensureInitialMessages(s);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getRemoteHistoryView(s)!.getSnapshot().ready).toBe(true);
+ const reads = () => host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:view').length;
+ await vi.advanceTimersByTimeAsync(10);
+ const readsBefore = reads();
+ const next = dbMessage(s, 'next', 'next answer', '2026-06-15T00:00:01Z');
+ if (scenario === 'read-failed') {
+ const original = host.invoke.getMockImplementation()!;
+ let failNext = true;
+ host.invoke.mockImplementation(async (device, channel, args) => {
+ if (channel === 'local-db:messages:view' && failNext) { failNext = false; throw new Error('link hiccup'); }
+ return original(device, channel, args);
+ });
+ host.hostMessage(s, next);
+ await vi.advanceTimersByTimeAsync(600);
+ expect(reads()).toBe(readsBefore + 1); // the invalidation read, which failed
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(reads()).toBe(readsBefore + 2); // the repair read must still happen
+ } else {
+ // Created push (and its 500 ms read) first; a second durable push whose
+ // created frame was lost arrives afterwards inside the same repair window.
+ host.hostMessage(s, dbMessage(s, 'early', 'early answer', '2026-06-15T00:00:00.500Z'));
+ await vi.advanceTimersByTimeAsync(600);
+ expect(reads()).toBe(readsBefore + 1);
+ host.hostMessage(s, next, { lossy: true });
+ host.push('maker:event', { sessionId: s, persistId: 'client-next',
+ event: { type: 'text', source: 'claude-code', data: { text: 'next answer', isFinal: true } } });
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(reads()).toBe(readsBefore + 2);
+ }
+ expect(getRemoteHistoryView(s)!.getSnapshot().items.flatMap((item) => item.type === 'messages' ? item.messages : [])
+ .map((row) => row.content)).toContain('next answer');
+ } finally {
+ leave?.();
+ makerChatStore.purgeSession(s);
+ vi.useRealTimers();
+ }
+ });
+
it.each(['success', 'failed', 'hidden', 'collapsed'])(
'waits for refreshed expanded details before releasing a read receipt: %s', async (scenario) => {
const s = sid();
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index ad70be0709..edc78cee4c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -1174,6 +1174,15 @@ function CCAgentSessionContent({
if (!isCurrentSubagentRunsChange(payload, ownerStamp, sessionId)) return;
onChanged();
}),
+ // The data-owning device forwards its own change push over the link (session
+ // topic); discovery only listens once that Host's list reply declared it.
+ subscribeRemoteChanges: (onChanged) =>
+ window.electronAPI.deviceLink.onRemotePush((push, localOwnerStamp) => {
+ if (push.deviceId !== remoteDeviceId || push.channel !== 'local-db:subagent-runs:changed') return;
+ if ((push.payload as { sessionId?: unknown } | null)?.sessionId !== sessionId) return;
+ if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;
+ onChanged();
+ }),
registerTab: () => openSubagentsTab(sessionId, SUBAGENT_TAB_REGISTER_ONLY),
isRequestOwnerCurrent: () => isDataOwnerGenerationCurrent(requestOwner),
onPresenceChange: (present) => setSessionOwningDurablePiRuns(present ? sessionId : null),
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/subagentTabDiscovery.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/subagentTabDiscovery.test.ts
index 1b211c6d30..741dec930b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/subagentTabDiscovery.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/subagentTabDiscovery.test.ts
@@ -171,6 +171,117 @@ describe('startSubagentTabDiscovery', () => {
expect(REMOTE_SUBAGENT_DISCOVERY_POLL_MS).toBeGreaterThanOrEqual(5_000);
});
+ describe('Host change push', () => {
+ // Every open remote task used to pay a list read every 5s for the life of its
+ // view, Pi or not. A Host that declares `changePush` is read on its push instead.
+ function remoteHarness() {
+ const h = harness();
+ let onRemote: (() => void) | null = null;
+ const unsubscribeRemote = vi.fn(() => { onRemote = null; });
+ const subscribeRemoteChanges = vi.fn((cb: () => void) => { onRemote = cb; return unsubscribeRemote; });
+ return { ...h, subscribeRemoteChanges, unsubscribeRemote, emitRemoteChange: () => onRemote?.() };
+ }
+
+ it('reads on the push and drops the poll to the fallback once the Host declares it', async () => {
+ const h = remoteHarness();
+ h.listRemote.mockResolvedValue({ ...EMPTY, changePush: true });
+ const dispose = startSubagentTabDiscovery({
+ sessionId: 's1', deviceId: 'device-a',
+ listLocal: h.listLocal, listRemote: h.listRemote,
+ subscribeLocalChanges: h.subscribeLocalChanges, subscribeRemoteChanges: h.subscribeRemoteChanges,
+ registerTab: h.registerTab, isRequestOwnerCurrent: () => true,
+ pushFallbackPollMs: 60_000,
+ });
+ await settle();
+ // Initial read, plus the one catch-up read after the listener was installed.
+ expect(h.listRemote).toHaveBeenCalledTimes(2);
+ expect(h.subscribeRemoteChanges).toHaveBeenCalledOnce();
+ // The 5s discovery cadence no longer applies.
+ await vi.advanceTimersByTimeAsync(REMOTE_SUBAGENT_DISCOVERY_POLL_MS * 4);
+ await settle();
+ expect(h.listRemote).toHaveBeenCalledTimes(2);
+ // The Host's push triggers the read that registers the tab.
+ h.listRemote.mockResolvedValue({ ...runs(1), changePush: true });
+ h.emitRemoteChange();
+ await settle();
+ expect(h.listRemote).toHaveBeenCalledTimes(3);
+ expect(h.registerTab).toHaveBeenCalledOnce();
+ // One-shot without a presence consumer: the push subscription is released too.
+ expect(h.unsubscribeRemote).toHaveBeenCalled();
+ dispose();
+ });
+
+ it('keeps the fallback poll for a lost push and coalesces a push that lands mid-read', async () => {
+ const h = remoteHarness();
+ let finish!: (value: SubagentRunsListResponse) => void;
+ h.listRemote.mockResolvedValue({ ...EMPTY, changePush: true });
+ const presence: boolean[] = [];
+ const dispose = startSubagentTabDiscovery({
+ sessionId: 's1', deviceId: 'device-a',
+ listLocal: h.listLocal, listRemote: h.listRemote,
+ subscribeLocalChanges: h.subscribeLocalChanges, subscribeRemoteChanges: h.subscribeRemoteChanges,
+ registerTab: h.registerTab, isRequestOwnerCurrent: () => true,
+ onPresenceChange: (present) => presence.push(present),
+ pushFallbackPollMs: 1_000,
+ });
+ await settle();
+ expect(presence).toEqual([false, false]); // initial + post-subscription catch-up
+ // Fallback read after the push-backed cadence, not the 5s one.
+ h.listRemote.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ await vi.advanceTimersByTimeAsync(1_000);
+ await settle();
+ expect(h.listRemote).toHaveBeenCalledTimes(3);
+ // A push during that read is answered by exactly one follow-up read.
+ h.emitRemoteChange();
+ h.emitRemoteChange();
+ h.listRemote.mockResolvedValue({ ...runs(1), changePush: true });
+ finish({ ...EMPTY, changePush: true });
+ await settle();
+ expect(h.listRemote).toHaveBeenCalledTimes(4);
+ expect(presence).toEqual([false, false, false, true]);
+ expect(h.registerTab).toHaveBeenCalledOnce();
+ dispose();
+ expect(h.unsubscribeRemote).toHaveBeenCalled();
+ });
+
+ it('catches a change pushed between the Host snapshot and the listener install', async () => {
+ const h = remoteHarness();
+ // The first reply predates a run that appeared right after the Host captured it;
+ // its push was emitted before any listener existed.
+ h.listRemote.mockResolvedValueOnce({ ...EMPTY, changePush: true });
+ h.listRemote.mockResolvedValue({ ...runs(1), changePush: true });
+ const dispose = startSubagentTabDiscovery({
+ sessionId: 's1', deviceId: 'device-a',
+ listLocal: h.listLocal, listRemote: h.listRemote,
+ subscribeLocalChanges: h.subscribeLocalChanges, subscribeRemoteChanges: h.subscribeRemoteChanges,
+ registerTab: h.registerTab, isRequestOwnerCurrent: () => true,
+ pushFallbackPollMs: 60_000,
+ });
+ await settle();
+ // Registered from the catch-up read, not after the 60s fallback.
+ expect(h.listRemote).toHaveBeenCalledTimes(2);
+ expect(h.registerTab).toHaveBeenCalledOnce();
+ dispose();
+ });
+
+ it('keeps the discovery poll for a Host that does not declare the push', async () => {
+ const h = remoteHarness();
+ h.listRemote.mockResolvedValue(EMPTY);
+ const dispose = startSubagentTabDiscovery({
+ sessionId: 's1', deviceId: 'device-a',
+ listLocal: h.listLocal, listRemote: h.listRemote,
+ subscribeLocalChanges: h.subscribeLocalChanges, subscribeRemoteChanges: h.subscribeRemoteChanges,
+ registerTab: h.registerTab, isRequestOwnerCurrent: () => true,
+ });
+ await settle();
+ await vi.advanceTimersByTimeAsync(REMOTE_SUBAGENT_DISCOVERY_POLL_MS);
+ await settle();
+ expect(h.listRemote).toHaveBeenCalledTimes(2);
+ expect(h.subscribeRemoteChanges).not.toHaveBeenCalled();
+ dispose();
+ });
+ });
+
it('never registers a tab when the owner reports no runs or no support', async () => {
const h = harness();
h.listRemote.mockResolvedValue(EMPTY);
diff --git a/apps/desktop/src/renderer/features/cc-agent/subagentTabDiscovery.ts b/apps/desktop/src/renderer/features/cc-agent/subagentTabDiscovery.ts
index d70a139c09..d4f0d9df2b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/subagentTabDiscovery.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/subagentTabDiscovery.ts
@@ -11,22 +11,23 @@
* — and once the records are gone (`/clear`, a rewind past their start, parent
* deletion) it has to go away again. Falling edges therefore keep watching past
* registration: the local path keeps its change subscription, and the remote
- * path — which has no change push at all — drops to a much slower poll rather
- * than stopping. Without a presence consumer both stop at registration, exactly
- * as before.
+ * path keeps a slow poll (or its change push, see below) rather than stopping.
+ * Without a presence consumer both stop at registration, exactly as before.
*
* Two data paths, one contract:
* - local task → local DB read + `subagentRuns.onChanged` push.
* - remote task → the durable truth lives on the data-owning device, so the
- * read goes through device-link. There is no remote change push for this
- * channel, so a low-frequency poll fills in. It is deliberately 5s-scale:
- * the only thing it can discover is "a tab should exist", and the panel's
- * own faster poll takes over the moment it does.
+ * read goes through device-link. A Host that forwards its change push over
+ * the link says so in the list reply (`changePush`); the controller then
+ * re-reads on that push and only keeps a slow fallback poll. An older Host
+ * gives no such signal, and the 5s-scale discovery poll fills in: the only
+ * thing it can discover is "a tab should exist", and the panel's own faster
+ * poll takes over the moment it does.
*/
import type { SubagentRunsListResponse } from '@cindy/maker-shared/subagent-workspace';
-/** Remote discovery cadence. Coarse on purpose — see the file docblock. */
+/** Remote discovery cadence without a change push. Coarse on purpose — see the file docblock. */
export const REMOTE_SUBAGENT_DISCOVERY_POLL_MS = 5_000;
/**
@@ -37,11 +38,20 @@ export const REMOTE_SUBAGENT_DISCOVERY_POLL_MS = 5_000;
* first Subagent notices five seconds. This one only decides when an entry for
* records that no longer exist goes away — nobody is waiting on that, and the
* cost is one device-link round per visible, already-registered remote task. It
- * is also the only thing that carries a remote `/clear` or rewind across: that
- * boundary emits a local change push the controller never receives.
+ * is also the only thing that carries a remote `/clear` or rewind across on a
+ * Host without the change push: that boundary emits a local change push the
+ * controller never receives.
*/
export const REMOTE_SUBAGENT_PRESENCE_POLL_MS = 20_000;
+/**
+ * Remote cadence once the Host has declared its change push. Every change that
+ * matters arrives as a push, so this only guards against a push lost to a link
+ * reset; one read per minute per open remote task is the whole cost. Every open
+ * remote task used to pay the 5s poll for the lifetime of its view, Pi or not.
+ */
+export const REMOTE_SUBAGENT_PUSH_FALLBACK_POLL_MS = 60_000;
+
export interface SubagentTabDiscoveryOptions {
readonly sessionId: string;
/** Data-owning device for a device-link task; null/undefined = this machine. */
@@ -52,6 +62,12 @@ export interface SubagentTabDiscoveryOptions {
readonly listRemote: (deviceId: string) => Promise<SubagentRunsListResponse>;
/** Local-only change push. Returns its unsubscribe. */
readonly subscribeLocalChanges: (onChanged: () => void) => () => void;
+ /**
+ * Change push forwarded from the data-owning device, already filtered to this
+ * task. Only used after the Host's list reply declared `changePush`. Returns
+ * its unsubscribe.
+ */
+ readonly subscribeRemoteChanges?: (onChanged: () => void) => () => void;
/** Idempotent tab registration. */
readonly registerTab: () => Promise<void>;
/**
@@ -67,6 +83,8 @@ export interface SubagentTabDiscoveryOptions {
readonly pollMs?: number;
/** Overrides the post-registration remote cadence; tests use it. */
readonly presencePollMs?: number;
+ /** Overrides the push-backed remote fallback cadence; tests use it. */
+ readonly pushFallbackPollMs?: number;
}
/**
@@ -79,18 +97,23 @@ export function startSubagentTabDiscovery(options: SubagentTabDiscoveryOptions):
listLocal,
listRemote,
subscribeLocalChanges,
+ subscribeRemoteChanges,
registerTab,
isRequestOwnerCurrent,
onPresenceChange,
pollMs = REMOTE_SUBAGENT_DISCOVERY_POLL_MS,
presencePollMs = REMOTE_SUBAGENT_PRESENCE_POLL_MS,
+ pushFallbackPollMs = REMOTE_SUBAGENT_PUSH_FALLBACK_POLL_MS,
} = options;
const remote = typeof deviceId === 'string' && deviceId.length > 0;
let disposed = false;
let registered = false;
+ /** Set once the remote Host's reply declared it forwards its change push. */
+ let remotePushDriven = false;
let poll: ReturnType<typeof setTimeout> | null = null;
let unsubscribe: (() => void) | null = null;
+ let unsubscribeRemote: (() => void) | null = null;
const stopPolling = (): void => {
if (poll === null) return;
@@ -105,6 +128,14 @@ export function startSubagentTabDiscovery(options: SubagentTabDiscoveryOptions):
if (disposed || !sessionId || (registered && !onPresenceChange)) return;
const response = remote ? await listRemote(deviceId as string) : await listLocal();
if (disposed || !isRequestOwnerCurrent()) return;
+ if (remote && response.changePush === true && subscribeRemoteChanges && !unsubscribeRemote) {
+ remotePushDriven = true;
+ unsubscribeRemote = subscribeRemoteChanges(runRemoteChange);
+ // A change pushed after the Host captured this reply but before the listener
+ // existed was missed; read once more instead of trusting the snapshot for the
+ // whole slow fallback interval. The re-read finds the listener installed.
+ remoteChangeDuringRound = true;
+ }
// `unsupported` is the honest answer from a device that has no durable
// Subagent store; an empty list means this task simply has no children yet.
//
@@ -122,12 +153,15 @@ export function startSubagentTabDiscovery(options: SubagentTabDiscoveryOptions):
// Registration reached its one-shot goal; the panel owns reads from here.
// A presence consumer keeps both watchers, because "should this entry still
// be offered" stays a live question — the remote one only drops to
- // `presencePollMs`, since the panel's own faster poll never reports back
- // here and a remote clear has no push to announce itself.
+ // `presencePollMs` (or the push fallback), since the panel's own faster poll
+ // never reports back here and a remote clear has no push to announce itself
+ // on an older Host.
if (onPresenceChange) return;
stopPolling();
unsubscribe?.();
unsubscribe = null;
+ unsubscribeRemote?.();
+ unsubscribeRemote = null;
};
const runDiscovery = (): void => {
@@ -142,15 +176,36 @@ export function startSubagentTabDiscovery(options: SubagentTabDiscoveryOptions):
* round still re-arms — the link coming back is exactly what this poll is
* waiting for.
*/
+ let remoteRoundInFlight = false;
+ let remoteChangeDuringRound = false;
const runRemoteDiscovery = (): void => {
- poll = null;
+ stopPolling();
+ remoteRoundInFlight = true;
void discover().catch(() => undefined).finally(() => {
+ remoteRoundInFlight = false;
if (disposed) return;
if (registered && !onPresenceChange) return;
- poll = setTimeout(runRemoteDiscovery, registered ? presencePollMs : pollMs);
+ // A push that landed mid-read may describe a newer state than the reply.
+ if (remoteChangeDuringRound) {
+ remoteChangeDuringRound = false;
+ runRemoteDiscovery();
+ return;
+ }
+ const delay = remotePushDriven ? pushFallbackPollMs : registered ? presencePollMs : pollMs;
+ poll = setTimeout(runRemoteDiscovery, delay);
});
};
+ /** Host change push: read now, coalescing with a round already in flight. */
+ function runRemoteChange(): void {
+ if (disposed) return;
+ if (remoteRoundInFlight) {
+ remoteChangeDuringRound = true;
+ return;
+ }
+ runRemoteDiscovery();
+ }
+
if (remote) {
runRemoteDiscovery();
} else {
@@ -163,5 +218,7 @@ export function startSubagentTabDiscovery(options: SubagentTabDiscoveryOptions):
stopPolling();
unsubscribe?.();
unsubscribe = null;
+ unsubscribeRemote?.();
+ unsubscribeRemote = null;
};
}
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 1c3937c6e7..509d3e9119 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -7539,18 +7539,35 @@ const backgroundTaskReconcileEpoch = new Map<string, number>();
// keeps streaming. Keep a small, per-session repair debounce so any later
// remote event can heal the missing durable row without turning the live
// stream into a polling loop.
+//
+// The same pushes also invalidate the history view, which re-reads the page
+// ~500 ms later. The repair therefore records when the LAST push of its window
+// arrived and only reads when no successful latest-page read started after that
+// moment: a read issued after the notice already shows whatever the push
+// announced, so a second page read 1 s later, plus its interaction snapshot, buys
+// nothing. A turn that emits a notice every 500 ms previously cost two full page
+// reads and one interaction read per notice on the host. A read that failed does
+// not certify anything; the repair then reads again.
const REMOTE_MESSAGE_REPAIR_DELAY_MS = 1_500;
-const remoteMessageRepairTimers = new Map<string, ReturnType<typeof setTimeout>>();
+const remoteMessageRepairTimers = new Map<string, { timer: ReturnType<typeof setTimeout>; noticedAt: number }>();
function scheduleRemoteMessageRepair(sessionId: string): void {
- if (!sessionId || remoteMessageRepairTimers.has(sessionId)) return;
- remoteMessageRepairTimers.set(
- sessionId,
- setTimeout(() => {
+ if (!sessionId) return;
+ const pending = remoteMessageRepairTimers.get(sessionId);
+ if (pending) {
+ // Debounce stays anchored to the first push, but a later push in the window
+ // must also be covered by the read that lets the repair skip.
+ pending.noticedAt = Date.now();
+ return;
+ }
+ const entry: { timer: ReturnType<typeof setTimeout>; noticedAt: number } = {
+ noticedAt: Date.now(),
+ timer: setTimeout(() => {
remoteMessageRepairTimers.delete(sessionId);
- void reconcileRemoteMessages(sessionId, { repair: true }).catch(() => undefined);
+ void reconcileRemoteMessages(sessionId, { repair: true, coveredSince: entry.noticedAt }).catch(() => undefined);
}, REMOTE_MESSAGE_REPAIR_DELAY_MS),
- );
+ };
+ remoteMessageRepairTimers.set(sessionId, entry);
}
function invalidateBackgroundTaskReconcile(sessionId: string): number {
@@ -9824,7 +9841,7 @@ function __teardownGlobalListeners(): void {
pendingTextDeltaBatches.clear();
for (const timer of backgroundTaskReconcileTimers.values()) clearTimeout(timer);
backgroundTaskReconcileTimers.clear();
- for (const timer of remoteMessageRepairTimers.values()) clearTimeout(timer);
+ for (const repair of remoteMessageRepairTimers.values()) clearTimeout(repair.timer);
remoteMessageRepairTimers.clear();
clearDeferredStateNotificationTimer();
pendingDeferredStateNotifications.clear();
@@ -12748,7 +12765,12 @@ function reconcileOpenSessionOrigins(): void {
*/
const _remoteReconcileInFlight = new Map<
string,
- { run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean; preserveClientIds: Set<string> }
+ {
+ run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean;
+ /** Latest push time among the repairs merged into this flight (Infinity = uncovered); see reconcileRemoteMessages. */
+ rerunCoveredSince?: number;
+ preserveClientIds: Set<string>;
+ }
>();
type HistoryViewForceFlight = {
@@ -12776,6 +12798,12 @@ function reconcileRemoteMessages(sessionId: string, opts?: {
*/
activationRead?: boolean;
preserveClientIds?: ReadonlySet<string>;
+ /**
+ * Repair only: the time the triggering push arrived. A latest-page read started
+ * strictly after it already covers the push, so the repair joins that read (or skips
+ * when it has finished) instead of forcing another page and interaction read.
+ */
+ coveredSince?: number;
}): Promise<boolean> {
const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
if (deviceId && isRemoteDeviceMarkedDisconnected(deviceId)) return Promise.resolve(false);
@@ -12783,6 +12811,10 @@ function reconcileRemoteMessages(sessionId: string, opts?: {
if (view && (view.getSnapshot().ready || opts?.freshHistory || opts?.repair)) {
const runHistoryView = (flight?: HistoryViewForceFlight) => {
const syncToken = noteRemoteSessionSyncStarted(sessionId);
+ // A post-notice read satisfies the "read after the signal" rule below by
+ // construction: the signal is the push, and the read began after it. Same
+ // millisecond is not "after": the read may have been issued first.
+ const covered = opts?.coveredSince !== undefined && view.latestReadStartedAt() > opts.coveredSince;
const rowsAtStart = new Map((sessions.get(sessionId)?.messages ?? []).map((row) => [row.clientId, row]));
const epochAtStart = _messagesEpoch.get(sessionId) ?? 0;
const noteHydration = (before: readonly ChatMessage[], after: readonly ChatMessage[]) => {
@@ -12798,10 +12830,22 @@ function reconcileRemoteMessages(sessionId: string, opts?: {
};
// Read receipts also need a post-signal page: joining a pre-existing read
// cannot certify this sync generation. Preserve the view and expansion.
+ // Interaction requests travel the same ordered reliable stream as the push
+ // that is being repaired, so a covered repair leaves their resync to the
+ // turn-end / focus / reconnect reconciles that still run unconditionally.
return Promise.all([
- view.refresh(false, !opts?.activationRead),
- reconcilePendingInteractions(sessionId),
+ covered
+ ? (view.isReadingLatest() ? view.refresh(false, false) : Promise.resolve())
+ : view.refresh(false, !opts?.activationRead),
+ covered ? Promise.resolve(0) : reconcilePendingInteractions(sessionId),
]).then(async () => {
+ // Covered means a read began after the notice AND applied. A failed read
+ // (error is cleared by the next read's start, so use the success stamp)
+ // leaves the push unrepaired: issue the repair read the skip would have saved.
+ if (covered && opts?.coveredSince !== undefined && view.isActive()
+ && view.latestReadOkStartedAt() <= opts.coveredSince) {
+ await Promise.all([view.refresh(false, !opts?.activationRead), reconcilePendingInteractions(sessionId)]);
+ }
if (getRemoteHistoryView(sessionId) !== view || !view.isActive()) return false;
if (isHistoryViewUnavailable(view.getSnapshot().error)) {
releaseRemoteHistoryView(sessionId, view);
@@ -12934,11 +12978,22 @@ function reconcileRemoteMessages(sessionId: string, opts?: {
// snapshot-less resync can authoritatively seal the previous block.
inFlight.preserveClientIds = new Set(opts.preserveClientIds);
}
- if (opts?.repair) inFlight.rerunRepair = true;
- void reconcilePendingInteractions(sessionId).catch(() => undefined);
+ if (opts?.repair) {
+ inFlight.rerunRepair = true;
+ // A read certifies only notices that precede it, so the rerun must start
+ // after the LATEST notice merged here; a repair without a notice time can
+ // never be certified.
+ inFlight.rerunCoveredSince = Math.max(inFlight.rerunCoveredSince ?? -Infinity, opts.coveredSince ?? Infinity);
+ }
+ // A push-driven repair is served by the rerun; only explicit resyncs need
+ // the interaction snapshot refreshed ahead of it.
+ if (!opts?.repair) void reconcilePendingInteractions(sessionId).catch(() => undefined);
return inFlight.run;
}
- const entry: { run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean; preserveClientIds: Set<string> } = {
+ const entry: {
+ run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean;
+ rerunCoveredSince?: number; preserveClientIds: Set<string>;
+ } = {
run: Promise.resolve(false),
rerun: false,
rerunForce: false,
@@ -12954,12 +13009,16 @@ function reconcileRemoteMessages(sessionId: string, opts?: {
const rerun = entry.rerun;
const rerunForce = entry.rerunForce;
const rerunRepair = entry.rerunRepair;
+ const rerunCoveredSince = entry.rerunCoveredSince;
// 先摘掉在飞标记,再补跑 —— 补跑会自己建新的 entry,期间来的触发继续被那一份合并。
_remoteReconcileInFlight.delete(sessionId);
if (rerun && sessions.has(sessionId)) {
applied = await reconcileRemoteMessages(
sessionId,
- { force: rerunForce, repair: rerunRepair, preserveClientIds: entry.preserveClientIds },
+ {
+ force: rerunForce, repair: rerunRepair, preserveClientIds: entry.preserveClientIds,
+ ...(rerunCoveredSince !== undefined ? { coveredSince: rerunCoveredSince } : {}),
+ },
);
}
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 1aa373ed75..dad74e2f68 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1,5 +1,26 @@
# 跨端协议兼容
+## 远程链路流量治理:交互优先名额与 Subagent 变更推送
+
+交互类 invoke(`maker:send`、`maker:abort-session`、`maker:input:enqueue` / `steer` / `stop` /
+`resume` / `retry-last-error` / `remove`、`maker:resolve-interaction`、`maker:agent-task:stop`,
+集合见 `packages/device-link/src/invokePolicy.ts` 的 `isInteractiveInvoke`)在控制端
+`InvokeScheduler` 与被控端 dispatch 准入上各多 2 个(被控端全局多 4 个)消息名额,且在控制端
+排队时先于普通前台请求出队;字节上限、超时、重试、授权与 wire 格式都不变。旧控制端没有本地
+名额但仍可被新被控端多放行;旧被控端对新控制端照原上限拒绝,控制端沿用既有 BACKPRESSURE
+重试。`maker:predict-prompt` 改为控制端后台档(只影响本地排队顺序)。
+
+`local-db:subagent-runs:list` 的响应新增可选 `changePush: true`,表示该被控端会把本机
+`local-db:subagent-runs:changed`(payload 顶层 `sessionId`,路由到 `session:<id>` topic)经
+link 转发给订阅了该任务的控制端。新桌面控制端收到该标记后改为按推送重读、只保留 60 秒的
+兜底轮询;旧被控端不带标记,控制端保持原 5 秒 / 20 秒轮询;旧控制端忽略该字段和未知推送
+(Mobile 当前不消费此推送)。不新增 relay 类型、数据库 schema、权限或 Mobile 原生指纹,
+云端无需改动。
+
+桌面控制端的持久推送修复读(`messages:created` / 带 persistId 的 `maker:event` 之后 1.5 秒
+重读最新页 + 交互快照)只在「窗口内最后一条推送之后已有一次成功应用的最新页读取」时才省掉;
+读取失败或晚于该读取的推送仍会触发修复读。本地行为,不进入 wire。
+
## Agent 预热与远程发送路径
新增 invoke `maker:session:prewarm(sessionId, createOpts)`,Desktop 本机 Renderer 与 device-link
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 354a480764..b60ad13807 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -204,7 +204,11 @@ Desktop 向曾协商可靠传输、当前发送链路未就绪的设备发起新
单 peer,不重启共享 relay、不重放已发出的写操作;回归覆盖另一 peer 与 legacy 请求继续工作。
普通出站 invoke 在共享 `InvokeScheduler` 中按目标设备排队:每台最多 12 个在途,
-其中 PR 引用/状态、定时任务侧栏和用量同步等后台查询最多 4 个。
+其中 PR 引用/状态、定时任务侧栏、用量同步和轮后提示预测等后台查询最多 4 个。
+发送、插话、停止、回答交互这类用户正在等的写入(`invokePolicy.ts` 的
+`isInteractiveInvoke`)另有 2 个专用名额,排队时先于普通前台请求出队,不与历史和列表读取
+竞争;被控端 dispatch 的 per-controller 16 / 全局 64 消息准入对它们同样各多 2 / 4 个,
+字节准入不放宽。这只是本地准入顺序,不改变授权、超时与重试。
同一真实设备的普通远控与多个共享任务共用并发和等待配额;取消仍按各自 scoped peer
隔离,关闭一个任务不会取消其他任务或普通远控请求,transport 的任务范围保持不变。
任务列表首拉与恢复探测走前台配额(仍受总并发 12 限制);Desktop 的周期弱刷新与归档
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index ee5bedd098..2ed609c4ac 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -246,14 +246,15 @@ describe('outbound invoke admission', () => {
for (let i = 0; i < 6; i++) calls.push(h.client.invoke(peers[i % 3], {
channel: 'git-context:pr-refs:list', args: [i],
}).catch(e => e));
+ // An ordinary foreground write: sends are interactive and have their own allowance.
for (let i = 0; i < 10; i++) calls.push(h.client.invoke(peers[i % 3], {
- channel: 'maker:send', args: [i],
+ channel: 'maker:input:update-text', args: [i],
}).catch(e => e));
const sent = () => h.current().sent.filter(e => e.kind === 'invoke' && e.dst === 'desktop');
expect(sent()).toHaveLength(12);
expect(sent().filter(e => (e.payload as { channel: string }).channel === 'git-context:pr-refs:list')).toHaveLength(4);
expect(sent().slice(0, 3).map(e => e.sharedTask?.sharedTaskId)).toEqual([undefined, 'task-a', 'task-b']);
- calls.push(h.client.invoke(sharedTaskHostPeer('task-c', 'other'), { channel: 'maker:send', args: [] }).catch(e => e));
+ calls.push(h.client.invoke(sharedTaskHostPeer('task-c', 'other'), { channel: 'maker:input:update-text', args: [] }).catch(e => e));
expect(h.current().sent.filter(e => e.kind === 'invoke' && e.dst === 'other')).toHaveLength(1);
// A normal-stream response releases shared capacity; the next task keeps its scoped route.
h.current().push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'desktop', id: sent()[4].id,
@@ -261,7 +262,7 @@ describe('outbound invoke admission', () => {
await vi.advanceTimersByTimeAsync(1);
expect(sent()).toHaveLength(13);
expect(sent().at(-1)).toMatchObject({ dst: 'desktop', sharedTask: { sharedTaskId: 'task-b', target: { role: 'host' } },
- payload: { channel: 'maker:send', args: [8] } });
+ payload: { channel: 'maker:input:update-text', args: [8] } });
} finally {
h.client.stop(); await Promise.all(calls); vi.useRealTimers();
}
@@ -276,14 +277,14 @@ describe('outbound invoke admission', () => {
try {
h.client.start(); await vi.advanceTimersByTimeAsync(1); h.current().ack();
for (let i = 0; i < 12; i++) calls.push(h.client.invoke('a', {
- channel: 'maker:send', args: [i],
+ channel: 'maker:input:update-text', args: [i],
}).catch(e => e));
let current = true;
const cancelled = new Error('owner changed while queued');
const preSend = vi.fn(() => { if (!current) throw cancelled; });
- const stale = h.client.invoke('a', { channel: 'maker:send', args: ['stale'] }, undefined, { preSend }).catch(e => e);
+ const stale = h.client.invoke('a', { channel: 'maker:input:update-text', args: ['stale'] }, undefined, { preSend }).catch(e => e);
calls.push(stale);
- calls.push(h.client.invoke('a', { channel: 'maker:send', args: ['fresh'] }).catch(e => e));
+ calls.push(h.client.invoke('a', { channel: 'maker:input:update-text', args: ['fresh'] }).catch(e => e));
const sent = () => h.current().sent.filter(e => e.kind === 'invoke');
expect(sent()).toHaveLength(12);
expect(preSend).not.toHaveBeenCalled();
@@ -294,7 +295,7 @@ describe('outbound invoke admission', () => {
expect(await stale).toBe(cancelled);
expect(preSend).toHaveBeenCalledTimes(1);
expect(sent()).toHaveLength(13);
- expect(sent().at(-1)?.payload).toMatchObject({ channel: 'maker:send', args: ['fresh'] });
+ expect(sent().at(-1)?.payload).toMatchObject({ channel: 'maker:input:update-text', args: ['fresh'] });
expect(sent().some(e => (e.payload as { args: unknown[] }).args[0] === 'stale')).toBe(false);
expect(metrics.mock.calls.filter(([event]) => event.phase === 'sent')).toHaveLength(13);
} finally {
diff --git a/packages/device-link/src/__tests__/invokeScheduler.test.ts b/packages/device-link/src/__tests__/invokeScheduler.test.ts
index 1069ec4bea..e6f3dd4cfe 100644
--- a/packages/device-link/src/__tests__/invokeScheduler.test.ts
+++ b/packages/device-link/src/__tests__/invokeScheduler.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { InvokeScheduler } from "../invokeScheduler.js";
import { DeviceLinkError } from "../protocol.js";
-import { isBackgroundInvoke, bypassInvokeScheduling } from "../invokePolicy.js";
+import { isBackgroundInvoke, bypassInvokeScheduling, isInteractiveInvoke, resolveInvokePriority } from "../invokePolicy.js";
import { sharedTaskGuestPeer, sharedTaskHostPeer } from "../sharedTaskPeer.js";
function deferred() {
@@ -223,6 +223,49 @@ describe("invoke admission", () => {
await Promise.all(pending);
});
+ // A task view keeps up to twelve history/list reads in flight; before the allowance
+ // a send queued behind them until one settled (one relay round trip ≈ 0.5 s each).
+ it("admits interactive writes beyond the twelve-slot limit and ahead of queued reads", async () => {
+ const scheduler = new InvokeScheduler();
+ const reads = Array.from({ length: 12 }, deferred);
+ const running = reads.map((job) => scheduler.run("a", "foreground", 30_000, () => job.promise));
+ const started: string[] = [];
+ const queuedRead = scheduler.run("a", "foreground", 30_000, async () => { started.push("read"); });
+ const sends = Array.from({ length: 3 }, deferred);
+ const sent = sends.map((job, index) => scheduler.run("a", "interactive", 30_000, () => {
+ started.push(`send-${index}`);
+ return job.promise;
+ }));
+ // Two extra slots: the third send waits, but still ahead of the queued read.
+ expect(started).toEqual(["send-0", "send-1"]);
+ sends[0].resolve();
+ await flush();
+ expect(started).toEqual(["send-0", "send-1", "send-2"]);
+ sends[1].resolve();
+ sends[2].resolve();
+ await flush();
+ // Sends never borrow from the read limit: twelve reads are still running.
+ expect(started).toEqual(["send-0", "send-1", "send-2"]);
+ reads[0].resolve();
+ await flush();
+ expect(started).toEqual(["send-0", "send-1", "send-2", "read"]);
+ reads.forEach((job) => job.resolve());
+ await Promise.all([...running, queuedRead, ...sent]);
+ });
+
+ it("classifies sends and interaction answers as interactive, never demoted by a background hint", () => {
+ for (const channel of ["maker:input:enqueue", "maker:input:steer", "maker:input:stop", "maker:send", "maker:resolve-interaction", "maker:agent-task:stop"]) {
+ expect(isInteractiveInvoke(channel)).toBe(true);
+ expect(resolveInvokePriority(channel, true)).toBe("interactive");
+ }
+ // Queue-management edits and reads stay where they were.
+ expect(resolveInvokePriority("maker:input:move")).toBe("foreground");
+ expect(resolveInvokePriority("local-db:messages:view")).toBe("foreground");
+ expect(resolveInvokePriority("local-db:messages:view", true)).toBe("background");
+ expect(resolveInvokePriority("git-context:pr-status")).toBe("background");
+ expect(resolveInvokePriority("maker:predict-prompt")).toBe("background");
+ });
+
it("classifies PR reads as background and keeps control/lease maintenance outside the queue", () => {
expect(isBackgroundInvoke("git-context:pr-refs:list")).toBe(true);
expect(isBackgroundInvoke("git-context:pr-status")).toBe(true);
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 5af9c20e8f..510a7a3415 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -797,6 +797,9 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([
SESSION_SYNC_CHANNEL,
'local-db:messages:created',
'local-db:messages:deleted',
+ // 被控端 Subagent 记录变化(payload 顶层 sessionId → session:<id> topic):控制端的
+ // Subagent 页签发现据此重读一次,不再每 5 秒轮询 local-db:subagent-runs:list。
+ 'local-db:subagent-runs:changed',
// 被控端 terminal error 落库脏信号:控制端据此把已加载历史的远程会话标脏,下次打开重拉。
'local-db:session:error-persisted',
// 被控端项目手动顺序变化:控制端 / 手机首页按被控端正本重排。
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index c6e769dbf5..f43d2bf009 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -1,4 +1,4 @@
-import { isPeerResetRetryableInvoke, isBackgroundInvoke, bypassInvokeScheduling } from './invokePolicy.js';
+import { isPeerResetRetryableInvoke, bypassInvokeScheduling, resolveInvokePriority } from './invokePolicy.js';
import { InvokeScheduler } from './invokeScheduler.js';
import { SessionMessageReuse } from './sessionMessageReuse.js';
import {
@@ -1477,7 +1477,7 @@ export class DeviceLinkClient {
: result;
};
return bypassInvokeScheduling(payload) ? send() : this.invokeScheduler.run(
- dst, options?.background ?? isBackgroundInvoke(payload.channel),
+ dst, resolveInvokePriority(payload.channel, options?.background),
Math.min(timeoutMs ?? this.timing.requestTimeoutMs, 30_000), send,
);
}
diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.ts
index e8cb21ddfb..e07cae6946 100644
--- a/packages/device-link/src/invokePolicy.ts
+++ b/packages/device-link/src/invokePolicy.ts
@@ -18,6 +18,9 @@ const BACKGROUND_INVOKE_CHANNELS = new Set([
// 远程任务状态栏的定时复查(每 15 秒两次只读);后台任务面板挂载水合同用,可让位于用户操作。
'maker:session-background-activity',
'maker:session-background-tasks:list',
+ // Next-prompt suggestion after a turn completes: a model request the host answers in
+ // ~2 s. Nobody waits on it, so it must not hold a foreground slot while the user sends.
+ 'maker:predict-prompt',
// 打字时的 Agent 预热是尽力而为的提示,排在用户正在等待的请求之后。
'maker:session:prewarm',
]);
@@ -26,6 +29,41 @@ export function isBackgroundInvoke(channel: string): boolean {
return BACKGROUND_INVOKE_CHANNELS.has(channel);
}
+/**
+ * Writes the person is actively waiting on: sending, steering or stopping a turn and
+ * answering an interaction. Every relay round trip costs ~0.5 s, so one of these queued
+ * behind a dozen history/list reads is exactly the slowness users feel. Both ends grant
+ * them a small admission allowance beyond the ordinary limits (InvokeScheduler on the
+ * controller, dispatch admission on the host); nothing here changes authorization,
+ * retries or timeouts, and a listed channel still needs its allowlist entry.
+ * Queue-management edits (reorder, expand, rename) stay foreground: the UI applies them
+ * optimistically and nobody waits on their round trip.
+ */
+const INTERACTIVE_INVOKE_CHANNELS = new Set([
+ 'maker:send',
+ 'maker:abort-session',
+ 'maker:input:enqueue',
+ 'maker:input:steer',
+ 'maker:input:stop',
+ 'maker:input:resume',
+ 'maker:input:retry-last-error',
+ 'maker:input:remove',
+ 'maker:resolve-interaction',
+ 'maker:agent-task:stop',
+]);
+
+export function isInteractiveInvoke(channel: string): boolean {
+ return INTERACTIVE_INVOKE_CHANNELS.has(channel);
+}
+
+export type InvokePriority = 'interactive' | 'foreground' | 'background';
+
+/** A caller's background hint never demotes an interactive write. */
+export function resolveInvokePriority(channel: string, backgroundHint?: boolean): InvokePriority {
+ if (isInteractiveInvoke(channel)) return 'interactive';
+ return (backgroundHint ?? isBackgroundInvoke(channel)) ? 'background' : 'foreground';
+}
+
/** Control traffic must not wait behind business operations to maintain a link/lease. */
export function bypassInvokeScheduling(payload: InvokePayload): boolean {
if (payload.channel === 'device-link:subscribe' || payload.channel === 'device-link:unsubscribe') return true;
diff --git a/packages/device-link/src/invokeScheduler.ts b/packages/device-link/src/invokeScheduler.ts
index 9088dadd37..fd23387d77 100644
--- a/packages/device-link/src/invokeScheduler.ts
+++ b/packages/device-link/src/invokeScheduler.ts
@@ -1,15 +1,24 @@
+import type { InvokePriority } from "./invokePolicy.js";
import { DeviceLinkError } from "./protocol.js";
import { parseSharedTaskPeer } from "./sharedTaskPeer.js";
const MAX_ACTIVE = 12;
const MAX_BACKGROUND_ACTIVE = 4;
+/**
+ * Interactive writes (send / steer / stop / answer) may run beyond MAX_ACTIVE by this
+ * many. The ordinary limit stays exactly where it was for reads, so a task view that
+ * keeps twelve history and list reads in flight can never make a send wait for one of
+ * them to settle. The allowance is small on purpose: it only has to cover what a person
+ * can trigger by hand, and it is local admission only, not transport capacity.
+ */
+const INTERACTIVE_EXTRA_ACTIVE = 2;
const MAX_QUEUED = 128;
// Background refreshes cannot consume the last waiting positions for user actions.
const MAX_BACKGROUND_QUEUED = 96;
interface Job {
peerId: string;
- background: boolean;
+ priority: InvokePriority;
start(): void;
cancel(error: DeviceLinkError): void;
}
@@ -27,10 +36,15 @@ export class InvokeScheduler {
run<T>(
peerId: string,
- background: boolean,
+ priority: InvokePriority | boolean,
waitMs: number,
run: () => Promise<T>,
): Promise<T> {
+ // Older callers pass the background flag; keep that contract.
+ const resolved: InvokePriority = typeof priority === "boolean"
+ ? (priority ? "background" : "foreground")
+ : priority;
+ const background = resolved === "background";
// Shared-task handles share the physical host's capacity, but keep their
// scoped peer identity for cancellation and all transport bookkeeping.
const deviceId = parseSharedTaskPeer(peerId)?.deviceId ?? peerId;
@@ -54,7 +68,7 @@ export class InvokeScheduler {
const queuedAt = Date.now();
const job: Job = {
peerId,
- background,
+ priority: resolved,
cancel: (error) => {
clearTimeout(timer);
// The transport may mark its error inFlight later; queued calls were never sent.
@@ -122,16 +136,28 @@ export class InvokeScheduler {
}
}
+ /**
+ * Admission order: interactive (own allowance, always first), then foreground, then
+ * background under its own cap. A queue is drained front to back within one priority,
+ * so two sends still go out in the order they were made.
+ */
private drain(deviceId: string, state: PeerQueue): void {
- while (state.active < MAX_ACTIVE && state.jobs.length) {
- let index = state.jobs.findIndex((job) => !job.background);
- if (index < 0) {
- // Keep one background read progressing, but do not refill a slow
- // transport with four new reads every time old requests time out.
- const limit = this.isPressured(state.jobs[0].peerId) ? 1 : MAX_BACKGROUND_ACTIVE;
- if (state.background >= limit) break;
- index = 0;
+ while (state.jobs.length) {
+ let index = -1;
+ if (state.active < MAX_ACTIVE + INTERACTIVE_EXTRA_ACTIVE) {
+ index = state.jobs.findIndex((job) => job.priority === "interactive");
}
+ if (index < 0 && state.active < MAX_ACTIVE) {
+ index = state.jobs.findIndex((job) => job.priority === "foreground");
+ if (index < 0) {
+ index = state.jobs.findIndex((job) => job.priority === "background");
+ // Keep one background read progressing, but do not refill a slow
+ // transport with four new reads every time old requests time out.
+ const limit = index >= 0 && this.isPressured(state.jobs[index].peerId) ? 1 : MAX_BACKGROUND_ACTIVE;
+ if (index >= 0 && state.background >= limit) index = -1;
+ }
+ }
+ if (index < 0) break;
state.jobs.splice(index, 1)[0].start();
}
if (!state.active && !state.jobs.length) this.peers.delete(deviceId);
diff --git a/packages/maker-shared/src/__tests__/historyViewLoading.test.ts b/packages/maker-shared/src/__tests__/historyViewLoading.test.ts
index 1d5dcc86e4..edcfca0e44 100644
--- a/packages/maker-shared/src/__tests__/historyViewLoading.test.ts
+++ b/packages/maker-shared/src/__tests__/historyViewLoading.test.ts
@@ -12,6 +12,43 @@ function fixture() {
return { view, transport };
}
+describe('history read coverage', () => {
+ // Desktop's push-driven repair asks these two questions to avoid a second page read
+ // per notice; an older-page read must not count as covering a latest-page notice.
+ it('reports when the latest page was last read and whether a latest read is in flight', async () => {
+ const { view, transport } = fixture();
+ expect(view.latestReadStartedAt()).toBe(0);
+ expect(view.isReadingLatest()).toBe(false);
+ let finish!: (value: typeof page) => void;
+ transport.page.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ const before = Date.now();
+ const latest = view.refresh();
+ expect(view.isReadingLatest()).toBe(true);
+ expect(view.latestReadStartedAt()).toBeGreaterThanOrEqual(before);
+ finish(page);
+ await latest;
+ expect(view.isReadingLatest()).toBe(false);
+ const startedAt = view.latestReadStartedAt();
+ transport.page.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ const older = view.refresh(true);
+ expect(view.isReadingLatest()).toBe(false);
+ expect(view.latestReadStartedAt()).toBe(startedAt);
+ finish(page);
+ await older;
+ });
+
+ it('stamps a latest read as certified only after it was applied', async () => {
+ const { view, transport } = fixture();
+ expect(view.latestReadOkStartedAt()).toBe(0);
+ transport.page.mockRejectedValueOnce(new Error('link hiccup'));
+ await view.refresh();
+ expect(view.latestReadStartedAt()).toBeGreaterThan(0);
+ expect(view.latestReadOkStartedAt()).toBe(0);
+ await view.refresh();
+ expect(view.latestReadOkStartedAt()).toBe(view.latestReadStartedAt());
+ });
+});
+
describe('history pagination feedback', () => {
it('keeps initial and repeated background reads silent, including a queued older page', async () => {
const { view, transport } = fixture();
diff --git a/packages/maker-shared/src/historyViewController.ts b/packages/maker-shared/src/historyViewController.ts
index 23c2646317..4e5b6186cd 100644
--- a/packages/maker-shared/src/historyViewController.ts
+++ b/packages/maker-shared/src/historyViewController.ts
@@ -73,6 +73,8 @@ export class HistoryViewController<T extends HistoryMessageSource> {
private pageGeneration = 0;
private intentVersion = 0;
private refreshTimer: ReturnType<typeof setTimeout> | null = null;
+ private latestReadStartedAtMs = 0;
+ private latestReadOkStartedAtMs = 0;
constructor(
private readonly transport: HistoryViewTransport<T>,
@@ -97,6 +99,20 @@ export class HistoryViewController<T extends HistoryMessageSource> {
getSnapshot = (): HistoryViewSnapshot<T> => this.state;
/** Pagination feedback only; background validation must not disturb the reading viewport. */
isLoadingOlder = (): boolean => this.state.loading && this.pageOlder;
+ /**
+ * Wall-clock start of the most recent latest-page read (0 before the first). A caller
+ * holding the time a change notice arrived can tell whether a read already covers it,
+ * instead of forcing one more page read per notice.
+ */
+ latestReadStartedAt = (): number => this.latestReadStartedAtMs;
+ /**
+ * Start time of the most recent latest-page read that completed and was applied (0 before
+ * the first). A failed or superseded read never advances it, so "covered by a read" can
+ * be certified without trusting an error-cleared snapshot.
+ */
+ latestReadOkStartedAt = (): number => this.latestReadOkStartedAtMs;
+ /** True while a latest-page read is in flight; older-page reads do not count. */
+ isReadingLatest = (): boolean => this.pagePromise !== null && !this.pageOlder;
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
@@ -187,6 +203,8 @@ export class HistoryViewController<T extends HistoryMessageSource> {
const generation = this.generation;
const before = older ? this.state.nextCursor ?? undefined : undefined;
const readReceipt = nextHistoryCacheReceipt();
+ const readStartedAt = Date.now();
+ if (!older) this.latestReadStartedAtMs = readStartedAt;
this.publish({ loading: true, error: null });
try {
const page = await this.transport.page(before);
@@ -210,6 +228,7 @@ export class HistoryViewController<T extends HistoryMessageSource> {
this.publish({ items: stableItems, ready: true, loading: false,
...(older ? {} : { stale: false, readReceipt }),
hasMore: retained.hasMore, nextCursor: retained.nextCursor }, older ? 'older' : 'latest');
+ if (!older) this.latestReadOkStartedAtMs = readStartedAt;
for (const summary of historyWorkSummaries(items)) {
if (this.state.expanded.has(summary.key)) void this.loadDetails(summary);
}
diff --git a/packages/maker-shared/src/subagentWorkspace.ts b/packages/maker-shared/src/subagentWorkspace.ts
index 1ae56c8a81..11324cc300 100644
--- a/packages/maker-shared/src/subagentWorkspace.ts
+++ b/packages/maker-shared/src/subagentWorkspace.ts
@@ -217,6 +217,12 @@ export interface SubagentRunsListResponse {
supported: boolean;
runs: SubagentRun[];
nextCursor?: string;
+ /**
+ * The answering Host pushes `local-db:subagent-runs:changed` to controllers subscribed
+ * to the task, so a remote reader may wait for that push instead of polling. Absent on
+ * older Hosts, which keep the poll.
+ */
+ changePush?: boolean;
}
export interface SubagentRunDetailResponse {