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: 降低空闲与远程场景的 CPU 开销并精简高频日志

Dash318ff075193e
diff --git a/apps/desktop/native/menubar/macos-menubar-helper.swift b/apps/desktop/native/menubar/macos-menubar-helper.swift
index 00124ff543..a9d9eac0ce 100644
--- a/apps/desktop/native/menubar/macos-menubar-helper.swift
+++ b/apps/desktop/native/menubar/macos-menubar-helper.swift
@@ -533,6 +533,10 @@ final class MenubarStore: ObservableObject {
/// Set when the panel opens on a short screen (13–14" laptops at default scaling): tubes,
/// rings and the task list tighten so the main page stays well clear of the Dock.
@Published var short = false
+ /// True from `open` until the closing fade has ordered the panel out. While false the pages
+ /// are not rendered, so their clocks and repeating animations stop instead of running in a
+ /// hidden window.
+ @Published var panelVisible = false
var strings: [String: String] { view?.strings ?? [:] }
@@ -825,6 +829,7 @@ final class StatusController: NSObject, NSWindowDelegate {
openRetries = 0
isOpen = true
closing = false
+ store.panelVisible = true
let panel = ensurePanel()
let screen = statusAnchor()?.screen ?? NSScreen.main ?? NSScreen.screens.first
let short = forceShort || (screen.map { $0.visibleFrame.height < Self.shortScreenHeight } ?? false)
@@ -871,6 +876,7 @@ final class StatusController: NSObject, NSWindowDelegate {
guard let self, self.closing else { return }
panel.orderOut(nil)
self.closing = false
+ self.store.panelVisible = false
self.store.page = .main
self.store.draftOrder = nil
}
@@ -1078,7 +1084,9 @@ struct PanelRoot: View {
var body: some View {
ZStack(alignment: .topTrailing) {
- if let view = store.view {
+ if !store.panelVisible {
+ // Ordered out: render nothing, so no clock or repeating animation keeps running.
+ } else if let view = store.view {
pages(view)
} else {
ProgressView().controlSize(.small).frame(maxWidth: .infinity, maxHeight: .infinity)
diff --git a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts
index c3541786f9..7d1aa19b5f 100644
--- a/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts
+++ b/apps/desktop/src/main/__tests__/sharedGlobalSkills.test.ts
@@ -13,6 +13,7 @@ import {
prepareSharedGlobalSkillLinks,
prepareSharedProjectSkillLinks,
projectWorkingDirFromSkillPath,
+ sharedGlobalSkillLinksFingerprint,
sharedGlobalSkillsPaths,
sharedProjectSkillsPaths,
} from '../maker-host/shared-global-skills';
@@ -149,6 +150,8 @@ describe('prepareSharedGlobalSkillLinks', () => {
expect(result.warnings).toEqual([
'cross-agent global skill sync is disabled; set crossAgentSyncEnabled to opt in',
]);
+ // Stable opt-out state: callers cache past it instead of retrying every launch.
+ expect(result.persistentWarnings).toEqual(result.warnings);
// 未 opt-in 时,不把 Claude 的用户技能拉进 ~/.agents/skills。
await expect(fs.lstat(path.join(paths.sharedSkillsDir, 'claude-only'))).rejects.toMatchObject({
code: 'ENOENT',
@@ -363,6 +366,8 @@ describe('prepareSharedGlobalSkillLinks', () => {
const result = await prepareSharedGlobalSkillLinks({ homeDir, isCrossAgentSyncEnabled: () => true });
expect(result.warnings.some((warning) => warning.includes('duplicate'))).toBe(true);
+ // A user-owned path we never overwrite is persistent, not a retryable failure.
+ expect(result.persistentWarnings).toEqual(result.warnings);
expect(await sameRealPath(path.join(paths.sharedSkillsDir, 'duplicate'), sharedSkill)).toBe(true);
expect(await sameRealPath(path.join(paths.claudeSkillsDir, 'duplicate'), claudeSkill)).toBe(true);
expect(await sameRealPath(path.join(paths.sharedSkillsDir, 'duplicate'), path.join(paths.claudeSkillsDir, 'duplicate'))).toBe(false);
@@ -385,6 +390,24 @@ describe('prepareSharedGlobalSkillLinks', () => {
expect(await sameRealPath(claudeLink, sharedSkill)).toBe(false);
});
+ // Cache-key contract for the 30s completion cache in auth-adapters: without it a cached
+ // run would hide a crossAgentSyncEnabled toggle or a newly added global skill.
+ it('changes the preparation fingerprint on a sync toggle or a root listing change only', async () => {
+ const root = await makeTmpDir();
+ const homeDir = path.join(root, 'home');
+ const paths = sharedGlobalSkillsPaths(homeDir);
+ await writeSkill(paths.claudeSkillsDir, 'existing');
+ const fingerprint = (enabled: boolean) =>
+ sharedGlobalSkillLinksFingerprint({ homeDir, isCrossAgentSyncEnabled: () => enabled });
+
+ const before = await fingerprint(false);
+ expect(await fingerprint(false)).toBe(before);
+ expect(await fingerprint(true)).not.toBe(before);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ await writeSkill(paths.claudeSkillsDir, 'added');
+ expect(await fingerprint(false)).not.toBe(before);
+ });
+
it('cleans up broken managed links after the source skill is removed', async () => {
const root = await makeTmpDir();
const homeDir = path.join(root, 'home');
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
index 781b11a8d5..f98b7a5932 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
@@ -1019,6 +1019,45 @@ describe('remote companion Session visibility at the device-link boundary', () =
expect(client.sendPush.mock.calls.every((call) => call[2].sessionId !== 's1')).toBe(true);
});
+ // 测试价值:forwardPush 扇出到多台控制端时,同一轮只读一次授权(实测 3 台 peer 下每条 push
+ // 每台各读一次 sessions,rawAll 堆积);同时守住「读取发出后到达的 push 必须重新读库」,
+ // 轮内合并不能变成缓存,隐藏之后的 push 不得沿用旧结论。unit,进程内 fake。
+ it('shares one authorization read per fan-out pass and never reuses it for later pushes', async () => {
+ let hidden = false;
+ let release!: () => void;
+ let gate: Promise<void> = Promise.resolve();
+ const batch = vi.fn(async (ids: readonly string[]) => {
+ const snapshot = hidden;
+ await gate;
+ return new Map(ids.map((id) => [id, snapshot ? 'hidden' as const : 'visible' as const]));
+ });
+ setRemoteBotSessionLookup(async () => { throw new Error('single lookup must not run'); }, batch);
+ const client = mkClient();
+ __testing.setActiveClient(client as never);
+ const peers = ['ctrl-1', 'ctrl-2', 'ctrl-3'];
+ for (const peer of peers) subscriptions.subscribe(peer, ['session:s1']);
+ __testing.forwardPush('maker:event', { sessionId: 's1', seq: 0 });
+ __testing.forwardPush('maker:event', { sessionId: 's1', seq: 1 });
+ await vi.waitFor(() => expect(client.sendPush).toHaveBeenCalledTimes(6));
+ expect(batch).toHaveBeenCalledTimes(1);
+ expect(batch).toHaveBeenCalledWith(['s1'], 'session');
+ for (const peer of peers) {
+ expect(client.sendPush.mock.calls.filter(([dst]) => dst === peer).map((call) => call[2].seq)).toEqual([0, 1]);
+ }
+
+ // A read already issued is not joined: the push after the hide reads again.
+ gate = new Promise<void>((resolve) => { release = resolve; });
+ __testing.forwardPush('maker:event', { sessionId: 's1', seq: 2 });
+ await vi.waitFor(() => expect(batch).toHaveBeenCalledTimes(2));
+ hidden = true;
+ __testing.forwardPush('maker:event', { sessionId: 's1', seq: 3 });
+ await vi.waitFor(() => expect(batch).toHaveBeenCalledTimes(3));
+ release();
+ await vi.waitFor(() => expect(client.sendPush).toHaveBeenCalledTimes(9));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(client.sendPush.mock.calls.map((call) => call[2].seq).filter((seq) => seq >= 2)).toEqual([2, 2, 2]);
+ });
+
it('revalidates cached replies without repeating the local handler', async () => {
let hidden = false;
setRemoteBotSessionLookup(async () => hidden ? 'hidden' : 'visible');
diff --git a/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.ts b/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.ts
index 1cdc400c83..d2689e50cb 100644
--- a/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.ts
@@ -64,9 +64,10 @@ describe('device-link IPC diagnostics', () => {
'transport summary',
expect.objectContaining({ code: 'BACKPRESSURE', completed: 1000, elapsedMs: 30_000 }),
);
+ // The success baseline accompanies failures at INFO in one combined line.
expect(h.emit).toHaveBeenCalledWith(
- 'transport summary',
- expect.objectContaining({ code: 'OK', completed: 1 }),
+ 'transport summary ok',
+ expect.objectContaining({ buckets: 1, completed: 1, channels: { [CHANNEL]: 1 } }),
);
expect(JSON.stringify(h.emit.mock.calls)).not.toContain('private');
expect(vi.getTimerCount()).toBe(0);
@@ -76,6 +77,23 @@ describe('device-link IPC diagnostics', () => {
h.diagnostics.flush();
});
+ // Log-noise regression: 3 healthy peers x several channels wrote ~6 identical-timestamp
+ // INFO lines every 30s. A healthy interval must collapse to one DEBUG line.
+ it('folds a healthy interval into one debug baseline line', async () => {
+ const h = harness();
+ for (const peer of ['peer-a', 'peer-b', 'peer-c']) {
+ await h.observed.invoke(peer, CHANNEL, []);
+ await h.observed.invoke(peer, 'maker:list-active', []);
+ await h.observed.subscribe(peer, ['private-topic']);
+ }
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(h.emit).toHaveBeenCalledExactlyOnceWith(
+ 'transport summary ok',
+ { buckets: 9, completed: 9, channels: { [CHANNEL]: 3, 'maker:list-active': 3, subscribe: 3 }, elapsedMs: 30_000 },
+ 'debug',
+ );
+ });
+
it('distinguishes raw causes, peers, windows and subscription operations', async () => {
const h = harness();
for (const code of ['NOT_CONNECTED', 'LINK_NOT_OPEN', 'PEER_RESET', 'BACKPRESSURE'] as const) {
@@ -95,8 +113,12 @@ describe('device-link IPC diagnostics', () => {
const rows = h.emit.mock.calls
.filter(([event]) => event === 'transport summary')
.map(([, row]) => row);
- expect(rows).toHaveLength(8);
- expect(new Set(rows.map((row) => row.peer)).size).toBe(2);
+ expect(rows).toHaveLength(7);
+ expect(new Set(rows.map((row) => row.peer)).size).toBe(1);
+ expect(h.emit).toHaveBeenCalledWith(
+ 'transport summary ok',
+ expect.objectContaining({ buckets: 1, completed: 1, channels: { unsubscribe: 1 } }),
+ );
expect(rows.filter((row) => row.operation === 'subscribe').map((row) => row.windowId)).toEqual([
10, 20,
]);
diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts
index 1752f29400..21d25ae388 100644
--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts
@@ -214,10 +214,10 @@ it.each([1_000, 30_000])('flushes completed calls on quit after %i ms without du
const quit = h.quitHandlers.get('device-link-ipc-diagnostics');
expect(quit?.phase).toBe('sync');
quit!.fn();
- const summaries = h.diagnosticsInfo.mock.calls.filter(([event]) => event === 'transport summary');
- expect(summaries).toHaveLength(2);
- expect(summaries.map(([, fields]) => [fields.code, fields.completed])).toEqual([
- ['OK', 1], ['NOT_CONNECTED', 1],
+ const summaries = h.diagnosticsInfo.mock.calls.filter(([event]) => event.startsWith('transport summary'));
+ // Failing buckets stay per bucket; successes fold into one baseline line.
+ expect(summaries.map(([event, fields]) => [event, fields.code, fields.completed])).toEqual([
+ ['transport summary', 'NOT_CONNECTED', 1], ['transport summary ok', undefined, 1],
]);
const count = h.diagnosticsInfo.mock.calls.length;
quit!.fn();
diff --git a/apps/desktop/src/main/device-link/__tests__/transferCodec.test.ts b/apps/desktop/src/main/device-link/__tests__/transferCodec.test.ts
index 04b3f0b92a..1184a435a6 100644
--- a/apps/desktop/src/main/device-link/__tests__/transferCodec.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/transferCodec.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { encodeInvokeResultTransfer, InvokeResultCache } from '@cindy/device-link';
-import { desktopTransferCodec } from '../transferCodec';
+import { createCompressionStatsLog, desktopTransferCodec } from '../transferCodec';
import { decodeGzipBase64TextBounded } from '../../../../../mobile/src/utils/gzipBase64';
describe('desktop device-link transfer codec', () => {
@@ -33,4 +33,24 @@ describe('desktop device-link transfer codec', () => {
expect(desktopTransferCodec.gunzipBase64!(cjk, 1_000)).toHaveLength(1_000);
expect(() => desktopTransferCodec.gunzipBase64!(cjk, 999)).toThrow();
});
+
+ // Log-noise regression: one DEBUG line per compressed reply (~16k/day) becomes one
+ // windowed summary; a slow synchronous compression is still reported on its own.
+ it('aggregates compression stats per window and reports slow calls immediately', () => {
+ const emit = vi.fn();
+ let now = 0;
+ const record = createCompressionStatsLog(emit, () => now, 1_000);
+ const stats = { originalBytes: 10_000, gzipBytes: 1_000, wireBytes: 1_336, compressionMs: 2 };
+ for (let i = 0; i < 100; i++) record(stats);
+ expect(emit).not.toHaveBeenCalled();
+ record({ ...stats, compressionMs: 150 });
+ expect(emit).toHaveBeenCalledExactlyOnceWith('gzip slow candidate', { ...stats, compressionMs: 150 });
+ now = 1_000;
+ record(stats);
+ expect(emit).toHaveBeenLastCalledWith('gzip summary', {
+ count: 101, originalBytes: 1_010_000, gzipBytes: 101_000, wireBytes: 134_936,
+ compressionMs: 350, maxCompressionMs: 150, elapsedMs: 1_000,
+ });
+ expect(emit).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 2dceda1f04..718caf5ca0 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -211,13 +211,15 @@ const textEncoder = new TextEncoder();
// per-peer queue bounded, with room for that body plus its message envelope.
const offlinePushQueue = createOfflinePushQueue({ maxBytes: 2 * 1024 * 1024 });
-// Serialize the async DB check at the final wire boundary, retaining per-peer
-// order even when replies arrive out of order. Bounds match best-effort push:
-// dropped frames recover through the existing Session snapshot mechanism.
+// Start the async DB check at the final wire boundary and deliver in per-peer
+// order even when replies arrive out of order. Checks issued in the same pass
+// (all peers of one fan-out, every item of one flush) share one batched read
+// that is issued after all of them arrived; see projectRemoteBotPush. Bounds
+// match best-effort push: dropped frames recover through the Session snapshot.
const botPushChecks = new Map<string, { tail: Promise<void>; bytes: number; count: number }>();
function sendBotCheckedPush(
dst: string, channel: string, payload: unknown, send: (payload: unknown) => void,
- failed: (error: unknown) => void,
+ failed: (error: unknown) => void, payloadBytes?: number,
): void | Promise<void> {
const sharedTaskFence = captureSharedTaskPush(dst, channel, payload);
if (!sharedTaskFence) return;
@@ -225,7 +227,7 @@ function sendBotCheckedPush(
send = (projected) => { if (sharedTaskFence()) deliver(projected); };
if (!hasRemoteBotSessionLookup()) { send(payload); return; }
let size: number;
- try { size = byteLength(JSON.stringify(payload)); } catch (error) { failed(error); return; }
+ try { size = payloadBytes ?? measurePushPayloadBytes(payload); } catch (error) { failed(error); return; }
const queue = botPushChecks.get(dst) ?? { tail: Promise.resolve(), bytes: 0, count: 0 };
if (queue.count >= 64 || queue.bytes + size > 8 * 1024 * 1024) {
failed(new DeviceLinkError('BACKPRESSURE', 'remote push authorization queue full'));
@@ -235,8 +237,11 @@ function sendBotCheckedPush(
const linkEpoch = remoteInvokeLinkEpoch.get(dst) ?? 0;
const owner = broadcastTap.captureDataOwnerBroadcastScope();
queue.count += 1; queue.bytes += size;
+ const authorized = projectRemoteBotPush(payload, channel);
+ // Settled below in per-peer order; do not surface as unhandled meanwhile.
+ authorized.catch(() => undefined);
queue.tail = queue.tail.then(async () => {
- const projected = await projectRemoteBotPush(payload, channel);
+ const projected = await authorized;
if (projected !== null && activeClient === client && (remoteInvokeLinkEpoch.get(dst) ?? 0) === linkEpoch && !isControllerRevoked(dst) && broadcastTap.isDataOwnerBroadcastScopeCurrent(owner)) send(projected);
}).catch(failed).finally(() => {
queue.count -= 1; queue.bytes -= size;
@@ -246,6 +251,23 @@ function sendBotCheckedPush(
return queue.tail;
}
+/**
+ * Push payloads are shared by reference across every peer of one fan-out and
+ * are not mutated after broadcast (batching already holds them by reference).
+ * Remember their UTF-8 JSON size so each peer and each staging step does not
+ * stringify the same event again.
+ */
+const pushPayloadBytes = new WeakMap<object, number>();
+function measurePushPayloadBytes(payload: unknown): number {
+ const key = payload !== null && typeof payload === 'object' ? payload : null;
+ const known = key ? pushPayloadBytes.get(key) : undefined;
+ if (known !== undefined) return known;
+ const json = JSON.stringify(payload);
+ const bytes = json ? byteLength(json) : 0;
+ if (key) pushPayloadBytes.set(key, bytes);
+ return bytes;
+}
+
/** 只排队可由 session snapshot 对账、且不携带权限终态的会话域事件。 */
const OFFLINE_QUEUEABLE_PUSH_CHANNELS: ReadonlySet<string> = new Set([
'local-db:messages:created',
@@ -1537,11 +1559,10 @@ function readPushSessionId(payload: unknown): string | null {
function estimateMakerEventBytes(payload: unknown): number {
try {
- const json = JSON.stringify(payload);
// 必须按 UTF-8 计:String.length 是 UTF-16 码元数,中文/emoji 会显著低估,
// 字节阈值随之形同虚设(单批可能被撑到需要分片或 PAYLOAD_TOO_LARGE)。
// byteLength 与可靠传输层计算分片大小用的是同一个函数,口径一致。
- return json ? byteLength(json) : 0;
+ return measurePushPayloadBytes(payload);
} catch {
// 不可序列化的 payload 交给 sendPush 报错处理;这里只保证估算不抛。
return 0;
@@ -1688,7 +1709,9 @@ function flushMakerEventBatchSession(
}, () => {
outcome.droppedEvents += slice.length;
stageSessionSync(dst, sessionId, historyRequired);
- });
+ // Queue accounting only: the events were already measured while staging,
+ // so do not stringify the whole batch once more per peer.
+ }, slice.reduce<number>((bytes, event) => bytes + estimateMakerEventBytes(event) + 1, byteLength(sessionId) + 32));
} catch (err) {
stageSessionSync(dst, sessionId, historyRequired);
// 发不出去就丢这一片(不降级、不重试、不滞留):理由与四轮 review 的推导见
diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.ts
index 64aa324951..1bb4deb77e 100644
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@ -1421,8 +1421,8 @@ export async function retryUnsubscribeAfterWindowGone(
export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()): void {
const diagnosticsLog = createLogger('device-link:ipc-diagnostics');
- const diagnostics = createDeviceLinkIpcDiagnostics((event, fields) =>
- diagnosticsLog.info(event, fields),
+ const diagnostics = createDeviceLinkIpcDiagnostics((event, fields, level) =>
+ level === 'debug' ? diagnosticsLog.debug(event, fields) : diagnosticsLog.info(event, fields),
);
// Submit the final partial interval at shutdown start, giving the async log
// writer the subsequent cleanup phases to drain before app.exit().
diff --git a/apps/desktop/src/main/device-link/ipcDiagnostics.ts b/apps/desktop/src/main/device-link/ipcDiagnostics.ts
index 05a1600c6a..6154e21ad0 100644
--- a/apps/desktop/src/main/device-link/ipcDiagnostics.ts
+++ b/apps/desktop/src/main/device-link/ipcDiagnostics.ts
@@ -51,13 +51,21 @@ interface Bucket {
completed: number;
}
+export type DeviceLinkIpcDiagnosticsLevel = 'info' | 'debug';
+
+/** Successful channels listed in the combined line; the rest are counted only. */
+const MAX_OK_CHANNELS = 8;
+
/** Local diagnostics for completed transport calls originating at renderer IPC.
* Counts before IPC error remapping; not wire sends or all main background work.
- * First failure per bucket is immediate; 30s summaries include that first event
- * and successes for a baseline. Bounded cardinality and no payloads/peer IDs.
+ * First failure per bucket is immediate; each 30s summary lists every failing
+ * bucket (including that first event) and folds all successful buckets into one
+ * baseline line. The baseline stays at debug unless the interval has failures,
+ * so a healthy multi-peer link no longer writes one INFO line per bucket.
+ * Bounded cardinality and no payloads/peer IDs.
*/
export function createDeviceLinkIpcDiagnostics(
- emit: (event: string, fields: Record<string, unknown>) => void,
+ emit: (event: string, fields: Record<string, unknown>, level?: DeviceLinkIpcDiagnosticsLevel) => void,
) {
const salt = randomBytes(32);
const buckets = new Map<string, Bucket>();
@@ -67,9 +75,13 @@ export function createDeviceLinkIpcDiagnostics(
let startedAt = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
- function safeEmit(event: string, fields: Record<string, unknown>): void {
+ function safeEmit(
+ event: string, fields: Record<string, unknown>, level: DeviceLinkIpcDiagnosticsLevel = 'info',
+ ): void {
try {
- emit(event, fields);
+ // INFO stays the two-argument default; only demoted lines carry a level.
+ if (level === 'debug') emit(event, fields, 'debug');
+ else emit(event, fields);
} catch {
/* Diagnostics cannot change request behavior. */
}
@@ -79,9 +91,33 @@ export function createDeviceLinkIpcDiagnostics(
if (timer) clearTimeout(timer);
timer = undefined;
const elapsedMs = Date.now() - startedAt;
- for (const bucket of buckets.values()) safeEmit('transport summary', { ...bucket, elapsedMs });
+ let failingBuckets = 0;
+ let okBuckets = 0;
+ let okCompleted = 0;
+ const okChannels = new Map<string, number>();
+ for (const bucket of buckets.values()) {
+ if (bucket.code !== 'OK') {
+ failingBuckets++;
+ safeEmit('transport summary', { ...bucket, elapsedMs });
+ continue;
+ }
+ okBuckets++;
+ okCompleted += bucket.completed;
+ okChannels.set(bucket.channel, (okChannels.get(bucket.channel) ?? 0) + bucket.completed);
+ }
+ if (okBuckets) {
+ const ranked = [...okChannels].sort((a, b) => b[1] - a[1]);
+ safeEmit('transport summary ok', {
+ buckets: okBuckets,
+ completed: okCompleted,
+ channels: Object.fromEntries(ranked.slice(0, MAX_OK_CHANNELS)),
+ ...(ranked.length > MAX_OK_CHANNELS ? { channelsOmitted: ranked.length - MAX_OK_CHANNELS } : {}),
+ elapsedMs,
+ }, failingBuckets || overflowFailures ? 'info' : 'debug');
+ }
if (overflowCompleted)
- safeEmit('transport summary overflow', { overflowCompleted, overflowFailures, elapsedMs });
+ safeEmit('transport summary overflow', { overflowCompleted, overflowFailures, elapsedMs },
+ overflowFailures ? 'info' : 'debug');
buckets.clear();
overflowCompleted = 0;
overflowFailures = 0;
diff --git a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
index 41af413a0d..0177995d01 100644
--- a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
+++ b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
@@ -1,4 +1,5 @@
import { DL_HISTORY_QUERY_CHANNEL } from '@cindy/device-link';
+import { currentDbRpcAdmissionClass, type DbRpcAdmissionClass } from '../localDb/client/rpcAdmission.js';
/**
* - ordinary / visible:正常可见;hidden:伙伴隐藏,任何远端读写都按不存在处理;
@@ -20,6 +21,65 @@ let batchLookup: RemoteBotSessionBatchLookup | null = null;
export function setRemoteBotSessionLookup(value: Lookup | null, batch: RemoteBotSessionBatchLookup | null = null): void {
lookup = value;
batchLookup = value ? batch : null;
+ // Joined requests keep the lookup they were issued against; new ones use the new one.
+ pendingPushAccess.clear();
+}
+
+/**
+ * Push 授权的同轮合并读取(DataLoader 形状,不是缓存)。
+ *
+ * 同一次同步分发(多控制端扇出、一次批量 flush、一轮离线回放)里的 push 在调用时登记
+ * 要查的任务 ID,本轮微任务结束时合并成一次批量读取;读取发出后的登记进入下一轮。
+ * 因此每条 push 的授权读取都在它到达 wire 边界之后才发出,结果只交给已登记的请求,
+ * 读取结算后不保留——隐藏/删除/换账号之后到达的 push 必然重新读库,与逐条读取同样新鲜。
+ * 按 DB 准入等级分轮,后台读不会搭上交互读的轮次(反之亦然)。
+ */
+interface PushAccessRound {
+ readonly ids: Set<string>;
+ /** Settles per ID so an injected single lookup failure stays scoped to that ID. */
+ readonly result: Promise<ReadonlyMap<string, Promise<RemoteBotSessionAccess>>>;
+}
+const pendingPushAccess = new Map<DbRpcAdmissionClass, PushAccessRound>();
+
+function readSessionAccess(
+ single: Lookup, batch: RemoteBotSessionBatchLookup | null, ids: readonly string[],
+): ReadonlyMap<string, Promise<RemoteBotSessionAccess>> {
+ const access = new Map<string, Promise<RemoteBotSessionAccess>>();
+ if (batch) {
+ const rows = batch(ids, 'session');
+ for (const id of ids) access.set(id, rows.then((map) => map.get(id) ?? 'hidden'));
+ } else {
+ // Injected single-lookup consumers keep the previous one-at-a-time read shape.
+ let previous: Promise<unknown> = Promise.resolve();
+ for (const id of ids) {
+ const current = previous.then(() => single(id, 'session'));
+ access.set(id, current);
+ previous = current.catch(() => undefined);
+ }
+ }
+ for (const pending of access.values()) pending.catch(() => undefined);
+ return access;
+}
+
+function readPushSessionAccess(single: Lookup, ids: readonly string[]): Promise<RemoteBotSessionAccess[]> {
+ const admission = currentDbRpcAdmissionClass();
+ let round = pendingPushAccess.get(admission);
+ if (!round) {
+ const roundIds = new Set<string>();
+ const activeBatch = batchLookup;
+ let start!: () => void;
+ const result = new Promise<void>((resolve) => { start = resolve; })
+ .then(() => readSessionAccess(single, activeBatch, [...roundIds]));
+ const created: PushAccessRound = { ids: roundIds, result };
+ round = created;
+ pendingPushAccess.set(admission, created);
+ queueMicrotask(() => {
+ if (pendingPushAccess.get(admission) === created) pendingPushAccess.delete(admission);
+ start();
+ });
+ }
+ for (const id of ids) round.ids.add(id);
+ return round.result.then((access) => Promise.all(ids.map((id) => access.get(id) ?? 'hidden')));
}
function record(value: unknown): Record<string, unknown> | null {
@@ -219,15 +279,20 @@ export async function projectRemoteSessionResult(channel: string, value: unknown
return projected;
}
-/** Called at delivery, including buffered batches and offline replay. */
+/**
+ * Called at delivery, including buffered batches and offline replay. The read is
+ * shared only with pushes reaching the wire boundary in the same pass (see
+ * readPushSessionAccess); it is never reused once issued.
+ */
export async function projectRemoteBotPush(value: unknown, channel = ''): Promise<unknown | null> {
if (!lookup) return value;
const ids = sessionIds(value);
const row = record(value);
if (channel === 'local-db:sessions:created' && typeof row?.id === 'string') ids.push(row.id);
- for (const id of new Set(ids)) {
- const access = await lookup(id);
- if (access === 'hidden' || (access === 'missing' && row?.source === 'bot')) return null;
+ const unique = [...new Set(ids)];
+ if (!unique.length) return value;
+ for (const status of await readPushSessionAccess(lookup, unique)) {
+ if (status === 'hidden' || (status === 'missing' && row?.source === 'bot')) return null;
}
return value;
}
diff --git a/apps/desktop/src/main/device-link/transferCodec.ts b/apps/desktop/src/main/device-link/transferCodec.ts
index 445eca9b9d..cd8d6a8844 100644
--- a/apps/desktop/src/main/device-link/transferCodec.ts
+++ b/apps/desktop/src/main/device-link/transferCodec.ts
@@ -1,10 +1,56 @@
import { createHash } from 'node:crypto';
-import { compressGzipSync, gunzipBase64TextBounded } from '@cindy/device-link/node-compression';
+import { compressGzipSync, gunzipBase64TextBounded, type CompressionStats } from '@cindy/device-link/node-compression';
import type { DeviceLinkTransferCodec } from '@cindy/device-link';
import { createLogger } from '../logger';
const log = createLogger('device-link:compression');
+/** One DEBUG summary per window instead of one line per compressed reply (~16k/day). */
+const COMPRESSION_STATS_WINDOW_MS = 5 * 60_000;
+/** Synchronous gzip blocks the main event loop; a single slow call is worth its own line. */
+const SLOW_COMPRESSION_MS = 100;
+
+/**
+ * 压缩统计聚合:只记原始/gzip/wire 字节与压缩耗时(不记录正文或凭证)。
+ * 不起定时器——窗口到期后的下一次压缩才输出上一窗口的汇总,空闲时零开销;
+ * 单次压缩超过 SLOW_COMPRESSION_MS 立即单独记一行。
+ */
+export function createCompressionStatsLog(
+ emit: (event: string, fields: Record<string, unknown>) => void,
+ now: () => number = Date.now,
+ windowMs = COMPRESSION_STATS_WINDOW_MS,
+): (stats: CompressionStats) => void {
+ let startedAt = 0;
+ let count = 0;
+ let originalBytes = 0;
+ let gzipBytes = 0;
+ let wireBytes = 0;
+ let compressionMs = 0;
+ let maxCompressionMs = 0;
+ return (stats) => {
+ const at = now();
+ if (count > 0 && at - startedAt >= windowMs) {
+ emit('gzip summary', {
+ count, originalBytes, gzipBytes, wireBytes,
+ compressionMs: Math.round(compressionMs),
+ maxCompressionMs: Math.round(maxCompressionMs),
+ elapsedMs: at - startedAt,
+ });
+ count = 0; originalBytes = 0; gzipBytes = 0; wireBytes = 0; compressionMs = 0; maxCompressionMs = 0;
+ }
+ if (count === 0) startedAt = at;
+ count++;
+ originalBytes += stats.originalBytes;
+ gzipBytes += stats.gzipBytes;
+ wireBytes += stats.wireBytes;
+ compressionMs += stats.compressionMs;
+ maxCompressionMs = Math.max(maxCompressionMs, stats.compressionMs);
+ if (stats.compressionMs >= SLOW_COMPRESSION_MS) emit('gzip slow candidate', { ...stats });
+ };
+}
+
+const recordCompression = createCompressionStatsLog((event, fields) => log.debug(event, fields));
+
/**
* Desktop 既是被控端也是控制端(桌面远控桌面),两个方向共用一份编码器。
* 保留 level 4 和同步发送错误契约;Node 编解码通过独立入口复用。
@@ -12,7 +58,7 @@ const log = createLogger('device-link:compression');
export const desktopTransferCodec: DeviceLinkTransferCodec = {
gzipBase64: (text) => {
const { compressed, stats } = compressGzipSync(Buffer.from(text, 'utf8'), 4, true);
- log.debug('gzip candidate', stats);
+ recordCompression(stats);
return compressed.toString('base64');
},
gunzipBase64: gunzipBase64TextBounded,
diff --git a/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.ts b/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.ts
index 01a107fb6c..33d3586de7 100644
--- a/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/authAssetPreparation.test.ts
@@ -5,8 +5,11 @@ const state = vi.hoisted(() => ({
owner: { dataOwnerId: 'a', generation: 1, mode: 'cloud' },
boundary: false,
bridge: vi.fn(),
+ links: vi.fn(),
+ fingerprint: 'fp-1',
+ logs: [] as Array<{ level: string; scope: string; warning?: unknown }>,
}));
-vi.mock('electron', () => ({ app: { getPath: () => '', isPackaged: true }, safeStorage: {} }));
+vi.mock('electron', () => ({ app: { getPath: () => '', getAppPath: () => '', isPackaged: true }, safeStorage: {} }));
vi.mock('@cindy/maker-core', () => ({}));
vi.mock('../../appSessionState.js', async (original) => ({
...await original<typeof import('../../appSessionState.js')>(),
@@ -14,13 +17,42 @@ vi.mock('../../appSessionState.js', async (original) => ({
isAppSessionBoundaryPending: () => state.boundary,
}));
vi.mock('../codex-global-plugins.js', () => ({ prepareCodexGlobalPluginsBridge: state.bridge }));
+vi.mock('../shared-global-skills.js', async (original) => ({
+ ...await original<typeof import('../shared-global-skills.js')>(),
+ prepareSharedGlobalSkillLinks: state.links,
+ sharedGlobalSkillLinksFingerprint: async () => state.fingerprint,
+}));
+vi.mock('../built-in-skills.js', async (original) => ({
+ ...await original<typeof import('../built-in-skills.js')>(),
+ resolveBundledSystemSkillsRoot: () => 'unused-bundle',
+ prepareBuiltInSkills: async () => ({ descriptors: [], projectionSafe: false, warnings: [] }),
+}));
+vi.mock('../../authBoundaryQuarantine.js', async (original) => ({
+ ...await original<typeof import('../../authBoundaryQuarantine.js')>(),
+ withSharedGlobalSkillProjectionMutation: (_owner: unknown, run: () => unknown) => run(),
+}));
+vi.mock('../../logger.js', async (original) => {
+ const record = (scope: string, level: string) => (_msg: string, meta?: { warning?: unknown }) => {
+ state.logs.push({ level, scope, warning: meta?.warning });
+ };
+ return {
+ ...await original<typeof import('../../logger.js')>(),
+ createLogger: (scope: string) => Object.fromEntries(
+ ['trace', 'debug', 'info', 'warn', 'error', 'fatal'].map((level) => [level, record(scope, level)]),
+ ),
+ };
+});
import { DesktopClaudeAuthAdapter, DesktopCodexAuthAdapter } from '../auth-adapters.js';
+import { SHARED_GLOBAL_SKILL_SYNC_DISABLED_NOTICE } from '../shared-global-skills.js';
beforeEach(() => {
state.owner = { dataOwnerId: 'a', generation: 1, mode: 'cloud' };
state.boundary = false;
state.bridge.mockReset().mockResolvedValue({ warnings: [], routingFailures: [] });
+ state.links.mockReset();
+ state.fingerprint = 'fp-1';
+ state.logs = [];
});
describe('asset preparation boundaries', () => {
@@ -57,4 +89,40 @@ describe('asset preparation boundaries', () => {
await adapter.ensureSharedGlobalSkills();
expect(prepare).toHaveBeenCalledTimes(4);
});
+
+ // Regression (idle CPU): the default sync opt-out and user-owned conflicting paths were
+ // returned as warnings, so the 30s completion cache never held and every agent env build
+ // re-ran the whole projection and re-logged the same lines. Unit tier, in-process fakes.
+ it('caches past persistent projection warnings, reports them once, and reruns on input changes', async () => {
+ const conflict = 'cannot link skill x from a to b: path exists and is not a managed symlink/junction';
+ const persistent = [SHARED_GLOBAL_SKILL_SYNC_DISABLED_NOTICE, conflict];
+ state.links.mockResolvedValue({ warnings: persistent, persistentWarnings: persistent });
+ const adapter = new DesktopClaudeAuthAdapter();
+ await adapter.ensureSharedGlobalSkills();
+ await adapter.ensureSharedGlobalSkills();
+ expect(state.links).toHaveBeenCalledTimes(1);
+ const reported = () => state.logs.filter((entry) => entry.scope === 'auth-adapters:asset-prep');
+ expect(reported()).toEqual([
+ { level: 'info', scope: 'auth-adapters:asset-prep', warning: SHARED_GLOBAL_SKILL_SYNC_DISABLED_NOTICE },
+ { level: 'warn', scope: 'auth-adapters:asset-prep', warning: conflict },
+ ]);
+
+ // A settings toggle or root listing change must not be hidden by the cache;
+ // the unchanged persistent set is not reported again.
+ state.fingerprint = 'fp-2';
+ await adapter.ensureSharedGlobalSkills();
+ expect(state.links).toHaveBeenCalledTimes(2);
+ expect(reported()).toHaveLength(2);
+
+ // A retryable failure still defeats the cache and is reported every run.
+ state.fingerprint = 'fp-3';
+ state.links.mockResolvedValue({ warnings: ['cannot link skill y: EACCES'], persistentWarnings: [] });
+ await adapter.ensureSharedGlobalSkills();
+ await adapter.ensureSharedGlobalSkills();
+ expect(state.links).toHaveBeenCalledTimes(4);
+ expect(reported().slice(2).map((entry) => entry.warning)).toEqual([
+ 'cannot link skill y: EACCES',
+ 'cannot link skill y: EACCES',
+ ]);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts
index 6057f9565f..a4163538dd 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeAuthAdapterOAuthEnv.test.ts
@@ -102,8 +102,10 @@ vi.mock('../../secrets/providerSecretStore.js', () => ({
// getAuthEnv 前置的共享 skills 预热会碰真实文件系统 —— 剪断(与本测试无关)。
vi.mock('../shared-global-skills.js', () => ({
- prepareSharedGlobalSkillLinks: async () => ({ warnings: [] }),
+ prepareSharedGlobalSkillLinks: async () => ({ warnings: [], persistentWarnings: [] }),
prepareSharedProjectSkillLinks: async () => ({ warnings: [] }),
+ sharedGlobalSkillLinksFingerprint: async () => 'test',
+ SHARED_GLOBAL_SKILL_SYNC_DISABLED_NOTICE: 'sync disabled',
}));
vi.mock('../built-in-skills.js', () => ({
diff --git a/apps/desktop/src/main/maker-host/__tests__/session-archive-sync.test.ts b/apps/desktop/src/main/maker-host/__tests__/session-archive-sync.test.ts
index 86952b361d..dc6d13391a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/session-archive-sync.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/session-archive-sync.test.ts
@@ -39,13 +39,14 @@ describe('task archive projection', () => {
const live = { getStatus: () => 'active', isTurnRunning: () => false, closeIfIdle: vi.fn(async () => true) };
f.prepare.mockImplementation(rows => prepareArchiveSessions(rows, () => live));
await f.coordinator.request();
- await vi.advanceTimersByTimeAsync(5 * 60_000);
+ await vi.advanceTimersByTimeAsync(60 * 60_000);
expect(f.sync).toHaveBeenCalledTimes(2);
expect(f.sync).toHaveBeenLastCalledWith(expect.objectContaining({ archived: false }));
expect(live.closeIfIdle).not.toHaveBeenCalled();
});
it('defers running handles and closes idle archived handles before syncing', async () => {
+ vi.useFakeTimers();
const f = fixture();
f.insert('task');
const live = { getStatus: () => 'active', isTurnRunning: vi.fn(() => true), closeIfIdle: vi.fn(async () => true) };
@@ -53,8 +54,9 @@ describe('task archive projection', () => {
await f.coordinator.request();
expect(f.sync).not.toHaveBeenCalled();
expect(live.closeIfIdle).not.toHaveBeenCalled();
+ // Turn completion writes no status, so the backed-off tick must pick it up.
live.isTurnRunning.mockReturnValue(false);
- await f.coordinator.request();
+ await vi.advanceTimersByTimeAsync(60_000);
expect(live.closeIfIdle).toHaveBeenCalledTimes(1);
expect(f.sync).toHaveBeenCalledTimes(1);
});
@@ -70,9 +72,10 @@ describe('task archive projection', () => {
// Another native client changes the thread; Cindy's row is unchanged.
nativeArchived = !nativeArchived;
- await vi.advanceTimersByTimeAsync(60_000);
+ // Unchanged rows must not spawn a native control process on every tick.
+ await vi.advanceTimersByTimeAsync(59 * 60_000);
expect(f.sync).toHaveBeenCalledTimes(1);
- await vi.advanceTimersByTimeAsync(4 * 60_000);
+ await vi.advanceTimersByTimeAsync(60_000);
expect(f.sync).toHaveBeenCalledTimes(2);
expect(nativeArchived).toBe(status === 'archived');
expect(f.db.prepare('SELECT status FROM sessions').get()).toEqual({ status });
@@ -95,16 +98,21 @@ describe('task archive projection', () => {
.toEqual({ working_dir: '/project', extra_dirs: '["/reference"]', writable_dirs: '["/output"]' });
});
- it('retries busy and failed records without repeating successful work', async () => {
+ it('backs off busy and failed records, then retries without repeating successful work', async () => {
+ vi.useFakeTimers();
const f = fixture();
f.insert('a'); f.insert('b');
f.prepare.mockResolvedValueOnce(false);
f.sync.mockRejectedValueOnce(new Error('offline'));
await f.coordinator.request();
expect(f.warn).toHaveBeenCalledWith(1);
+ expect(f.sync).toHaveBeenCalledTimes(1);
+ // Unrelated requests before the backoff expires must not retry native work.
await f.coordinator.request();
+ expect(f.sync).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(60_000);
expect(f.sync).toHaveBeenCalledTimes(3);
- await f.coordinator.request();
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(f.sync).toHaveBeenCalledTimes(3);
});
diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.ts
index ad91e9beac..cf99b8e615 100644
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@ -39,7 +39,11 @@ import { prepareCodexGlobalSkillsLinks } from './codex-global-skills.js';
import { prepareCodexGlobalRulesCopy } from './codex-global-rules.js';
import { prepareCodexGlobalPluginsBridge } from './codex-global-plugins.js';
import { DESKTOP_CAPABILITY_ROUTING_POLICY } from './capability-routing.js';
-import { prepareSharedGlobalSkillLinks } from './shared-global-skills.js';
+import {
+ prepareSharedGlobalSkillLinks,
+ SHARED_GLOBAL_SKILL_SYNC_DISABLED_NOTICE,
+ sharedGlobalSkillLinksFingerprint,
+} from './shared-global-skills.js';
import { PreparationCache } from './preparation-cache.js';
import {
prepareBuiltInSkills,
@@ -582,6 +586,8 @@ function claudeSubscriptionServesModel(model: string | undefined): boolean {
/** Claude AuthAdapter —— 只回鉴权 env, endpoint / behavior flag 走 runtime-configs.ts。 */
export class DesktopClaudeAuthAdapter implements AuthAdapter {
private readonly sharedSkillsPreparation = new PreparationCache(30_000);
+ /** Last reported set of persistent projection warnings; each set is logged once. */
+ private reportedPersistentSkillWarnings = '[]';
/** invalidate() 触发时把 auth state 推给 renderer(maker-host 装配注入,对齐 codex)。 */
private onInvalidatedBroadcast?: (reason: string) => void;
@@ -610,7 +616,10 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
async ensureSharedGlobalSkills(): Promise<void> {
const scope = preparationScope();
- await this.sharedSkillsPreparation.ensure(scope.key, async () => {
+ // The opt-in setting and root listings are part of the key so a cached completion
+ // never hides a crossAgentSyncEnabled toggle or an added/removed global skill.
+ const key = JSON.stringify([scope.key, await sharedGlobalSkillLinksFingerprint()]);
+ await this.sharedSkillsPreparation.ensure(key, async () => {
const success = await this.runEnsureSharedGlobalSkills(scope.ownerId);
return success && scope.current();
});
@@ -637,17 +646,32 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
const sharedProjection = await prepareSharedGlobalSkillLinks({
assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
});
+ const persistent = new Set(sharedProjection.persistentWarnings);
return {
warnings: [
...preparedBuiltIns.warnings,
...migrationWarnings,
- ...sharedProjection.warnings,
+ ...sharedProjection.warnings.filter((warning) => !persistent.has(warning)),
],
+ persistentWarnings: sharedProjection.persistentWarnings,
};
});
for (const warning of result.warnings) {
assetPrepLog.warn('shared global skill warning', { warning });
}
+ // The sync opt-out and user-owned conflicting paths are stable state, not failures:
+ // report each distinct set once and let the completion cache hold past them.
+ const persistentSignature = JSON.stringify([...result.persistentWarnings].sort());
+ if (persistentSignature !== this.reportedPersistentSkillWarnings) {
+ this.reportedPersistentSkillWarnings = persistentSignature;
+ for (const warning of result.persistentWarnings) {
+ if (warning === SHARED_GLOBAL_SKILL_SYNC_DISABLED_NOTICE) {
+ assetPrepLog.info('shared global skill notice', { warning });
+ } else {
+ assetPrepLog.warn('shared global skill warning', { warning });
+ }
+ }
+ }
return result.warnings.length === 0;
} catch (error) {
assetPrepLog.warn('prepare shared global skills failed', {
@@ -1370,16 +1394,12 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
private async runEnsureGlobalCodexSkills(ownerId: string | null): Promise<boolean> {
- // Prepare the private built-in roots before Codex snapshots discovery.
+ // Load-bearing order: prepare the private built-in roots and the ~/.agents/skills
+ // projection before Codex snapshots discovery. That shared pass (same call, same
+ // owner guard) runs inside ensureSharedGlobalSkills and reports its own warnings, so
+ // Codex does not repeat it; per-launch freshness of the approved catalog comes from
+ // prepareCodexGlobalSkillsLinks below.
await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();
- const sharedOutcome = await withSharedGlobalSkillProjectionMutation(ownerId, () =>
- prepareSharedGlobalSkillLinks({
- assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
- }),
- ).then(
- (r) => ({ ok: true as const, label: 'shared-skills' as const, warnings: r.warnings }),
- (err: Error) => ({ ok: false as const, label: 'shared-skills' as const, err }),
- );
const [skillsOutcome, rulesOutcome] = await Promise.all([
withSharedGlobalSkillProjectionMutation(ownerId, async () =>
@@ -1394,7 +1414,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
),
]);
- const outcomes = [sharedOutcome, skillsOutcome, rulesOutcome];
+ const outcomes = [skillsOutcome, rulesOutcome];
// A failed verified catalog must not fall back to yesterday's projections.
if (!skillsOutcome.ok) throw skillsOutcome.err;
for (const outcome of outcomes) {
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 7ee2cf7203..606869207a 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1862,7 +1862,8 @@ export function getMaker(): Maker {
let buildSessionMcpConfig:
| ((sessionInstanceId: string) => Record<string, unknown>)
| undefined;
- if (!isReview) {
+ // Review hosts and native-storage-only (archive) hosts never expose Cindy MCP tools.
+ if (!isReview && !ctx.nativeStorageOnly) {
try {
const cfg = await getCodexExtraSpawnConfig({
mcpProviders: providers,
diff --git a/apps/desktop/src/main/maker-host/session-archive-sync.ts b/apps/desktop/src/main/maker-host/session-archive-sync.ts
index 178dc25fd4..8de10d7a75 100644
--- a/apps/desktop/src/main/maker-host/session-archive-sync.ts
+++ b/apps/desktop/src/main/maker-host/session-archive-sync.ts
@@ -12,7 +12,11 @@ const SELECT = `SELECT id, sdk_session_id AS sdkSessionId, remote_host_id AS rem
FROM sessions WHERE agent_kind = 'codex' AND sdk_session_id IS NOT NULL
AND status IN ('active', 'archived')`;
-const NATIVE_RECHECK_MS = 5 * 60_000;
+// Native CLI actions can change storage without updating Cindy. Every group is
+// re-verified in one batched pass at this interval; each pass spawns a native
+// control process, so it stays far apart from the 60s tick.
+const NATIVE_RECHECK_MS = 60 * 60_000;
+const TICK_MS = 60_000;
/** Keep idle active handles available to their native writer; only archived
* handles need closing before the native archive operation. Called under route locks. */
@@ -41,13 +45,19 @@ export function createSessionArchiveSync(deps: {
release(): Promise<void>;
warn(failures: number): void;
}) {
- const applied = new Map<string, { signature: string; checkedAt: number }>();
+ const applied = new Map<string, string>();
+ // Busy or failed groups back off per signature. A Cindy status write changes
+ // the signature, so it is synced on the request that follows it.
+ const deferred = new Map<string, { signature: string; attempts: number; retryAt: number }>();
+ let nativeCheckedAt = Number.NEGATIVE_INFINITY;
let stopped = false;
let pending = false;
let running: Promise<void> | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
async function reconcile(): Promise<void> {
+ const startedAt = Date.now();
+ const recheckNative = startedAt - nativeCheckedAt >= NATIVE_RECHECK_MS;
const scope = deps.capture();
const assertCurrent = () => {
if (stopped) throw new Error('Archive sync stopped');
@@ -63,14 +73,23 @@ export function createSessionArchiveSync(deps: {
groups.set(key, group);
}
for (const key of applied.keys()) if (!groups.has(key)) applied.delete(key);
+ for (const key of deferred.keys()) if (!groups.has(key)) deferred.delete(key);
let failures = 0;
+ const defer = (key: string, signature: string) => {
+ const previous = deferred.get(key);
+ const attempts = previous?.signature === signature ? previous.attempts + 1 : 1;
+ const delay = Math.min(TICK_MS * 2 ** (attempts - 1), NATIVE_RECHECK_MS);
+ applied.delete(key);
+ deferred.set(key, { signature, attempts, retryAt: Date.now() + delay });
+ };
for (const [key, group] of groups) {
assertCurrent();
const signature = JSON.stringify(group.map(row => [row.id, row.status]).sort());
- const previous = applied.get(key);
- // Native CLI actions can change storage without updating Cindy. Bound the
- // cache lifetime, while avoiding a full native scan on every UI mutation.
- if (previous?.signature === signature && Date.now() - previous.checkedAt < NATIVE_RECHECK_MS) continue;
+ if (!recheckNative) {
+ if (applied.get(key) === signature) continue;
+ const backoff = deferred.get(key);
+ if (backoff?.signature === signature && Date.now() < backoff.retryAt) continue;
+ }
const first = group[0]!;
if (first.remoteHostId && !deps.canUseRemote(first.remoteHostId)) continue;
try {
@@ -83,7 +102,8 @@ export function createSessionArchiveSync(deps: {
// A copied task can share a native ID. Active references win; a changed
// group is retried under its complete set of locks on the next pass.
const currentSignature = JSON.stringify(current.map(row => [row.id, row.status]).sort());
- if (currentSignature !== signature || !await deps.prepare(current)) return;
+ if (currentSignature !== signature) return;
+ if (!await deps.prepare(current)) { defer(key, signature); return; }
assertCurrent();
await deps.sync({
threadId: first.sdkSessionId,
@@ -92,13 +112,16 @@ export function createSessionArchiveSync(deps: {
assertCurrent,
});
assertCurrent();
- applied.set(key, { signature, checkedAt: Date.now() });
+ applied.set(key, signature);
+ deferred.delete(key);
});
} catch {
assertCurrent();
+ defer(key, signature);
failures++;
}
}
+ if (recheckNative) nativeCheckedAt = startedAt;
if (failures) deps.warn(failures);
}
@@ -118,7 +141,9 @@ export function createSessionArchiveSync(deps: {
if (!stopped) {
// Also covers internal lifecycle writers and retries after a busy task,
// offline SSH target, unavailable credentials or an interrupted backfill.
- timer = setTimeout(() => { void request(); }, pending ? 0 : 60_000);
+ // The tick itself only reads the database; native work happens only for
+ // changed, backed-off-and-due, or hourly re-verified groups.
+ timer = setTimeout(() => { void request(); }, pending ? 0 : TICK_MS);
timer.unref?.();
}
});
diff --git a/apps/desktop/src/main/maker-host/shared-global-skills.ts b/apps/desktop/src/main/maker-host/shared-global-skills.ts
index 93caf01e62..f97391fde2 100644
--- a/apps/desktop/src/main/maker-host/shared-global-skills.ts
+++ b/apps/desktop/src/main/maker-host/shared-global-skills.ts
@@ -31,8 +31,18 @@ export interface SharedGlobalSkillLinksResult {
changed: boolean;
actions: LinkAction[];
warnings: string[];
+ /**
+ * Subset of `warnings` that describe stable user-owned state rather than a failed
+ * attempt: the cross-agent sync opt-out and user paths we deliberately never
+ * overwrite. Retrying cannot clear them, so callers may cache past them and report
+ * them once instead of on every run.
+ */
+ persistentWarnings: string[];
}
+export const SHARED_GLOBAL_SKILL_SYNC_DISABLED_NOTICE =
+ 'cross-agent global skill sync is disabled; set crossAgentSyncEnabled to opt in';
+
interface PrepareOptions {
homeDir?: string;
/** Optional owner-bound caller guard for Ghost-managed fanout. */
@@ -318,9 +328,10 @@ async function linkEntriesIntoRoot(
targetRoot: string,
useRelativeTarget = false,
assertMutationAllowed?: () => void,
-): Promise<{ actions: LinkAction[]; changed: boolean; warnings: string[] }> {
+): Promise<{ actions: LinkAction[]; changed: boolean; warnings: string[]; persistentWarnings: string[] }> {
const actions: LinkAction[] = [];
const warnings: string[] = [];
+ const persistentWarnings: string[] = [];
let changed = false;
const targetRootCompare = (await realPathOrNull(targetRoot)) ?? normalizeForCompare(targetRoot);
@@ -354,13 +365,14 @@ async function linkEntriesIntoRoot(
};
actions.push(action);
if (result.status === 'conflict' || result.status === 'error') {
- warnings.push(
- `cannot link skill ${entry.name} from ${entry.path} to ${targetPath}: ${result.reason ?? result.status}`,
- );
+ const warning = `cannot link skill ${entry.name} from ${entry.path} to ${targetPath}: ${result.reason ?? result.status}`;
+ warnings.push(warning);
+ // A conflict is a user-owned path we never overwrite; only I/O errors are retryable.
+ if (result.status === 'conflict') persistentWarnings.push(warning);
}
}
- return { actions, changed, warnings };
+ return { actions, changed, warnings, persistentWarnings };
}
/**
@@ -395,6 +407,7 @@ export async function prepareSharedGlobalSkillLinks(
const codexRootCompare = (await realPathOrNull(paths.codexSkillsDir)) ?? normalizeForCompare(paths.codexSkillsDir);
const warnings: string[] = [];
+ const persistentWarnings: string[] = [];
const actions: LinkAction[] = [];
let changed = false;
const managedRoots = Array.from(new Set([
@@ -434,6 +447,7 @@ export async function prepareSharedGlobalSkillLinks(
);
actions.push(...claudeToShared.actions);
warnings.push(...claudeToShared.warnings);
+ persistentWarnings.push(...claudeToShared.persistentWarnings);
changed = changed || claudeToShared.changed;
const codexToClaude = await linkEntriesIntoRoot(
@@ -444,6 +458,7 @@ export async function prepareSharedGlobalSkillLinks(
);
actions.push(...codexToClaude.actions);
warnings.push(...codexToClaude.warnings);
+ persistentWarnings.push(...codexToClaude.persistentWarnings);
changed = changed || codexToClaude.changed;
const codexToShared = await linkEntriesIntoRoot(
@@ -454,10 +469,12 @@ export async function prepareSharedGlobalSkillLinks(
);
actions.push(...codexToShared.actions);
warnings.push(...codexToShared.warnings);
+ persistentWarnings.push(...codexToShared.persistentWarnings);
changed = changed || codexToShared.changed;
} else if (claudeEntries.length > 0 || codexEntries.length > 0) {
// 未 opt-in 且存在可同步的用户技能时才提示;纯 Ghost 对账不打扰。
- warnings.push('cross-agent global skill sync is disabled; set crossAgentSyncEnabled to opt in');
+ warnings.push(SHARED_GLOBAL_SKILL_SYNC_DISABLED_NOTICE);
+ persistentWarnings.push(SHARED_GLOBAL_SKILL_SYNC_DISABLED_NOTICE);
}
const sharedEntries = await listSkillEntries('shared', paths.sharedSkillsDir);
@@ -469,6 +486,7 @@ export async function prepareSharedGlobalSkillLinks(
);
actions.push(...sharedToClaude.actions);
warnings.push(...sharedToClaude.warnings);
+ persistentWarnings.push(...sharedToClaude.persistentWarnings);
changed = changed || sharedToClaude.changed;
opts.assertOwnerStable?.();
@@ -477,9 +495,35 @@ export async function prepareSharedGlobalSkillLinks(
changed,
actions,
warnings,
+ persistentWarnings,
};
}
+/**
+ * Cheap inputs of `prepareSharedGlobalSkillLinks` for completion caches: the opt-in
+ * setting plus each global root's mtime (adding, removing or renaming a top-level skill
+ * entry bumps it). A cached run must not hide a settings toggle or a new/removed skill.
+ */
+export async function sharedGlobalSkillLinksFingerprint(
+ opts: Pick<PrepareOptions, 'homeDir' | 'isCrossAgentSyncEnabled'> = {},
+): Promise<string> {
+ const paths = sharedGlobalSkillsPaths(opts.homeDir);
+ let crossAgentSyncEnabled: boolean | null;
+ try {
+ crossAgentSyncEnabled = opts.isCrossAgentSyncEnabled
+ ? opts.isCrossAgentSyncEnabled()
+ : (await import('./shared-global-skills-settings.js')).readSharedGlobalSkillsSettings().crossAgentSyncEnabled;
+ } catch {
+ crossAgentSyncEnabled = null;
+ }
+ const mtimes = await Promise.all(
+ [paths.sharedSkillsDir, paths.claudeSkillsDir, paths.codexSkillsDir].map(async (dir) => {
+ try { return (await fsp.stat(dir)).mtimeMs; } catch { return null; }
+ }),
+ );
+ return JSON.stringify([crossAgentSyncEnabled, ...mtimes]);
+}
+
/**
* Makes project skills visible to both engines without copying or rewriting them.
*
diff --git a/apps/desktop/src/main/vision-bridge/vision-bridge.ts b/apps/desktop/src/main/vision-bridge/vision-bridge.ts
index d96700c03c..ad07632acb 100644
--- a/apps/desktop/src/main/vision-bridge/vision-bridge.ts
+++ b/apps/desktop/src/main/vision-bridge/vision-bridge.ts
@@ -158,18 +158,35 @@ export function createVisionBridge(deps: VisionBridgeDeps): {
cache.set(key, { value, order: order++ });
}
+ /**
+ * 每个 model 最近一次记录的判定结果。isTargetModel 在每轮请求都会被调用(日志实测
+ * ~4k/天,几乎全是重复的 disabled),只在某 model 的判定结果变化时才写 debug 日志。
+ */
+ const lastTargetDecisionByModel = new Map<string, string>();
+ const TARGET_DECISION_LOG_LIMIT = 128;
+ function logTargetDecision(model: string, decision: string, ctx: Record<string, unknown>): void {
+ if (lastTargetDecisionByModel.get(model) === decision) return;
+ lastTargetDecisionByModel.delete(model);
+ if (lastTargetDecisionByModel.size >= TARGET_DECISION_LOG_LIMIT) {
+ const oldest = lastTargetDecisionByModel.keys().next().value;
+ if (oldest !== undefined) lastTargetDecisionByModel.delete(oldest);
+ }
+ lastTargetDecisionByModel.set(model, decision);
+ logger?.debug?.(`vision bridge: target check -> ${decision}`, { model, ...ctx });
+ }
+
/** 判定某 model 是否启用视觉桥(总开关 + 目标模型命中)。层 B 与层 A 共用。 */
function isTargetModel(model: string, sessionId?: string): boolean {
const settings = readVisionBridgeSettings();
if (!settings.enabled) {
- logger?.debug?.('vision bridge: target check -> disabled', { model });
+ logTargetDecision(model, 'disabled', {});
return false;
}
// 显式命中:运行时 model 可能带 [1m]/codex//bare 变体,targetModels 存的是 catalog id;
// 两边都归一化后再比对,避免勾选命中失败(如 deepseek/deepseek-v4-flash vs ...[1m])。
const normalizedModel = normalizeVisionModelId(model);
if (settings.targetModels.some((id) => normalizeVisionModelId(id) === normalizedModel)) {
- logger?.debug?.('vision bridge: target check -> explicit hit', { model, normalizedModel, targetModels: settings.targetModels });
+ logTargetDecision(model, 'explicit hit', { normalizedModel, targetModels: settings.targetModels });
return true;
}
// 默认合并:用户未显式自定义 targetModels 时,已知无视觉模型(deepseek 等)默认
@@ -181,10 +198,10 @@ export function createVisionBridge(deps: VisionBridgeDeps): {
(entry?.modalities ? entry.modalities.input.includes('image') : undefined);
const knownNoVision = supportsImage !== undefined ? !supportsImage : isKnownNoVisionModel(model);
if (!customized && knownNoVision) {
- logger?.debug?.('vision bridge: target check -> default no-vision hit', { model, normalizedModel });
+ logTargetDecision(model, 'default no-vision hit', { normalizedModel });
return true;
}
- logger?.debug?.('vision bridge: target check -> miss', { model, normalizedModel, customized, knownNoVision });
+ logTargetDecision(model, 'miss', { normalizedModel, customized, knownNoVision });
return false;
}
@@ -505,6 +522,7 @@ export function createVisionBridge(deps: VisionBridgeDeps): {
disposed = true;
cache.clear();
inFlight.clear();
+ lastTargetDecisionByModel.clear();
},
};
}
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts
index 772d0b4699..c9d80eedb8 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkRemoteProjects.test.ts
@@ -232,6 +232,38 @@ describe('startRemoteSessionsReconciler', () => {
expect(refresh).toHaveBeenCalledTimes(3);
});
+ // 测试价值:startRemoteSessionsReconciler 的 cadence 把有 push 的设备全量对账从每拍放宽到
+ // 间隔一次(实测 3 台 peer 每 10s 三连 sessions:list + 自动化读取),但 sessions 订阅缺口
+ // 的设备没有 push 兜底,必须仍每拍补订;wake 不受间隔约束。unit,fake timers。
+ it('reconciles subscribed peers once per interval but subscription gaps every tick', async () => {
+ vi.useFakeTimers();
+ const gaps = new Set(['gap']);
+ const refresh = vi.fn(async (_id: string) => 'ok');
+ const { stop, wake } = startRemoteSessionsReconciler(
+ () => new Map([['healthy', 'A'], ['gap', 'B']]),
+ refresh,
+ 60_000,
+ createReconcileBackoff({ baseMs: 10_000, jitter: (ms) => ms }),
+ () => true,
+ { tickMs: 10_000, needsEveryTick: (id) => gaps.has(id) },
+ );
+ const callsFor = (id: string) => refresh.mock.calls.filter(([device]) => device === id).length;
+ // The first sighting follows bootstrap, so the interval starts there (10s tick).
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(callsFor('healthy')).toBe(0);
+ expect(callsFor('gap')).toBe(6);
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(callsFor('healthy')).toBe(1);
+ gaps.clear();
+ await vi.advanceTimersByTimeAsync(50_000);
+ expect(callsFor('healthy')).toBe(1);
+ expect(callsFor('gap')).toBe(7);
+ wake();
+ expect(callsFor('healthy')).toBe(2);
+ expect(callsFor('gap')).toBe(8);
+ stop();
+ });
+
it('counts one coalesced refresh failure once when periodic ticks overlap', async () => {
vi.useFakeTimers();
const eligible = new Map([['dev-a', 'Mac A']]);
diff --git a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
index 6851011bb0..e59e94dca1 100644
--- a/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
+++ b/apps/desktop/src/renderer/features/device-link/useDeviceLinkRemoteProjects.ts
@@ -132,8 +132,19 @@ export function startSessionListTokenRefresh(
/** sessions:created reseed 防抖(被控端短时间多次创建会话 / orca 起多 worker 时合并重拉)。 */
const RESEED_DEBOUNCE_MS = 300;
-/** best-effort push 的窗口内 anti-entropy 周期。窗口外终态按有界轮询分批收敛。 */
-const RECONCILE_INTERVAL_MS = 10_000;
+/**
+ * best-effort push 的窗口内 anti-entropy 周期。列表、置顶、归档/删除走 sessions:patched /
+ * created push,自动化索引与绑定走 maker:schedule:event push;周期全量只兜丢失的 push,
+ * 窗口外终态按有界轮询分批收敛。重连、熔断恢复、presence 重新合格走 bootstrap 立即重拉,
+ * 回到电脑 / 窗口重新可见走 wake 立即对账,都不等这一拍。
+ */
+const RECONCILE_INTERVAL_MS = 60_000;
+
+/**
+ * 对账检查节拍与失败退避基准。sessions 订阅缺口(补订待重试)的设备没有 push 兜底,
+ * 每拍都对账并补订;其它设备按 RECONCILE_INTERVAL_MS 才发起全量。
+ */
+const RECONCILE_TICK_MS = 10_000;
/** 连续失败退避封顶:失败设备最低仍保持约 2 分钟一次的对账,恢复靠 push / 熔断探测先行。 */
const RECONCILE_BACKOFF_MAX_MS = 120_000;
@@ -235,6 +246,10 @@ export type ReconcileBackoff = ReturnType<typeof createReconcileBackoff>;
* 继续由 refreshRemoteDeviceSessions 负责;连续失败的设备按 createReconcileBackoff 放慢
* (refresh resolve 出的 RefreshResult 用于记账:'gave-up' = 失败,'ok' = 成功,其余中性;
* reject 一律计失败)。返回清理函数,避免窗口卸载后残留 timer。
+ *
+ * cadence.tickMs 小于 intervalMs 时按 tick 检查:needsEveryTick 的设备每拍对账,其它设备
+ * 距上次周期尝试满 intervalMs 才对账(首次见到的设备刚做过 bootstrap,从此刻起算)。
+ * 失败退避与间隔同时生效,取较晚者。不传 cadence 时每拍都到期(原行为)。
*/
export function startRemoteSessionsReconciler(
getEligibleDevices: () => Iterable<readonly [string, string]>,
@@ -242,7 +257,25 @@ export function startRemoteSessionsReconciler(
intervalMs = RECONCILE_INTERVAL_MS,
backoff: ReconcileBackoff = createReconcileBackoff({ baseMs: intervalMs }),
isActive: () => boolean = () => true,
+ cadence?: {
+ tickMs: number;
+ needsEveryTick?: (deviceId: string) => boolean;
+ now?: () => number;
+ },
): { stop: () => void; wake: () => void } {
+ const tickMs = Math.min(cadence?.tickMs ?? intervalMs, intervalMs);
+ const now = cadence?.now ?? Date.now;
+ /** 上次周期尝试时刻;容差半拍,避免 setInterval 抖动把 60s 拖成 70s。 */
+ const lastAttemptAt = new Map<string, number>();
+ const isDue = (deviceId: string): boolean => {
+ if (tickMs >= intervalMs || cadence?.needsEveryTick?.(deviceId)) return true;
+ const last = lastAttemptAt.get(deviceId);
+ if (last === undefined) {
+ lastAttemptAt.set(deviceId, now());
+ return false;
+ }
+ return now() - last >= intervalMs - tickMs / 2;
+ };
// 单次刷新可能横跨多个 tick(弱网下超时链 >10s);weak coalescing 会让后续 tick 拿到
// 同一个在途 Promise,若每个 tick 都挂 then,一次 gave-up 会被重复记账、退避直接跳档
// (review P2)。per-device 在途标记保证一次合并请求只记一次。
@@ -255,7 +288,8 @@ export function startRemoteSessionsReconciler(
for (const [deviceId, name] of getEligibleDevices()) {
seen.add(deviceId);
if (inFlight.has(deviceId)) continue;
- if (!opts?.ignoreBackoff && !backoff.shouldAttempt(deviceId)) continue;
+ if (!opts?.ignoreBackoff && (!isDue(deviceId) || !backoff.shouldAttempt(deviceId))) continue;
+ lastAttemptAt.set(deviceId, now());
inFlight.add(deviceId);
void refresh(deviceId, name)
.then((result) => {
@@ -275,15 +309,18 @@ export function startRemoteSessionsReconciler(
});
}
backoff.retainOnly(seen);
+ for (const deviceId of lastAttemptAt.keys()) {
+ if (!seen.has(deviceId)) lastAttemptAt.delete(deviceId);
+ }
};
- const timer = setInterval(runPass, intervalMs);
+ const timer = setInterval(runPass, tickMs);
return {
stop() {
stopped = true;
clearInterval(timer);
inFlight.clear();
},
- // 从闲置回到在用:立刻对账,不等下一拍 10 秒,也不吃失败退避。闲着不加 30 分钟兜底。
+ // 从闲置回到在用:立刻对账,不等下一拍,也不吃失败退避。闲着不加 30 分钟兜底。
wake() {
runPass({ ignoreBackoff: true });
},
@@ -322,6 +359,14 @@ export function useDeviceLinkRemoteProjects(
windowRole === 'main' ? createRemoteReconcilePresence() : null,
);
const wakeRemoteReconcileRef = useRef<() => void>(() => undefined);
+ const periodicReconcileWasActiveRef = useRef(periodicReconcileActive);
+ useEffect(() => {
+ const wasActive = periodicReconcileWasActiveRef.current;
+ periodicReconcileWasActiveRef.current = periodicReconcileActive;
+ // 独立侧栏重新可见:隐藏期间暂停的对账与跳过的自动化事件立即补上,与主窗口
+ // visibilitychange 的 wake 同口径,不等周期一拍。
+ if (periodicReconcileActive && !wasActive) wakeRemoteReconcileRef.current();
+ }, [periodicReconcileActive]);
useEffect(() => {
const gate = mainPresenceRef.current;
if (windowRole !== 'main' || !gate) return undefined;
@@ -796,8 +841,11 @@ export function useDeviceLinkRemoteProjects(
return result;
},
RECONCILE_INTERVAL_MS,
- undefined,
+ // 失败退避阶梯沿用 10s 基准;健康设备另受 60s 间隔约束。
+ createReconcileBackoff({ baseMs: RECONCILE_TICK_MS }),
() => periodicReconcileActiveRef.current && (mainPresenceRef.current?.isActive() ?? true),
+ // sessions 订阅缺口没有 push 兜底:保持每拍补订 + 对账。
+ { tickMs: RECONCILE_TICK_MS, needsEveryTick: (deviceId) => sessionsSubscribeRetry.has(deviceId) },
);
wakeRemoteReconcileRef.current = periodicReconcile.wake;
@@ -869,7 +917,7 @@ export function useDeviceLinkRemoteProjects(
}
}
if (push.channel === 'maker:schedule:event') {
- // 推送照收;闲着不跟事件去拉整份自动化索引。人回来 wake/10s 用 scope both 补上。
+ // 推送照收;闲着不跟事件去拉整份自动化索引。人回来 / 窗口重新可见时 wake 用 scope both 补上。
const watching =
periodicReconcileActiveRef.current && (mainPresenceRef.current?.isActive() ?? true);
if (!watching) return;
@@ -978,7 +1026,7 @@ export function useDeviceLinkRemoteProjects(
});
// 冷缓存回写由「分片变更」驱动,而不是只在一次成功 refresh 之后:
- // 被控端推来的 archived / deleted 增量(applyPatch)只改内存,若 app 在下一次 10 秒对账
+ // 被控端推来的 archived / deleted 增量(applyPatch)只改内存,若 app 在下一次周期对账
// 之前退出,下次离线冷启动就会把那条已归档 / 已删除的会话又 hydrate 回侧边栏
// (review: codex P1)。订阅覆盖所有 mutation(snapshot / patch / 改名 / 断连 / 移除),
// 去抖 1200ms 合并高频变更,main 侧还有内容指纹去重 —— 内容没变根本不落盘。
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 45271890ba..37272791d3 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -158,7 +158,8 @@ Codex 跨凭证优先保留同一个原生线程;仅当目标需要另一个 h
归档状态以 Cindy 的 `sessions.status` 为准。Codex 经原生 `thread/archive` /
`thread/unarchive` 同步历史位置与索引,成功后更新线程位置记录;禁止直接改原生 SQLite
或搬动 rollout,也不能为归档触发历史复制/重建。启动时补齐存量状态,忙碌任务、离线
-SSH 或暂时失败留待重试;共享原生 ID 的活动任务优先,不关闭其他任务的进程。同步必须
+SSH 或暂时失败按组退避重试;只有状态变化的组才调用原生接口,未变化的组每小时批量复核
+一次(兜底 Cindy 外的原生操作);本地归档用的 app-server 只做存储 RPC,不挂 MCP bridge;共享原生 ID 的活动任务优先,不关闭其他任务的进程。同步必须
持有任务路由锁并验证当前 owner,使用原历史根与数据库根。Claude Code 与 Pi 当前没有
原生归档接口,保持 Cindy 状态;历史扫描及重新导入不得覆盖 Cindy 的归档与归档任务的
项目目录、额外目录及可写目录范围。手机远控复用宿主同一状态写入路径。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 7f186b9b5d..3394aad557 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -230,7 +230,8 @@ Desktop 的压缩保持 gzip level 4 与同步发送/错误处理契约,手
共用这一实现。收益按 gzip 的 base64 长度与原始 JSON 的 UTF-8 **字节数**比较,缩小超过
10% 才采用;大小门槛、解压上限与缓存预算仍按原有字符数计。Node 编解码及数字统计复用
`@cindy/device-link/node-compression` 独立入口,跨平台主入口与 Mobile 不加载 Node 模块。
-DEBUG 统计只记原始/gzip/wire 字节与压缩耗时,不记录正文或凭证。
+DEBUG 统计只记原始/gzip/wire 字节与压缩耗时(按 5 分钟窗口汇总,单次 ≥100ms 单独记),
+不记录正文或凭证。
回归见 Desktop `device-link/__tests__/transferCodec.test.ts`(实际 zlib/pako 解码)。
Mobile 开启本地诊断时,在原有 30 秒/卡顿区间统计内汇总 `relayTransfers`:每个 channel
diff --git a/packages/anthropic-compat-proxy/src/instructions-injection.ts b/packages/anthropic-compat-proxy/src/instructions-injection.ts
index 122e655401..d7e89eb380 100644
--- a/packages/anthropic-compat-proxy/src/instructions-injection.ts
+++ b/packages/anthropic-compat-proxy/src/instructions-injection.ts
@@ -73,8 +73,35 @@ function findHeader(
return null;
}
-function logInjection(logger: ProxyLogger | undefined, ctx: InjectionLogContext): void {
- logger?.debug?.('codex proxy instructions injection', ctx);
+const INJECTION_LOG_DEDUPE_LIMIT = 512;
+
+/**
+ * 每笔 /responses POST 都会走一次注入判定;同一线程的判定通常每轮相同(实测与 POST
+ * 数同量)。只在某线程的判定结果(命中/追加/已存在/前后字节数)变化时记 debug,
+ * 首次出现与变化仍可排查;失败另走 error 日志,不受去重影响。
+ */
+function createInjectionLogger(logger: ProxyLogger | undefined): (ctx: InjectionLogContext) => void {
+ const lastSignatureByThread = new Map<string, string>();
+ return (ctx) => {
+ if (!logger?.debug) return;
+ const threadKey = ctx.selectedThreadId ?? '';
+ const signature = [
+ ctx.selectedHeaderName,
+ ctx.registryHit,
+ ctx.appended,
+ ctx.alreadyPresent,
+ ctx.instructionsBeforeBytes,
+ ctx.instructionsAfterBytes,
+ ].join('|');
+ if (lastSignatureByThread.get(threadKey) === signature) return;
+ lastSignatureByThread.delete(threadKey);
+ if (lastSignatureByThread.size >= INJECTION_LOG_DEDUPE_LIMIT) {
+ const oldest = lastSignatureByThread.keys().next().value;
+ if (oldest !== undefined) lastSignatureByThread.delete(oldest);
+ }
+ lastSignatureByThread.set(threadKey, signature);
+ logger.debug('codex proxy instructions injection', ctx);
+ };
}
/**
@@ -135,6 +162,8 @@ export function createInstructionsInjectionTransform(
return pathname.endsWith('/responses');
});
+ const logInjection = createInjectionLogger(opts.logger);
+
return (body, ctx) => {
if (!pathMatch(ctx.url)) return null;
@@ -146,7 +175,7 @@ export function createInstructionsInjectionTransform(
// No usable thread-id header → can't key the registry. Never fall back to a
// "last/only" entry (that would cross-contaminate sessions); just skip.
if (!selected) {
- logInjection(opts.logger, buildInjectionLog({
+ logInjection(buildInjectionLog({
selected: null, registryHit: false, beforeBytes, afterBytes: beforeBytes,
inputDeveloperCount, appended: false, alreadyPresent: false,
}));
@@ -157,7 +186,7 @@ export function createInstructionsInjectionTransform(
// session, or not yet registered). Skip, no fallback.
const productInstructions = opts.registry.get(selected.value);
if (productInstructions === undefined) {
- logInjection(opts.logger, buildInjectionLog({
+ logInjection(buildInjectionLog({
selected, registryHit: false, beforeBytes, afterBytes: beforeBytes,
inputDeveloperCount, appended: false, alreadyPresent: false,
}));
@@ -172,7 +201,7 @@ export function createInstructionsInjectionTransform(
selected, registryHit: true, beforeBytes, afterBytes: beforeBytes,
inputDeveloperCount, appended: false, alreadyPresent: false,
});
- logInjection(opts.logger, logCtx);
+ logInjection(logCtx);
opts.logger?.error?.('codex proxy instructions injection failed', {
...logCtx,
event: 'codex_proxy_injection_error',
@@ -190,7 +219,7 @@ export function createInstructionsInjectionTransform(
// Idempotent: never append twice.
if (before.includes(productInstructions)) {
- logInjection(opts.logger, buildInjectionLog({
+ logInjection(buildInjectionLog({
selected, registryHit: true, beforeBytes, afterBytes: beforeBytes,
inputDeveloperCount, appended: false, alreadyPresent: true,
}));
@@ -199,7 +228,7 @@ export function createInstructionsInjectionTransform(
// Append after the existing codex base instructions — never replace.
const nextInstructions = before ? `${before}\n\n${productInstructions}` : productInstructions;
- logInjection(opts.logger, buildInjectionLog({
+ logInjection(buildInjectionLog({
selected, registryHit: true, beforeBytes, afterBytes: textBytes(nextInstructions),
inputDeveloperCount, appended: true, alreadyPresent: false,
}));
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index 165b6957b6..96ece08e55 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -3678,6 +3678,75 @@ describe('anthropic-compat-proxy 客户端中断传播', () => {
expect(errorLogs.filter((m) => m.includes('upstream response stream error'))).toHaveLength(0);
});
+ // 回归:Codex CLI 收到 response.completed 即断开,上游 body 往往尚未 end —— 日志里 ~97%
+ // 的 /responses 被误记成 client-aborted。终态事件后断开须按正常完成收口(仍释放上游),
+ // 只有终态前断开才是失败。
+ it.each([
+ {
+ name: 'terminal event forwarded → complete',
+ events: 'event: response.created\ndata: {"type":"response.created"}\n\n'
+ + 'event: response.completed\ndata: {"type":"response.completed","response":{}}\n\n',
+ waitFor: 'response.completed',
+ expected: { type: 'complete', status: 200 },
+ observerEnds: 1,
+ disconnectLogs: 0,
+ },
+ {
+ name: 'no terminal event yet → client-aborted',
+ events: 'event: response.created\ndata: {"type":"response.created"}\n\n',
+ waitFor: 'response.created',
+ expected: { type: 'failure', failure: 'client-aborted' },
+ observerEnds: 0,
+ disconnectLogs: 1,
+ },
+ ])('client close after SSE: $name', async ({ events: sse, waitFor, expected, observerEnds, disconnectLogs }) => {
+ let sawUpstreamClose!: () => void;
+ const upstreamClosed = new Promise<void>((r) => { sawUpstreamClose = r; });
+ const upstream = await startFakeUpstream((_idx, _body, res) => {
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ res.write(sse);
+ // 永不 end:上游在终态事件后仍保持 body 打开。
+ res.on('close', () => sawUpstreamClose());
+ });
+ upstreamClose = upstream.close;
+ const lifecycle: Array<Record<string, unknown>> = [];
+ const infoLogs: string[] = [];
+ let ends = 0;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ logger: { info: (msg) => { infoLogs.push(msg); } },
+ routingTransform: () => ({
+ forwardLifecycle: {
+ onComplete: (status) => lifecycle.push({ type: 'complete', status }),
+ onFailure: (failure) => lifecycle.push({ type: 'failure', failure }),
+ },
+ }),
+ responseObserver: () => ({ onEnd: () => { ends += 1; } }),
+ });
+
+ const controller = new AbortController();
+ const res = await fetch(`${proxy.url}/v1/responses`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ model: 'test-model', stream: true }),
+ signal: controller.signal,
+ });
+ const reader = (res.body as ReadableStream<Uint8Array>).getReader();
+ const decoder = new TextDecoder();
+ let received = '';
+ while (!received.includes(waitFor)) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ received += decoder.decode(value, { stream: true });
+ }
+ controller.abort();
+ await upstreamClosed;
+ await vi.waitFor(() => expect(lifecycle).toEqual([expected]));
+ expect(ends).toBe(observerEnds);
+ expect(infoLogs.filter((m) => m.includes('client disconnected'))).toHaveLength(disconnectLogs);
+ });
+
it('透明重试后的上游 2xx SSE 中断时,立即收口且旧 listener 不误报客户端断开', async () => {
const errorLogs: Array<{ msg: string; ctx?: Record<string, unknown> }> = [];
const infoLogs: string[] = [];
diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.ts
index e820b7835b..0510a2e0e9 100644
--- a/packages/anthropic-compat-proxy/src/server.ts
+++ b/packages/anthropic-compat-proxy/src/server.ts
@@ -130,6 +130,13 @@ const DEBUG_REQUEST_DUMP_MAX_BYTES = 64 * 1024;
// 错误响应 (status >= 400) body 的 dump 上限。错误响应通常只是一个 JSON error 对象
// (~几百字节),给 16KB 已经非常宽裕,超出按相同截断策略尾部追加 "... (truncated, total N bytes)"。
const ERROR_RESPONSE_DUMP_MAX_BYTES = 16 * 1024;
+/**
+ * 流式响应的终态事件:Responses `response.completed|failed|incomplete`、Anthropic
+ * `message_stop`、Chat Completions `data: [DONE]`。见 forward() 里 client close 的收口。
+ */
+const SSE_TERMINAL_EVENT_RE =
+ /\nevent:[ \t]*(?:response\.(?:completed|failed|incomplete)|message_stop)[ \t]*(?:\r?\n|\r?$)|"type"[ \t]*:[ \t]*"(?:response\.(?:completed|failed|incomplete)|message_stop)"|\ndata:[ \t]*\[DONE\]/;
+const SSE_TERMINAL_SCAN_TAIL_CHARS = 64;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -1057,6 +1064,10 @@ function forward(
// upstreamReq.error 或 upstreamRes.error。request 侧通过这个回调汇入当前
// response 的终态处理,保证 observer 与下游收口语义不受事件先后影响。
let failActiveResponse: ((err: unknown) => void) | null = null;
+ // 2xx SSE 已把终态事件(response.completed / message_stop / [DONE] 等)转给客户端后,
+ // 客户端随即断开是正常收尾(Codex CLI 收到 response.completed 就关连接,上游 body 往往
+ // 还没 end)。流式路径在这里挂一个收口函数:返回 true 表示已按正常完成处理。
+ let completeAfterTerminalSseEvent: (() => boolean) | null = null;
// upstreamRes emits `end` before a request-scoped response Transform finishes
// its _flush. Keep those downstream transforms pending so an async flush
// error can still fail the client instead of being mistaken for a harmless
@@ -1098,6 +1109,11 @@ function forward(
// 透明重试的上一笔 forward 也保留着 close listener;它的上游已经 end,
// 后一笔若因上游故障 destroy clientRes,不能被旧 listener 误报成客户端断开。
if (proxyDestroyedClient || upstreamResponseTerminal === 'end' || clientRes.writableEnded) return;
+ if (completeAfterTerminalSseEvent?.()) {
+ // 生成已经结束,不存在计费泄漏;仍释放上游 socket,不让它悬挂到 body 自然结束。
+ upstreamReq.destroy();
+ return;
+ }
clientAborted = true;
if (upstreamResponseTerminal === null) upstreamResponseTerminal = 'client-aborted';
if (forwardLifecycle?.onFailure) {
@@ -1665,6 +1681,43 @@ function forward(
// 收 body: 总字节始终累加;status >= 400 时额外收集前 ERROR_RESPONSE_DUMP_MAX_BYTES
// 字节做 dump 用。2xx 路径只做计数, 无内存压力。
// 错误响应的 status 在 'response' 事件就拿到了,这里直接判断要不要开收集器。
+ // 终态 SSE 事件探测:仅明文 2xx SSE(压缩流无法按行扫描,保持原有断开即失败语义)。
+ // 匹配 `event: <终态>` 行或 data JSON 的顶层 `"type":"<终态>"`(JSON 字符串内的引号
+ // 必然被转义,正文内容不会误命中);保留上一 chunk 的尾巴以覆盖跨 chunk 截断。
+ const scanTerminalSseEvent = (isSse || canInferSse) && !isCompressed && status >= 200 && status < 300;
+ let terminalSseEventSeen = false;
+ // 以换行起头:首个 chunk 开头即视为行首。
+ let terminalSseScanTail = '\n';
+ const scanChunkForTerminalSseEvent = (chunk: Buffer): void => {
+ if (!scanTerminalSseEvent || terminalSseEventSeen) return;
+ const text = terminalSseScanTail + chunk.toString('latin1');
+ if (SSE_TERMINAL_EVENT_RE.test(text)) {
+ terminalSseEventSeen = true;
+ terminalSseScanTail = '';
+ return;
+ }
+ terminalSseScanTail = text.slice(-SSE_TERMINAL_SCAN_TAIL_CHARS);
+ };
+ completeAfterTerminalSseEvent = () => {
+ if (!terminalSseEventSeen || !streamGateCommitted || upstreamResponseTerminal !== null) return false;
+ upstreamResponseTerminal = 'end';
+ // transform 随 clientRes close 一起被 destroy,不会再 emit 'end';清掉挂起集合,
+ // 让随后 upstream 的 aborted/error 被视为已收口后的迟到事件。
+ pendingResponseTransforms.clear();
+ observerEnd();
+ logger.debug?.('client closed after terminal SSE event — releasing upstream', {
+ reqId,
+ method,
+ path: upstreamPathname,
+ status,
+ bytes: totalBytes,
+ });
+ if (forwardLifecycle?.onComplete) {
+ notifyForwardLifecycle(() => forwardLifecycle.onComplete?.(status));
+ }
+ return true;
+ };
+
const collectErrBody = status >= 400;
let totalBytes = 0;
const errBuf: Buffer[] = [];
@@ -1675,6 +1728,7 @@ function forward(
lastChunkBytes = chunk.length;
lastChunkAt = Date.now();
observerData(chunk);
+ scanChunkForTerminalSseEvent(chunk);
if (collectErrBody && errBufBytes < ERROR_RESPONSE_DUMP_MAX_BYTES) {
const remain = ERROR_RESPONSE_DUMP_MAX_BYTES - errBufBytes;
errBuf.push(chunk.length <= remain ? chunk : chunk.subarray(0, remain));
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 1d23caac18..7a7bd72f52 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -1042,6 +1042,12 @@ export interface AgentDeps {
requestedCredentialMode?: AgentCredentialMode;
/** Marks app-server work that must not share the normal local task host. */
hostPurpose?: 'control-plane' | 'review' | 'custom-context';
+ /**
+ * Control-plane host that only serves native thread storage RPCs
+ * (thread/read, thread/archive, thread/unarchive) and never runs a turn,
+ * so it must not start the Cindy MCP bridge.
+ */
+ nativeStorageOnly?: boolean;
/** Wire model id whose native catalog entry must allow the requested window. */
customContextModel?: string;
/** Requested context window for a one-session custom-context host. */
diff --git a/packages/maker-core/src/agents/codex/app-server/host.test.ts b/packages/maker-core/src/agents/codex/app-server/host.test.ts
index c287f27e01..35e0c0ade9 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.test.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.test.ts
@@ -257,6 +257,50 @@ describe('AppServerHost assistant text delta routing', () => {
});
});
+// 保护: account/rateLimits/updated 按 limitId 去重后, 不变的快照不再重复广播 (原先每
+// ~3.5s 一条 account_usage), 但内容变化仍立即下发, 且晚到的 subscriber 仍能经 replay
+// 立即拿到当前配额 (Codex chip 冷启动依赖它)。
+describe('AppServerHost account rate limit fan-out', () => {
+ it('fans out only changed snapshots per limitId and still replays the latest to late subscribers', async () => {
+ const transport = new NotificationTransport();
+ const host = new AppServerHost({
+ createTransport: () => transport,
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ });
+ await host.ensureStarted();
+ const early = vi.fn();
+ const earlySubscription = host.subscribeThread('thread-1', { accountRateLimitsUpdated: early });
+ const snapshot = (limitId: string, usedPercent: number) => ({
+ method: 'account/rateLimits/updated',
+ params: { rateLimits: { limitId, primary: { usedPercent, windowDurationMins: 300, resetsAt: 1 } } },
+ });
+
+ transport.emit(snapshot('codex', 10));
+ transport.emit(snapshot('codex', 10));
+ transport.emit(snapshot('codex_spark', 10));
+ transport.emit(snapshot('codex', 10));
+ transport.emit(snapshot('codex', 20));
+
+ expect(early.mock.calls.map(([p]) => [p.rateLimits.limitId, p.rateLimits.primary.usedPercent])).toEqual([
+ ['codex', 10],
+ ['codex_spark', 10],
+ ['codex', 20],
+ ]);
+
+ transport.emit(snapshot('codex', 20));
+ const late = vi.fn();
+ const lateSubscription = host.subscribeThread('thread-2', { accountRateLimitsUpdated: late });
+ expect(late).toHaveBeenCalledOnce();
+ expect(late.mock.calls[0][0].rateLimits).toMatchObject({ limitId: 'codex', primary: { usedPercent: 20 } });
+ expect(early).toHaveBeenCalledTimes(3);
+
+ await earlySubscription.release();
+ await lateSubscription.release();
+ await host.shutdown();
+ });
+});
+
describe('AppServerHost custom Provider subagent policy', () => {
const routes = [
{
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index 1e26df27ee..1e6c2cc186 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -110,6 +110,12 @@ const NOTIFICATIONS_TO_OPT_OUT = [
'item/plan/delta',
'item/commandExecution/outputDelta',
'item/fileChange/outputDelta',
+ // 以下高频通知全仓无消费方 (client 只会落一条 unhandled notification 日志, 实测合计
+ // ~2万条/天)。要消费其中任一项时, 先从这里移除再加进 SUBSCRIBED_METHODS。
+ 'turn/moderationMetadata',
+ 'mcpServer/startupStatus/updated',
+ 'remoteControl/status/changed',
+ 'item/commandExecution/terminalInteraction',
];
const DEFAULT_THREAD_UNSUBSCRIBE_TIMEOUT_MS = 5_000;
@@ -374,6 +380,11 @@ export class AppServerHost {
* session 时不必等下次 turn 完成才看到 chip 数据。整个 host 生命周期共享一份 (账号级)。
*/
private lastAccountRateLimits: AccountRateLimitsUpdatedNotification['params'] | null = null;
+ /**
+ * 按 limitId 记录最近一次已 fan-out 的配额 payload (JSON)。app-server 会以秒级间隔
+ * 重复推送内容不变的快照 (实测 ~64% 与上一条相同), 相同内容不再重复广播与记日志。
+ */
+ private readonly lastFannedOutRateLimitsJson = new Map<string, string>();
private shuttingDown = false;
private shutdownPromise: Promise<void> | null = null;
@@ -1193,10 +1204,15 @@ export class AppServerHost {
// 缓存最近 snapshot (给新 subscribe replay) + 广播给所有 active subscriber 各一份。
if (method === 'account/rateLimits/updated') {
const p = params as AccountRateLimitsUpdatedNotification['params'];
+ // replay 快照始终跟随最新一条 (哪怕内容未变), 新 subscriber 拿到的与旧行为一致。
this.lastAccountRateLimits = p;
- this.logger.info('accountRateLimits fan-out', {
+ const rawJson = JSON.stringify(p.rateLimits ?? null);
+ const limitKey = p.rateLimits?.limitId ?? '';
+ if (this.lastFannedOutRateLimitsJson.get(limitKey) === rawJson) return;
+ this.lastFannedOutRateLimitsJson.set(limitKey, rawJson);
+ this.logger.debug('accountRateLimits fan-out', {
subscribers: this.subscribers.size,
- rawJson: JSON.stringify(p.rateLimits ?? null),
+ rawJson,
});
for (const handlers of this.subscribers.values()) {
try {
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index e53a8d40b5..77e4132420 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -592,13 +592,19 @@ describe('Codex archive synchronization', () => {
MockCodexTransport.onCreate = transport => transport.setMockResponse('thread/read', { result: {
thread: { id: 'archived-thread', path: '/history/archived_sessions/rollout.jsonl' },
} });
+ const prepareCodexExtraSpawnConfig = vi.fn(async () => ({ extraArgs: [], extraEnv: {} }));
const agent = new CodexAgent(createDeps({}, {
resolveCodexThreadStorage: async () => ({ historyHome: '/history', sqliteHome: '/state' }),
recordCodexThreadLocation,
+ prepareCodexExtraSpawnConfig,
}));
try {
await agent.syncThreadArchiveState({ threadId: 'archived-thread', archived: true, assertCurrent: () => {} });
expect(createdTransports).toHaveLength(1);
+ // Archive hosts never run turns; the host builds no MCP bridge for them.
+ expect(prepareCodexExtraSpawnConfig).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ hostPurpose: 'control-plane', nativeStorageOnly: true,
+ }));
expect(createdStdioOptions[0].extraArgs).toContain('sqlite_home="/state"');
expect(recordCodexThreadLocation).toHaveBeenCalledWith('archived-thread', '/state', '/history/archived_sessions/rollout.jsonl');
await agent.releaseArchiveHosts();
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 4f4be5d6bd..2b7bfb2fee 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -1966,6 +1966,8 @@ export class CodexAgent extends BaseAgent {
if (!opts.remoteHostId) this.archiveHostKeys.add(key);
const host = await this.getHost(opts.remoteHostId, undefined, {
keyOverride: key, hostPurpose: 'control-plane',
+ // Local archive hosts never run turns; skip the MCP bridge they would never use.
+ ...(!opts.remoteHostId ? { nativeStorageOnly: true } : {}),
...(storage ? { historyHome: storage.historyHome, sqliteHome: storage.sqliteHome } : {}),
});
return { key, host };
@@ -2547,6 +2549,8 @@ export class CodexAgent extends BaseAgent {
localAuthPolicy?: 'isolated' | 'legacy-shared';
keyOverride?: string;
hostPurpose?: 'control-plane' | 'review' | 'custom-context';
+ /** Archive-only control host: native storage RPCs, no turns, no MCP bridge. */
+ nativeStorageOnly?: boolean;
customContextModel?: string;
customContextWindow?: number;
sqliteHome?: string;
@@ -2780,6 +2784,7 @@ assertRouteCurrent();
opts.localAuthPolicy,
opts.routeIsCurrent,
opts.deviceHostedGuestProviderId,
+ opts.nativeStorageOnly,
).finally(() => {
// 成功: this.hosts 已赋值, 后续走快路径; 失败: 清掉 promise 让下次调用能重试
const current = this.hostPromises.get(key);
@@ -3028,6 +3033,7 @@ assertRouteCurrent();
localAuthPolicy?: 'isolated' | 'legacy-shared',
routeIsCurrent?: () => boolean,
deviceHostedGuestProviderId?: string,
+ nativeStorageOnly?: boolean,
): Promise<AppServerHost> {
const seq = (this.createHostSeqByKey.get(key) ?? 0) + 1;
this.createHostSeqByKey.set(key, seq);
@@ -3164,6 +3170,7 @@ assertRouteCurrent();
? { requestedCredentialMode: credentialMode }
: {}),
...(hostPurpose ? { hostPurpose } : {}),
+ ...(nativeStorageOnly ? { nativeStorageOnly } : {}),
...(hostPurpose === 'custom-context'
? {
customContextModel,