Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(device-link): 闲置远程控制端停止全量对账并避免侧栏索引打满被控端 (#4435)

Chris Zhang6befbed70c6c
diff --git a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
index 98c07761ad..970ab8d5c4 100644
--- a/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/providerListProjection.test.ts
@@ -372,3 +372,56 @@ describe('active runtime summary projection', () => {
},
);
});
+
+describe('schedule sidebar index tunnel cap', () => {
+ it('coalesces the schedule index channel with other listing reads', () => {
+ expect(__testing.coalesceRemoteInvokeChannels.has('maker:schedule:list-sidebar-index-runs')).toBe(true);
+ expect(__testing.coalesceRemoteInvokeChannels.has('local-db:sessions:list')).toBe(true);
+ });
+
+ it('keeps the newest mapping when the snapshot exceeds the tunnel budget', () => {
+ const padding = 'x'.repeat(80_000);
+ const runs = Array.from({ length: 80 }, (_, i) => ({
+ runId: `run-${i}`,
+ scheduleId: `sched-${i}`,
+ scheduleName: padding,
+ sessionId: `session-${i}`,
+ status: 'failed',
+ firedAt: i,
+ }));
+ const result = { runs, extra: true };
+ const projected = __testing.projectInvokeResultForTunnel(
+ 'maker:schedule:list-sidebar-index-runs',
+ result,
+ ) as { runs: Array<{ runId: string }>; extra: boolean };
+ expect(projected.extra).toBe(true);
+ expect(projected.runs.length).toBeGreaterThan(0);
+ expect(projected.runs.length).toBeLessThan(runs.length);
+ expect(projected.runs.at(-1)?.runId).toBe('run-79');
+ expect(JSON.stringify(projected).length).toBeLessThanOrEqual(
+ __testing.remoteScheduleIndexMaxBytes,
+ );
+ });
+
+ it('returns the original snapshot when it already fits', () => {
+ const result = { runs: [{ runId: 'run-1', status: 'success' }] };
+ expect(__testing.projectInvokeResultForTunnel(
+ 'maker:schedule:list-sidebar-index-runs',
+ result,
+ )).toBe(result);
+ });
+
+ it('returns an empty snapshot when a single run still exceeds the tunnel budget', () => {
+ const result = {
+ runs: [{
+ runId: 'run-fat',
+ scheduleName: 'x'.repeat(__testing.remoteScheduleIndexMaxBytes),
+ status: 'failed',
+ }],
+ };
+ expect(__testing.projectInvokeResultForTunnel(
+ 'maker:schedule:list-sidebar-index-runs',
+ result,
+ )).toEqual({ runs: [] });
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 7942891da9..1071c8c373 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -84,6 +84,7 @@ import {
} from './remoteBotSessionBoundary.js';
import { getControllerPlatform } from './controllerPlatform';
import { runDeviceLinkInvokeContext } from './invoke-context';
+import { runAsBackgroundDbRpc } from '../localDb/client/rpcAdmission.js';
import { fetchLocalMediaToOss } from './mediaFetch';
import { transcribeRemoteVoiceInput } from './voiceTranscribe';
import { readTelegramRemoteStatus, setTelegramRemoteOnline } from './telegramRemoteControl';
@@ -497,6 +498,34 @@ function projectModelsForController(models: unknown): unknown {
* 模型显示 override 快照同样属于非敏感展示状态,需随目录投影给控制端。
* 其它通道原样返回。
*/
+/** 侧栏索引过胖时裁掉最旧 run,避免 4MB 传输上限导致算完发不出去再重打 DB。 */
+function capScheduleSidebarIndexForTunnel(result: unknown): unknown {
+ if (!result || typeof result !== 'object' || Array.isArray(result)) return result;
+ const record = result as { runs?: unknown };
+ if (!Array.isArray(record.runs) || record.runs.length === 0) return result;
+ const pack = (runs: unknown[]) => ({ ...record, runs });
+ const fits = (runs: unknown[]): boolean => {
+ const serialized = safeJsonStringify(pack(runs));
+ return serialized != null && encodedByteLength(serialized) <= REMOTE_SCHEDULE_INDEX_MAX_BYTES;
+ };
+ if (fits(record.runs)) return result;
+ // 存储层把未读旧 run 放前面、最新映射放最后。超限时保尾部,侧栏归属仍在。
+ let lo = 1;
+ let hi = record.runs.length;
+ let keep = 0;
+ while (lo <= hi) {
+ const mid = Math.floor((lo + hi) / 2);
+ if (fits(record.runs.slice(record.runs.length - mid))) {
+ keep = mid;
+ lo = mid + 1;
+ } else {
+ hi = mid - 1;
+ }
+ }
+ if (keep === 0) return pack([]);
+ return pack(record.runs.slice(record.runs.length - keep));
+}
+
function projectInvokeResultForTunnel(
channel: string,
result: unknown,
@@ -515,6 +544,9 @@ function projectInvokeResultForTunnel(
return { sessionId: row.sessionId, isTurnRunning: row.isTurnRunning };
});
}
+ if (channel === 'maker:schedule:list-sidebar-index-runs') {
+ return capScheduleSidebarIndexForTunnel(result);
+ }
if (channel !== 'maker:provider:list') return result;
const r = result as { providers?: unknown; modelVisibilityOverrides?: unknown };
if (!Array.isArray(r.providers)) return result;
@@ -618,7 +650,11 @@ const COALESCE_REMOTE_INVOKE_CHANNELS: ReadonlySet<string> = new Set([
'maker:get-capabilities',
'maker:provider:list',
'maker:git-safety:get',
+ // Studio/手机周期对账会连打这条;不合并就会把单线程 DB worker 打满。
+ 'maker:schedule:list-sidebar-index-runs',
]);
+/** 隧道回包必须低于 4MB 传输上限与 per-controller 4MB 准入;2MB 给 envelope 留余量。 */
+const REMOTE_SCHEDULE_INDEX_MAX_BYTES = 2 * 1024 * 1024;
/**
* Keep one slow controller from consuming the entire target-device budget.
* The global limit still protects the host, while this per-controller slice
@@ -3692,10 +3728,16 @@ export async function runInvoke(
historyView,
},
// provider:list 的首参只承载隧道能力协商,不进入本机 IPC handler。
- () => dispatchLocalInvoke(
- payload.channel,
- payload.channel === 'maker:provider:list' ? [] : args,
- ),
+ // 对账 listing 走后台读配额,不占满写入名额。
+ () => {
+ const invoke = () => dispatchLocalInvoke(
+ payload.channel,
+ payload.channel === 'maker:provider:list' ? [] : args,
+ );
+ return COALESCE_REMOTE_INVOKE_CHANNELS.has(payload.channel)
+ ? runAsBackgroundDbRpc(invoke)
+ : invoke();
+ },
);
if (hasRemoteBotSessionLookup()) await assertRemoteBotInvocationAllowed(args, payload.channel);
if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(invocationOwner)) throw new Error('[NOT_FOUND] Session does not exist');
@@ -3834,6 +3876,9 @@ export const __testing = {
optionalControllerCapabilities,
sendInvokeResultSafe,
projectInvokeResultForTunnel,
+ capScheduleSidebarIndexForTunnel,
+ remoteScheduleIndexMaxBytes: REMOTE_SCHEDULE_INDEX_MAX_BYTES,
+ coalesceRemoteInvokeChannels: COALESCE_REMOTE_INVOKE_CHANNELS,
remoteInvokeInFlightLimit: REMOTE_INVOKE_IN_FLIGHT_LIMIT,
remoteInvokeInFlightPerControllerLimit: REMOTE_INVOKE_IN_FLIGHT_PER_CONTROLLER_LIMIT,
remoteInvokeOrphanTimeoutMs: REMOTE_INVOKE_ORPHAN_TIMEOUT_MS,
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index d1884c386c..e0dd0c0af9 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -13,6 +13,7 @@ import {
type VecStatusEvent,
type WorkerMessage,
} from './DbTransport.js';
+import { isBackgroundDbRpc } from './rpcAdmission.js';
const WORKER_CODE = `
// 旧版 inline worker fallback。默认运行时走 .vite/build/dbWorker.js;
@@ -2506,6 +2507,7 @@ interface PendingRpc {
timeout: ReturnType<typeof setTimeout>;
/** 当前预算窗口的起点(挂钟)。跨睡眠重武装时会重置,见 evaluateRpcTimeout。 */
sentAtMs: number;
+ background: boolean;
}
interface QueuedRpc {
@@ -2516,6 +2518,7 @@ interface QueuedRpc {
/** RPC 总预算从进入 transport 开始计,而不是等 dispatch 后才开始。 */
budgetStartedAtMs: number;
queueTimeout?: ReturnType<typeof setTimeout>;
+ background: boolean;
}
/**
@@ -2569,12 +2572,19 @@ export interface WorkerThreadTransportOptions {
maxQueuedRpcs?: number;
/** 单个 RPC 从入队到完成的总预算;生产默认 30s,测试可缩短。 */
rpcTimeoutMs?: number;
+ /** 后台读(侧栏/对账)在途上限;写入和发消息走主配额。 */
+ maxBackgroundInFlightRpcs?: number;
+ /** 后台读排队上限;超出只拒后台读,不挡写入。 */
+ maxBackgroundQueuedRpcs?: number;
}
export class WorkerThreadTransport implements DbTransport {
private static readonly RPC_TIMEOUT_MS = 30_000;
private static readonly DEFAULT_MAX_IN_FLIGHT_RPCS = 128;
private static readonly DEFAULT_MAX_QUEUED_RPCS = 512;
+ /** 一次侧栏索引大约 4 路 rawAll;16 够几路对账并行,占不满 128。 */
+ private static readonly DEFAULT_MAX_BACKGROUND_IN_FLIGHT_RPCS = 16;
+ private static readonly DEFAULT_MAX_BACKGROUND_QUEUED_RPCS = 32;
private worker: Worker;
private nextId = 1;
@@ -2600,6 +2610,7 @@ export class WorkerThreadTransport implements DbTransport {
}
const id = this.nextId++;
const req: RpcRequest = { id, op, args };
+ const background = isBackgroundDbRpc();
return new Promise<R>((resolve, reject) => {
const queued: QueuedRpc = {
req,
@@ -2607,17 +2618,20 @@ export class WorkerThreadTransport implements DbTransport {
resolve: resolve as (value: unknown) => void,
reject,
budgetStartedAtMs: Date.now(),
+ background,
};
- if (this.pending.size < this.maxInFlightRpcs) {
+ if (this.canDispatchImmediately(queued)) {
this.dispatch(queued);
return;
}
- if (this.queued.length >= this.maxQueuedRpcs) {
+ if (!this.canEnqueue(queued)) {
reject(
createDbTransportError(
DB_TRANSPORT_NOT_SENT,
`db worker RPC queue overloaded: op="${op}" inFlight=${this.pending.size}` +
- ` queued=${this.queued.length}`,
+ ` queued=${this.queued.length}` +
+ ` backgroundInFlight=${this.backgroundPendingCount()}` +
+ ` backgroundQueued=${this.backgroundQueuedCount()}`,
),
);
return;
@@ -2683,6 +2697,52 @@ export class WorkerThreadTransport implements DbTransport {
return this.opts.rpcTimeoutMs ?? WorkerThreadTransport.RPC_TIMEOUT_MS;
}
+ private get maxBackgroundInFlightRpcs(): number {
+ return Math.min(
+ this.maxInFlightRpcs,
+ this.opts.maxBackgroundInFlightRpcs ?? WorkerThreadTransport.DEFAULT_MAX_BACKGROUND_IN_FLIGHT_RPCS,
+ );
+ }
+
+ private get maxBackgroundQueuedRpcs(): number {
+ return Math.min(
+ this.maxQueuedRpcs,
+ this.opts.maxBackgroundQueuedRpcs ?? WorkerThreadTransport.DEFAULT_MAX_BACKGROUND_QUEUED_RPCS,
+ );
+ }
+
+ private backgroundPendingCount(): number {
+ let count = 0;
+ for (const pending of this.pending.values()) {
+ if (pending.background) count += 1;
+ }
+ return count;
+ }
+
+ private backgroundQueuedCount(): number {
+ let count = 0;
+ for (const item of this.queued) {
+ if (item.background) count += 1;
+ }
+ return count;
+ }
+
+ private canDispatchImmediately(item: QueuedRpc): boolean {
+ if (this.pending.size >= this.maxInFlightRpcs) return false;
+ if (item.background && this.backgroundPendingCount() >= this.maxBackgroundInFlightRpcs) {
+ return false;
+ }
+ return true;
+ }
+
+ private canEnqueue(item: QueuedRpc): boolean {
+ if (this.queued.length >= this.maxQueuedRpcs) return false;
+ if (item.background && this.backgroundQueuedCount() >= this.maxBackgroundQueuedRpcs) {
+ return false;
+ }
+ return true;
+ }
+
private armQueuedTimeout(item: QueuedRpc): void {
const onTimeout = (): void => {
const index = this.queued.indexOf(item);
@@ -2742,6 +2802,7 @@ export class WorkerThreadTransport implements DbTransport {
reject: item.reject,
timeout,
sentAtMs: item.budgetStartedAtMs,
+ background: item.background,
});
try {
this.worker.postMessage(item.req, item.transferList as never);
@@ -2753,9 +2814,25 @@ export class WorkerThreadTransport implements DbTransport {
}
}
+ private takeNextQueued(): QueuedRpc | undefined {
+ const interactiveIndex = this.queued.findIndex((item) => !item.background);
+ if (interactiveIndex >= 0) {
+ const next = this.queued[interactiveIndex];
+ if (!this.canDispatchImmediately(next)) return undefined;
+ this.queued.splice(interactiveIndex, 1);
+ return next;
+ }
+ const backgroundIndex = this.queued.findIndex((item) => item.background);
+ if (backgroundIndex < 0) return undefined;
+ const next = this.queued[backgroundIndex];
+ if (!this.canDispatchImmediately(next)) return undefined;
+ this.queued.splice(backgroundIndex, 1);
+ return next;
+ }
+
private drainQueue(): void {
while (!this.closed && this.pending.size < this.maxInFlightRpcs) {
- const next = this.queued.shift();
+ const next = this.takeNextQueued();
if (!next) return;
this.dispatch(next);
}
diff --git a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts
index 216dfd320c..4a69af2d78 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/WorkerThreadTransport.test.ts
@@ -10,6 +10,7 @@ import {
type LogEvent,
type VecStatusEvent,
} from '../DbTransport.js';
+import { runAsBackgroundDbRpc } from '../rpcAdmission.js';
import { WorkerThreadTransport } from '../WorkerThreadTransport.js';
describe('WorkerThreadTransport', () => {
@@ -74,6 +75,28 @@ describe('WorkerThreadTransport', () => {
});
});
+ it('keeps interactive writes moving when background listing is capped', async () => {
+ const transport = new WorkerThreadTransport({
+ useInlineWorker: true,
+ maxInFlightRpcs: 4,
+ maxQueuedRpcs: 4,
+ maxBackgroundInFlightRpcs: 1,
+ maxBackgroundQueuedRpcs: 1,
+ });
+ try {
+ const backgroundBusy = runAsBackgroundDbRpc(() => transport.send('sleep', { ms: 80 }));
+ const backgroundQueued = runAsBackgroundDbRpc(() => transport.send('sleep', { ms: 80 }));
+ await expect(
+ runAsBackgroundDbRpc(() => transport.send('sleep', { ms: 80 })),
+ ).rejects.toThrow(/overloaded/);
+ await expect(transport.send('query', { sql: 'SELECT 1 AS n' })).resolves.toEqual([{ n: 1 }]);
+ await expect(backgroundBusy).resolves.toEqual({ slept: 80 });
+ await expect(backgroundQueued).resolves.toEqual({ slept: 80 });
+ } finally {
+ await transport.close();
+ }
+ });
+
it('applies bounded backpressure before posting more RPCs to the worker', async () => {
const transport = new WorkerThreadTransport({
useInlineWorker: true,
diff --git a/apps/desktop/src/main/localDb/client/rpcAdmission.ts b/apps/desktop/src/main/localDb/client/rpcAdmission.ts
new file mode 100644
index 0000000000..e9de338f31
--- /dev/null
+++ b/apps/desktop/src/main/localDb/client/rpcAdmission.ts
@@ -0,0 +1,24 @@
+/**
+ * DB worker 排队分级。
+ *
+ * 侧栏/对账这类重读和本机写会话挤同一条 SQLite worker 时,读会把 128/512 占满,
+ * 写直接 overloaded。用 AsyncLocalStorage 给「后台读」盖章:worker 限制后台占用、
+ * 出队时写入优先。默认(无标记)= 交互写入,包括本机打字和远程发消息。
+ */
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+export type DbRpcAdmissionClass = 'interactive' | 'background';
+
+const storage = new AsyncLocalStorage<DbRpcAdmissionClass>();
+
+export function runAsBackgroundDbRpc<T>(fn: () => T): T {
+ return storage.run('background', fn);
+}
+
+export function currentDbRpcAdmissionClass(): DbRpcAdmissionClass {
+ return storage.getStore() ?? 'interactive';
+}
+
+export function isBackgroundDbRpc(): boolean {
+ return storage.getStore() === 'background';
+}
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
index 986eb07d68..3edb88eac8 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
@@ -481,6 +481,101 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
}
});
+ it('caps unread terminal runs so the sidebar index stays bounded', async () => {
+ const harness = createStorageHarness();
+ try {
+ harness.db.run(sql`
+ INSERT INTO sessions (id, title, source, workspace_kind, created_at, updated_at)
+ VALUES ('sess-unread-cap', 'Unread cap', 'desktop', 'dialogue', 1, 1)
+ `);
+ await harness.storage.insert(baseSchedule({ id: 'sch-unread-cap' }));
+ for (let i = 0; i < 250; i += 1) {
+ await harness.storage.insertRun({
+ id: `unread-${i}`,
+ scheduleId: 'sch-unread-cap',
+ sessionId: 'sess-unread-cap',
+ status: 'failed',
+ firedAt: i,
+ });
+ }
+ await harness.storage.insertRun({
+ id: 'latest-read',
+ scheduleId: 'sch-unread-cap',
+ sessionId: 'sess-unread-cap',
+ status: 'success',
+ firedAt: 1000,
+ readAt: 1001,
+ });
+ const runs = await harness.storage.listSidebarIndexRuns();
+ expect(runs.some((run) => run.runId === 'latest-read')).toBe(true);
+ expect(runs.filter((run) => run.runId.startsWith('unread-'))).toHaveLength(200);
+ expect(runs).toHaveLength(201);
+ } finally {
+ harness.close();
+ }
+ });
+
+ it('reuses the sidebar index snapshot until runs change', async () => {
+ const harness = createStorageHarness();
+ try {
+ await harness.storage.insert(baseSchedule({ id: 'sch-cache' }));
+ await harness.storage.insertRun({
+ id: 'run-cache-1',
+ scheduleId: 'sch-cache',
+ status: 'success',
+ firedAt: 1,
+ readAt: 2,
+ });
+ const first = await harness.storage.listSidebarIndexRuns();
+ const second = await harness.storage.listSidebarIndexRuns();
+ expect(second).toBe(first);
+ await harness.storage.insertRun({
+ id: 'run-cache-2',
+ scheduleId: 'sch-cache',
+ status: 'failed',
+ firedAt: 3,
+ });
+ const third = await harness.storage.listSidebarIndexRuns();
+ expect(third).not.toBe(first);
+ expect(third.some((run) => run.runId === 'run-cache-2')).toBe(true);
+ } finally {
+ harness.close();
+ }
+ });
+
+ it('rebuilds sidebar index when another writer changes run status or nextFireAt', async () => {
+ const harness = createStorageHarness();
+ try {
+ await harness.storage.insert(baseSchedule({ id: 'sch-ext', nextFireAt: 9_000 }));
+ await harness.storage.insertRun({
+ id: 'run-ext',
+ scheduleId: 'sch-ext',
+ status: 'running',
+ firedAt: 1,
+ });
+ const cached = await harness.storage.listSidebarIndexRuns();
+ expect(cached.find((run) => run.runId === 'run-ext')).toMatchObject({
+ status: 'running',
+ nextFireAt: 9_000,
+ });
+ expect(await harness.storage.listSidebarIndexRuns()).toBe(cached);
+
+ harness.db.run(sql`
+ UPDATE schedule_runs SET status = 'success', finished_at = 2 WHERE id = 'run-ext'
+ `);
+ const afterFinish = await harness.storage.listSidebarIndexRuns();
+ expect(afterFinish).not.toBe(cached);
+ expect(afterFinish.find((run) => run.runId === 'run-ext')?.status).toBe('success');
+
+ harness.db.run(sql`UPDATE schedules SET next_fire_at = 12000 WHERE id = 'sch-ext'`);
+ const afterReschedule = await harness.storage.listSidebarIndexRuns();
+ expect(afterReschedule).not.toBe(afterFinish);
+ expect(afterReschedule.find((run) => run.runId === 'run-ext')?.nextFireAt).toBe(12_000);
+ } finally {
+ harness.close();
+ }
+ });
+
it('recovers warnings per automation without erasing unread history; healthy skips only recover checks', async () => {
const harness = createStorageHarness();
try {
diff --git a/apps/desktop/src/main/scheduler-host/storage.ts b/apps/desktop/src/main/scheduler-host/storage.ts
index cc8ccee52d..097d996851 100644
--- a/apps/desktop/src/main/scheduler-host/storage.ts
+++ b/apps/desktop/src/main/scheduler-host/storage.ts
@@ -15,6 +15,7 @@
*/
import { eq, desc, and, isNull, isNotNull, inArray, notInArray, or, sql } from 'drizzle-orm';
+import { runAsBackgroundDbRpc } from '../localDb/client/rpcAdmission.js';
import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
import { broadcastSessionPatched } from '../localDb/ipc/sessions.js';
@@ -206,6 +207,9 @@ const LEGACY_SESSION_RUN_ID_PREFIX = 'legacy-session:';
const unreadTerminalRunWhere = () =>
sql`${scheduleRuns.readAt} IS NULL AND ${scheduleRuns.status} IN ('success', 'failed', 'aborted', 'interrupted')`;
+/** 侧栏未读终态硬上限:红点累计用最近失败,避免随空打次数把远程回包顶过 4MB。 */
+const SIDEBAR_UNREAD_RUN_LIMIT = 200;
+
function toScheduleSource(value: string | null): Schedule['source'] | undefined {
if (value === 'user' || value === 'project' || value === 'bot') return value;
return undefined;
@@ -367,6 +371,56 @@ function publicScheduleRunWhere() {
export class DrizzleScheduleStorage implements ScheduleStorage {
constructor(private readonly getDb: () => SchedulerDrizzleDb) {}
+ private sidebarIndexGeneration = 0;
+ private sidebarIndexCache: {
+ generation: number;
+ revision: string;
+ runs: ScheduleSidebarIndexRun[];
+ } | null = null;
+
+ private bumpSidebarIndexCache(): void {
+ this.sidebarIndexGeneration += 1;
+ this.sidebarIndexCache = null;
+ }
+
+ private async readSidebarIndexRevision(): Promise<string> {
+ const db = this.getDb();
+ const [latest] = await db
+ .select({ n: sql<number>`count(*)`.mapWith(Number) })
+ .from(scheduleSessionLatestRuns);
+ const [runStats] = await db
+ .select({
+ n: sql<number>`count(*)`.mapWith(Number),
+ maxFired: sql<number>`coalesce(max(${scheduleRuns.firedAt}), 0)`.mapWith(Number),
+ maxRead: sql<number>`coalesce(max(${scheduleRuns.readAt}), 0)`.mapWith(Number),
+ maxFinished: sql<number>`coalesce(max(${scheduleRuns.finishedAt}), 0)`.mapWith(Number),
+ running: sql<number>`coalesce(sum(case when ${scheduleRuns.status} = 'running' then 1 else 0 end), 0)`.mapWith(Number),
+ })
+ .from(scheduleRuns);
+ // nextFireAt / status 会被另一 Cindy 进程改(dev/release 双开共用 DB,见 claimDueFire),
+ // 本进程 generation 不会 bump。行数和 max(firedAt/readAt) 覆盖不到这些 UPDATE。
+ const [scheduleStats] = await db
+ .select({
+ n: sql<number>`count(*)`.mapWith(Number),
+ nextFireSum: sql<number>`coalesce(sum(${schedules.nextFireAt}), 0)`.mapWith(Number),
+ nextFireN: sql<number>`coalesce(sum(case when ${schedules.nextFireAt} is not null then 1 else 0 end), 0)`.mapWith(Number),
+ activeN: sql<number>`coalesce(sum(case when ${schedules.status} = 'active' then 1 else 0 end), 0)`.mapWith(Number),
+ })
+ .from(schedules);
+ return [
+ latest?.n ?? 0,
+ runStats?.n ?? 0,
+ runStats?.maxFired ?? 0,
+ runStats?.maxRead ?? 0,
+ runStats?.maxFinished ?? 0,
+ runStats?.running ?? 0,
+ scheduleStats?.n ?? 0,
+ scheduleStats?.nextFireSum ?? 0,
+ scheduleStats?.nextFireN ?? 0,
+ scheduleStats?.activeN ?? 0,
+ ].join(':');
+ }
+
// ---------- Schedule CRUD ----------
async list(filter?: ListFilter): Promise<Schedule[]> {
@@ -399,6 +453,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
// 理论上不可能:刚插完;防御性 throw 让上层立刻看到
throw new Error(`DrizzleScheduleStorage: insert verify failed for id=${s.id}`);
}
+ this.bumpSidebarIndexCache();
return inserted;
}
@@ -411,13 +466,16 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
}
await db.update(schedules).set(setObj).where(eq(schedules.id, id));
// drizzle update 不会 throw "not found"——主动 SELECT 验证
- return this.get(id);
+ const updated = await this.get(id);
+ if (updated) this.bumpSidebarIndexCache();
+ return updated;
}
async delete(id: string): Promise<void> {
const db = this.getDb();
// schedule_runs.schedule_id ON DELETE CASCADE,相关 run 由 SQLite 自动清
await db.delete(schedules).where(eq(schedules.id, id));
+ this.bumpSidebarIndexCache();
}
/**
@@ -453,6 +511,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
throw new Error('claimDueFire: sqlite driver did not report changes count');
}
if (changes === 0) return null;
+ this.bumpSidebarIndexCache();
return this.get(id);
}
@@ -465,6 +524,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
if (!row) {
throw new Error(`DrizzleScheduleStorage: insertRun verify failed for id=${run.id}`);
}
+ this.bumpSidebarIndexCache();
return scheduleRunToCamel(row);
}
@@ -495,6 +555,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
updatedAt: new Date(patch.finishedAt).toISOString(),
});
}
+ if (row) this.bumpSidebarIndexCache();
return row ? scheduleRunToCamel(row) : null;
}
@@ -637,6 +698,11 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
* - 内部例行任务在 SQL 内排除,避免未读历史随运行次数累积到公共侧栏内存中。
*/
async listSidebarIndexRuns(): Promise<ScheduleSidebarIndexRun[]> {
+ return runAsBackgroundDbRpc(async () => {
+ const revision = await this.readSidebarIndexRevision();
+ const cached = this.sidebarIndexCache;
+ if (cached && cached.revision === revision) return cached.runs;
+ const generation = this.sidebarIndexGeneration;
const db = this.getDb();
const projection = {
runId: scheduleRuns.id,
@@ -665,7 +731,9 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
.select(projection)
.from(scheduleRuns)
.innerJoin(schedules, eq(scheduleRuns.scheduleId, schedules.id))
- .where(and(unreadTerminalRunWhere(), publicScheduleRunWhere())),
+ .where(and(unreadTerminalRunWhere(), publicScheduleRunWhere()))
+ .orderBy(desc(scheduleRuns.firedAt), desc(scheduleRuns.id))
+ .limit(SIDEBAR_UNREAD_RUN_LIMIT),
db
.select(projection)
.from(scheduleRuns)
@@ -691,9 +759,11 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
.where(publicScheduleRunWhere()),
]);
const latestRunIds = new Set(latestSessionRows.map((row) => row.runId));
- const unreadRunIds = new Set(unreadRows.map((row) => row.runId));
+ // SQL 按 fired_at 新→旧截 200 条;组装仍把其中较旧的未读放前面,红点累计后再用尾部最新映射裁决归属。
+ const unreadOldestFirst = unreadRows.slice().reverse();
+ const unreadRunIds = new Set(unreadOldestFirst.map((row) => row.runId));
const rows = [
- ...unreadRows.filter((row) => !latestRunIds.has(row.runId)),
+ ...unreadOldestFirst.filter((row) => !latestRunIds.has(row.runId)),
...latestFailedRows.filter(
(row) => !latestRunIds.has(row.runId) && !unreadRunIds.has(row.runId),
),
@@ -771,7 +841,12 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
});
}
- return [...indexedRuns, ...legacyRuns].filter((run) => run.scheduleSource !== 'bot');
+ const runs = [...indexedRuns, ...legacyRuns].filter((run) => run.scheduleSource !== 'bot');
+ if (generation === this.sidebarIndexGeneration) {
+ this.sidebarIndexCache = { generation, revision, runs };
+ }
+ return runs;
+ });
}
/**
@@ -1091,6 +1166,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
const [row] = await db.select().from(scheduleRuns).where(condition).limit(1);
if (!row) return null;
await db.delete(scheduleRuns).where(condition);
+ this.bumpSidebarIndexCache();
return scheduleRunToCamel(row);
}
@@ -1207,6 +1283,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
),
)
.run();
+ this.bumpSidebarIndexCache();
return [...new Set(staleRows.map((r) => r.scheduleId))];
}
@@ -1268,6 +1345,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
return null;
}
await db.update(scheduleRuns).set({ readAt: Date.now() }).where(eq(scheduleRuns.id, runId));
+ this.bumpSidebarIndexCache();
return row.scheduleId;
}
@@ -1294,7 +1372,9 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
.where(and(unreadTerminalRunWhere(), publicScheduleRunWhere()))
.run();
const changes = (result as unknown as { changes?: number }).changes;
- return typeof changes === 'number' ? changes : 0;
+ const updated = typeof changes === 'number' ? changes : 0;
+ if (updated > 0) this.bumpSidebarIndexCache();
+ return updated;
}
async markAllRunsRead(scheduleId: string): Promise<number> {
@@ -1306,7 +1386,9 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
.where(and(eq(scheduleRuns.scheduleId, scheduleId), unreadTerminalRunWhere()))
.run();
const changes = (result as unknown as { changes?: number }).changes;
- return typeof changes === 'number' ? changes : 0;
+ const updated = typeof changes === 'number' ? changes : 0;
+ if (updated > 0) this.bumpSidebarIndexCache();
+ return updated;
}
/**
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts
index 71c5c8a5bc..538864d7f3 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
createReconcileBackoff,
+ createRemoteReconcilePresence,
nextArchivedSessionRetryDelay,
nextSessionListTokenRetryDelay,
resolveIneligibleRemoteProjectAction,
@@ -87,7 +88,7 @@ describe('startRemoteSessionsReconciler', () => {
let visible = true;
const refresh = vi.fn(async () => 'gave-up');
const backoff = createReconcileBackoff({ baseMs: 10_000, jitter: (ms) => ms });
- const stop = startRemoteSessionsReconciler(
+ const { stop } = startRemoteSessionsReconciler(
() => new Map([['dev-a', 'Mac A']]),
refresh,
1_000,
@@ -110,6 +111,51 @@ describe('startRemoteSessionsReconciler', () => {
stop();
});
+ it('wakes immediately after idle instead of waiting for the next interval', async () => {
+ vi.useFakeTimers();
+ let visible = false;
+ const refresh = vi.fn(async () => 'ok');
+ const { stop, wake } = startRemoteSessionsReconciler(
+ () => new Map([['dev-a', 'Mac A']]),
+ refresh,
+ 10_000,
+ undefined,
+ () => visible,
+ );
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(refresh).not.toHaveBeenCalled();
+ visible = true;
+ wake();
+ expect(refresh).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(9_000);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ stop();
+ });
+
+ it('wake bypasses failure backoff so returning to the computer is not delayed', async () => {
+ vi.useFakeTimers();
+ const refresh = vi.fn(async () => 'gave-up');
+ const backoff = createReconcileBackoff({
+ baseMs: 10_000,
+ maxMs: 120_000,
+ jitter: (ms) => ms,
+ now: () => Date.now(),
+ });
+ const { stop, wake } = startRemoteSessionsReconciler(
+ () => new Map([['dev-a', 'Mac A']]),
+ refresh,
+ 1_000,
+ backoff,
+ );
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(refresh).toHaveBeenCalledTimes(1);
+ wake();
+ expect(refresh).toHaveBeenCalledTimes(2);
+ stop();
+ });
+
it('pauses hidden window polling without duplicating pending requests on resume', async () => {
vi.useFakeTimers();
let visible = false;
@@ -120,7 +166,7 @@ describe('startRemoteSessionsReconciler', () => {
finish = resolve;
}),
);
- const stop = startRemoteSessionsReconciler(
+ const { stop } = startRemoteSessionsReconciler(
() => new Map([['dev-a', 'Mac A']]),
refresh,
1_000,
@@ -153,7 +199,7 @@ describe('startRemoteSessionsReconciler', () => {
['dev-b', 'Mac B'],
]);
const refresh = vi.fn(async () => 'ok');
- const stop = startRemoteSessionsReconciler(() => eligible, refresh, 1_000);
+ const { stop } = startRemoteSessionsReconciler(() => eligible, refresh, 1_000);
await vi.advanceTimersByTimeAsync(1_000);
expect(refresh.mock.calls).toEqual([
@@ -185,7 +231,7 @@ describe('startRemoteSessionsReconciler', () => {
jitter: (delay) => delay,
now: () => Date.now(),
});
- const stop = startRemoteSessionsReconciler(() => eligible, refresh, 1_000, backoff);
+ const { stop } = startRemoteSessionsReconciler(() => eligible, refresh, 1_000, backoff);
await vi.advanceTimersByTimeAsync(1_000);
await vi.advanceTimersByTimeAsync(1_000);
@@ -214,7 +260,7 @@ describe('startRemoteSessionsReconciler', () => {
jitter: (d) => d,
now: () => Date.now(),
});
- const stop = startRemoteSessionsReconciler(() => eligible, refresh, 1_000, backoff);
+ const { stop } = startRemoteSessionsReconciler(() => eligible, refresh, 1_000, backoff);
const badCalls = () => refresh.mock.calls.filter(([id]) => id === 'dev-bad').length;
const goodCalls = () => refresh.mock.calls.filter(([id]) => id === 'dev-good').length;
@@ -264,7 +310,7 @@ describe('startRemoteSessionsReconciler', () => {
if (outcome === 'failure') failures.push(deviceId);
origReport(deviceId, outcome);
};
- const stop = startRemoteSessionsReconciler(() => eligible, refresh, 1_000, backoff);
+ const { stop } = startRemoteSessionsReconciler(() => eligible, refresh, 1_000, backoff);
// 三个 tick 过去,刷新仍在途:不再重复发起,也没有任何记账
await vi.advanceTimersByTimeAsync(3_000);
@@ -363,3 +409,21 @@ describe('resolveIneligibleRemoteProjectAction', () => {
).toBe('remove');
});
});
+
+describe('createRemoteReconcilePresence', () => {
+ it('pauses polling after idle while keeping a visible window reconnectable', () => {
+ let now = 1_000;
+ const gate = createRemoteReconcilePresence({ idleMs: 5_000, now: () => now });
+ expect(gate.isActive()).toBe(true);
+ now = 6_000;
+ expect(gate.isActive()).toBe(false);
+ expect(gate.noteActivity()).toBe(true);
+ expect(gate.isActive()).toBe(true);
+ expect(gate.noteActivity()).toBe(false);
+ expect(gate.setVisible(false)).toBe(false);
+ expect(gate.isActive()).toBe(false);
+ now = 20_000;
+ expect(gate.setVisible(true)).toBe(true);
+ expect(gate.isActive()).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
index 08f899f515..7c264ab20f 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
@@ -131,6 +131,44 @@ const RECONCILE_INTERVAL_MS = 10_000;
/** 连续失败退避封顶:失败设备最低仍保持约 2 分钟一次的对账,恢复靠 push / 熔断探测先行。 */
const RECONCILE_BACKOFF_MAX_MS = 120_000;
+/** 主窗口无人输入超过此时长则停周期对账;连接与 push 进度仍在。 */
+export const REMOTE_RECONCILE_USER_IDLE_MS = 5 * 60_000;
+
+/**
+ * 主窗口周期对账闸:页面不可见或用户离开电脑后停拉全量列表。
+ * 独立侧栏仍走 windowVisible(#4205),不要把这套 idle 叠上去。
+ */
+export function createRemoteReconcilePresence(opts?: {
+ idleMs?: number;
+ now?: () => number;
+}): {
+ isActive(): boolean;
+ /** @returns 是否从闲置变为在用,调用方应立刻对账一次。 */
+ setVisible(visible: boolean): boolean;
+ /** @returns 是否从闲置变为在用,调用方应立刻对账一次。 */
+ noteActivity(): boolean;
+} {
+ const idleMs = opts?.idleMs ?? REMOTE_RECONCILE_USER_IDLE_MS;
+ const now = opts?.now ?? Date.now;
+ let visible = true;
+ let lastActivityAt = now();
+ const isActive = () => visible && now() - lastActivityAt < idleMs;
+ return {
+ isActive,
+ setVisible(next) {
+ const wasActive = isActive();
+ visible = next;
+ if (next) lastActivityAt = now();
+ return !wasActive && isActive();
+ },
+ noteActivity() {
+ const wasActive = isActive();
+ lastActivityAt = now();
+ return !wasActive && isActive();
+ },
+ };
+}
+
type RemoteSessionsRefresh = (deviceId: string, name?: string) => Promise<unknown>;
/**
@@ -197,18 +235,19 @@ export function startRemoteSessionsReconciler(
intervalMs = RECONCILE_INTERVAL_MS,
backoff: ReconcileBackoff = createReconcileBackoff({ baseMs: intervalMs }),
isActive: () => boolean = () => true,
-): () => void {
+): { stop: () => void; wake: () => void } {
// 单次刷新可能横跨多个 tick(弱网下超时链 >10s);weak coalescing 会让后续 tick 拿到
// 同一个在途 Promise,若每个 tick 都挂 then,一次 gave-up 会被重复记账、退避直接跳档
// (review P2)。per-device 在途标记保证一次合并请求只记一次。
const inFlight = new Set<string>();
- const timer = setInterval(() => {
+ const runPass = (opts?: { ignoreBackoff?: boolean }) => {
// Hidden auxiliary windows retain their push mirror and failure backoff, but do no polling.
if (!isActive()) return;
const seen = new Set<string>();
for (const [deviceId, name] of getEligibleDevices()) {
seen.add(deviceId);
- if (inFlight.has(deviceId) || !backoff.shouldAttempt(deviceId)) continue;
+ if (inFlight.has(deviceId)) continue;
+ if (!opts?.ignoreBackoff && !backoff.shouldAttempt(deviceId)) continue;
inFlight.add(deviceId);
void refresh(deviceId, name)
.then((result) => {
@@ -226,10 +265,17 @@ export function startRemoteSessionsReconciler(
});
}
backoff.retainOnly(seen);
- }, intervalMs);
- return () => {
- clearInterval(timer);
- inFlight.clear();
+ };
+ const timer = setInterval(runPass, intervalMs);
+ return {
+ stop() {
+ clearInterval(timer);
+ inFlight.clear();
+ },
+ // 从闲置回到在用:立刻对账,不等下一拍 10 秒,也不吃失败退避。闲着不加 30 分钟兜底。
+ wake() {
+ runPass({ ignoreBackoff: true });
+ },
};
}
@@ -256,6 +302,29 @@ export function useDeviceLinkRemoteProjects(periodicReconcileActive = true, wind
const { isAuthenticated, deviceId: selfDeviceId, dataOwnerId } = useAuth();
const periodicReconcileActiveRef = useRef(periodicReconcileActive);
periodicReconcileActiveRef.current = periodicReconcileActive;
+ const mainPresenceRef = useRef(
+ windowRole === 'main' ? createRemoteReconcilePresence() : null,
+ );
+ const wakeRemoteReconcileRef = useRef<() => void>(() => undefined);
+ useEffect(() => {
+ const gate = mainPresenceRef.current;
+ if (windowRole !== 'main' || !gate) return undefined;
+ const syncVisible = () => {
+ if (gate.setVisible(document.visibilityState === 'visible')) wakeRemoteReconcileRef.current();
+ };
+ const note = () => {
+ if (gate.noteActivity()) wakeRemoteReconcileRef.current();
+ };
+ syncVisible();
+ document.addEventListener('visibilitychange', syncVisible);
+ window.addEventListener('pointerdown', note);
+ window.addEventListener('keydown', note);
+ return () => {
+ document.removeEventListener('visibilitychange', syncVisible);
+ window.removeEventListener('pointerdown', note);
+ window.removeEventListener('keydown', note);
+ };
+ }, [windowRole]);
// 账号边界真正由 dataOwnerId 界定:登出 / 切账号都必然改变它。**不能只靠 !isAuthenticated** ——
// 运行时替换刷新路径可以在不经过 signed-out 的情况下直接把新 owner 发布出来,那时本 effect
@@ -597,13 +666,14 @@ export function useDeviceLinkRemoteProjects(periodicReconcileActive = true, wind
}, RESEED_DEBOUNCE_MS),
);
});
- const stopPeriodicReconcile = startRemoteSessionsReconciler(
+ const periodicReconcile = startRemoteSessionsReconciler(
() => (linkOnline ? eligible : []),
async (deviceId, name) => {
log.debug(`sessions refresh trigger=periodic window=${windowRole} peer=${deviceId.slice(0, 8)} visible=${periodicReconcileActiveRef.current}`);
// sessions:list 是 200 条有界窗口;refresh 层会保留窗口外 active 行,并有界补查
// 缺席缓存 id 的终态,不能直接把响应缺席解释成删除。
const result = await refreshRemoteDeviceSessions(deviceId, name, {
+ scope: 'both',
snapshotMode: 'merge',
coalescingMode: 'weak',
});
@@ -613,8 +683,9 @@ export function useDeviceLinkRemoteProjects(periodicReconcileActive = true, wind
},
RECONCILE_INTERVAL_MS,
undefined,
- () => periodicReconcileActiveRef.current,
+ () => periodicReconcileActiveRef.current && (mainPresenceRef.current?.isActive() ?? true),
);
+ wakeRemoteReconcileRef.current = periodicReconcile.wake;
// 目标设备「无响应」熔断翻转(main 权威):镜像给 UI;恢复时重跑 subscribe+bootstrap
// ——熔断 open 期间的订阅 / 首拉都被快速失败挡掉了,恢复必须主动补,不能等用户手点。
@@ -671,6 +742,10 @@ export function useDeviceLinkRemoteProjects(periodicReconcileActive = true, wind
if (disposed || !eligible.has(push.deviceId)) return;
if (!isDeviceLinkRemotePushCurrent(push, localOwnerStamp)) return;
if (push.channel === 'maker:schedule:event') {
+ // 推送照收;闲着不跟事件去拉整份自动化索引。人回来 wake/10s 用 scope both 补上。
+ const watching =
+ periodicReconcileActiveRef.current && (mainPresenceRef.current?.isActive() ?? true);
+ if (!watching) return;
void refreshRemoteDeviceSessions(push.deviceId, eligible.get(push.deviceId), { scope: 'schedule' }).then((result) => {
if (result === 'revoked' && !disposed) handleRevoked(push.deviceId);
});
@@ -768,7 +843,8 @@ export function useDeviceLinkRemoteProjects(periodicReconcileActive = true, wind
disposed = true;
setRemoteReseedImpl(null);
setRemoteSessionBootstrapRetryImpl(null);
- stopPeriodicReconcile();
+ wakeRemoteReconcileRef.current = () => undefined;
+ periodicReconcile.stop();
for (const t of reseedTimers.values()) clearTimeout(t);
reseedTimers.clear();
clearAllArchivedSessionRetries();