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(companions): stream snapshot accounting and keep disabled Skills inactive

Chris140e1701716e
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index 91b32c3282..a9c92d78f7 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -28,6 +28,12 @@ preview retains its full snapshot and normal error path. Discovery performs no w
Retained previews are limited to one per controller, four total and 128 MiB of
snapshot data combined. Oldest previews are evicted through the existing expired
preview flow. Recovery reads its durable checkpoint without caching another preview.
+Preview/retry accounting and source fingerprints stream the existing item graph
+without a mapped clone or full metadata JSON string. Strings use 16 Ki-character
+chunks (preserving surrogate pairs); each 64 KiB of work yields to Main and retry/
+preview accounting rechecks the owner. Binary files are charged directly and the
+legacy byte/hash representation remains unchanged. A refreshed cache entry cannot
+replace a newer preview while waiting; over-budget reads stop during accounting.
All command operations use the existing per-call approval policy. Discovery never
persists a native tool/server grant that could authorize a later `start` operation.
Auto still reviews the actual invocation; Full Access retains its normal behavior.
@@ -144,6 +150,9 @@ omitting it retains normal companion defaults, and a rejected request can be cor
Warm search and pagination stream that index and retain only the requested
response page, without reopening each source file. Full name/description
matching, stable name/slug ordering and disabled entries remain available.
+ Disabled query results retain management/deduplication metadata and `enabled:
+ false`, but omit `filePath` and `bodyStartLine`. Original files and the settings
+ read remain intact; enabling a Skill restores its body/resource discovery path.
Mutation invalidation and watcher recovery also cover this query index and
disabled metadata. A cold cache builds it once; subsequent queries still scan
index bytes for exact matching/counts, rather than maintaining a search database.
diff --git a/apps/desktop/src/main/bot-import/__tests__/files.test.ts b/apps/desktop/src/main/bot-import/__tests__/files.test.ts
index e57f29c2ef..faf001b5ee 100644
--- a/apps/desktop/src/main/bot-import/__tests__/files.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/files.test.ts
@@ -1,5 +1,5 @@
import { expect, it, vi } from 'vitest';
-import { createImportBudget, deserializeImportSnapshot, readImportFile, readImportTree, serializeImportSnapshot, snapshotFingerprint } from '../files.js';
+import { createImportBudget, deserializeImportSnapshot, readImportFile, readImportTree, reserveSnapshotItems, serializeImportSnapshot, snapshotFingerprint, snapshotFingerprintAsync } from '../files.js';
import { readImportSkillTree } from '../skills.js';
import type { ImportSnapshot } from '../types.js';
import { promises as fs } from 'node:fs';
@@ -145,3 +145,71 @@ it('copies native venv interpreter aliases while keeping unrelated external link
await expect(readImportSkillTree(skill)).rejects.toThrow('SOURCE_LINK_OUTSIDE_FOLDER');
} finally { await fs.rm(root, { recursive: true, force: true }); }
});
+
+it.each(['items', 'files'] as const)('counts a 100,000-entry %s snapshot incrementally and yields without serializing its graph', async kind => {
+ const file = { name: 'empty', bytes: Buffer.alloc(0), executable: false };
+ const view = { id: 'skill', name: 'Fixture', category: 'skills' as const, selected: true };
+ const items = kind === 'items' ? Array.from({ length: 100_000 }, () => ({ view }))
+ : [{ view, files: Array.from({ length: 100_000 }, () => file) }];
+ const stringify = JSON.stringify;
+ const serialize = vi.spyOn(JSON, 'stringify').mockImplementation((value, ...args) => {
+ if (value && typeof value === 'object') throw new Error('snapshot graph serialized');
+ return stringify(value, ...args);
+ });
+ let bytes = 0, files = 0, yielded = false;
+ const turn = new Promise<void>(resolve => setImmediate(() => { yielded = true; resolve(); }));
+ try {
+ await reserveSnapshotItems(items, { reserve: size => { bytes += size; }, reserveFile: size => { bytes += size + 256; files++; } });
+ expect(bytes).toBeGreaterThan(100_000);
+ expect(files).toBe(kind === 'files' ? 100_000 : 0);
+ expect(yielded).toBe(true);
+ expect(items[0]?.view).toBe(view);
+ } finally { serialize.mockRestore(); await turn; }
+});
+
+it('preserves exact legacy budget bytes and fingerprints across streamed string/file boundaries', async () => {
+ const text = 'x'.repeat(16 * 1024 - 1) + '😀漢\u0000\n"\\' + '\ud800';
+ const files = [{ name: 'empty', bytes: Buffer.alloc(0), executable: false },
+ { name: 'binary', bytes: Buffer.alloc(128 * 1024, 255), executable: true }];
+ const items = [{ view: { id: 'fixture', name: text, category: 'memory' as const, selected: true }, files,
+ asset: { name: 'asset', bytes: Buffer.from('fixture') },
+ credential: { format: 'fixture', value: { when: new Date('2026-09-29T00:00:00Z'), list: [null, false, undefined, 7, Infinity], omitted: undefined, hidden: { toJSON: () => undefined } } }, text }];
+ const mapped = items.map(item => ({ ...item, files: item.files.map(file => ({ ...file, bytes: null })), asset: { ...item.asset, bytes: null } }));
+ const expected = Buffer.byteLength(JSON.stringify(mapped)) + files.reduce((total, file) => total + file.bytes.length + 256, 0) + items[0]!.asset.bytes.length + 256;
+ const before = serializeImportSnapshot({ source: {} as never, fingerprint: 'fixture', items });
+ await reserveSnapshotItems(items, createImportBudget(expected));
+ await expect(reserveSnapshotItems(items, createImportBudget(expected - 1))).rejects.toThrow('SOURCE_SNAPSHOT_TOO_LARGE');
+ expect(await snapshotFingerprintAsync(items)).toBe(snapshotFingerprint(items));
+ expect(serializeImportSnapshot({ source: {} as never, fingerprint: 'fixture', items })).toBe(before);
+});
+
+it('stops streamed accounting on budget exhaustion and on an owner change', async () => {
+ const view = { id: 'fixture', name: 'Fixture', category: 'memory' as const, selected: true };
+ const read = vi.fn(() => 'tail should stay unread');
+ const tail = { view, get text() { return read(); } };
+ const items = [{ view, text: 'x'.repeat(1024 * 1024) }, tail];
+ await expect(reserveSnapshotItems(items, createImportBudget(1000))).rejects.toThrow('SOURCE_SNAPSHOT_TOO_LARGE');
+ expect(read).not.toHaveBeenCalled();
+ let changed = false;
+ const turn = new Promise<void>(resolve => setImmediate(() => { changed = true; resolve(); }));
+ await expect(reserveSnapshotItems(items, createImportBudget(), () => {
+ if (changed) throw new Error('OWNER_CHANGED');
+ })).rejects.toThrow('OWNER_CHANGED');
+ expect(read).not.toHaveBeenCalled();
+ await turn;
+});
+
+it('accounts a near-budget binary snapshot without serializing or copying its buffers', async () => {
+ const bytes = Buffer.alloc(16 * 1024 * 1024, 1);
+ const items = Array.from({ length: 7 }, (_, index) => ({
+ view: { id: `fixture-${index}`, name: 'Fixture', category: 'memory' as const, selected: true },
+ asset: { name: `${index}.bin`, bytes },
+ }));
+ const toJSON = vi.spyOn(Buffer.prototype, 'toJSON').mockImplementation(() => { throw new Error('buffer copied'); });
+ try {
+ await reserveSnapshotItems(items, createImportBudget());
+ expect(items.every(item => item.asset.bytes === bytes)).toBe(true);
+ await expect(reserveSnapshotItems([...items, ...items.slice(0, 2)], createImportBudget())).rejects.toThrow('SOURCE_SNAPSHOT_TOO_LARGE');
+ expect(toJSON).not.toHaveBeenCalled();
+ } finally { toJSON.mockRestore(); }
+});
diff --git a/apps/desktop/src/main/bot-import/files.ts b/apps/desktop/src/main/bot-import/files.ts
index ad8975e3f5..27eab9c50e 100644
--- a/apps/desktop/src/main/bot-import/files.ts
+++ b/apps/desktop/src/main/bot-import/files.ts
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
import { constants, promises as fs } from 'node:fs';
import path from 'node:path';
import { encodeEnvironment, decodeEnvironment } from './environmentJson.js';
+import { visitSnapshotJson } from './snapshotJson.js';
import { CompanionImportError, type ImportFile, type ImportItem, type ImportSnapshot } from './types.js';
const MAX_FILE_BYTES = 16 * 1024 * 1024;
@@ -32,6 +33,12 @@ export function snapshotFingerprint(items: ImportItem[]): string {
return fingerprint(mapItemBytes(items, digest));
}
+export async function snapshotFingerprintAsync(items: ImportItem[]): Promise<string> {
+ const hash = createHash('sha256');
+ await visitSnapshotJson(items, bytes => createHash('sha256').update(bytes).digest('hex'), text => { hash.update(text); });
+ return hash.digest('hex');
+}
+
function mapItemBytes(items: ImportItem[], encode: (bytes: Buffer) => unknown) {
return items.map(item => ({ ...item,
...(item.files ? { files: item.files.map(file => ({ ...file, bytes: encode(file.bytes) })) } : {}),
@@ -39,9 +46,9 @@ function mapItemBytes(items: ImportItem[], encode: (bytes: Buffer) => unknown) {
}));
}
-export function reserveSnapshotItems(items: ImportItem[], budget: ImportReadBudget): void {
- const metadata = mapItemBytes(items, bytes => { budget.reserveFile(bytes.length); return null; });
- budget.reserve(Buffer.byteLength(JSON.stringify(metadata)));
+export async function reserveSnapshotItems(items: ImportItem[], budget: ImportReadBudget, assertOwner: () => void = () => {}): Promise<void> {
+ await visitSnapshotJson(items, bytes => { budget.reserveFile(bytes.length); return null; },
+ text => budget.reserve(Buffer.byteLength(text)), assertOwner);
}
/** Checkpoints use compact binary encoding; old numeric-array checkpoints still resume. */
diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.ts
index 2a5150f569..c1e19e838a 100644
--- a/apps/desktop/src/main/bot-import/host.ts
+++ b/apps/desktop/src/main/bot-import/host.ts
@@ -90,12 +90,16 @@ export async function listCompanionImportSources(controller: string): Promise<Co
}
/** Keep at most one preview per controller, four total, within one snapshot byte budget. */
-function retainPreview(id: string, entry: Owned<ImportSnapshot>) {
- previews.delete(id);
+async function retainPreview(id: string, entry: Owned<ImportSnapshot>, assertOwner: () => void, refresh = false) {
let bytes = Buffer.byteLength(JSON.stringify({ ...entry.value, items: undefined }));
- const reserve = (size: number) => { bytes += size; };
- reserveSnapshotItems(entry.value.items, { reserve, reserveFile: reserve });
+ const reserve = (size: number) => {
+ bytes += size;
+ if (bytes > MAX_SNAPSHOT_BYTES) throw new CompanionImportError('SOURCE_SNAPSHOT_TOO_LARGE');
+ };
+ await reserveSnapshotItems(entry.value.items, { reserve, reserveFile: reserve }, assertOwner);
if (bytes > MAX_SNAPSHOT_BYTES) throw new CompanionImportError('SOURCE_SNAPSHOT_TOO_LARGE');
+ if (refresh && previews.get(id) !== entry) return;
+ previews.delete(id);
prune(previews);
for (const [key, prior] of previews) if (prior.controller === entry.controller) previews.delete(key);
let total = [...previews.values()].reduce((sum, preview) => sum + preview.bytes, 0);
@@ -118,7 +122,7 @@ export async function previewCompanionImport(sourceId: string, controller: strin
scope.assert();
}
const id = randomUUID();
- retainPreview(id, { owner: scope.scope, controller, value: snapshot, createdAt: Date.now() });
+ await retainPreview(id, { owner: scope.scope, controller, value: snapshot, createdAt: Date.now() }, scope.assert);
const secrets = previewImportRedactions(snapshot.items);
const redact = (text: string) => redactEnvironmentValues(text, secrets);
return { id, selectionRanges: true, selectionChunks: true, source: { id: sourceId, kind: source.kind, name: redact(source.name) }, name: redact(source.name),
@@ -586,7 +590,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
};
const transferDeps: TransferDeps = {
assertOwner: scope.assert,
- validateItems(items) {
+ async validateItems(items) {
// Repaired manifests can reveal credentials that were unavailable at preview time.
for (const value of Object.values(selectedImportRedactions(items))) {
if (knownValues.has(value)) continue;
@@ -595,7 +599,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
}
// Capturing lazily selected resources may grow even a rejected selection.
const cached = previews.get(selection.previewId);
- if (cached?.value === snapshot) retainPreview(selection.previewId, cached);
+ if (cached?.value === snapshot) await retainPreview(selection.previewId, cached, scope.assert, true);
for (const item of items.filter(item => item.view.category === 'skills' && !item.captureIssue)) {
try {
const slug = skillSlug(item);
diff --git a/apps/desktop/src/main/bot-import/snapshotJson.ts b/apps/desktop/src/main/bot-import/snapshotJson.ts
new file mode 100644
index 0000000000..b1dd4912a7
--- /dev/null
+++ b/apps/desktop/src/main/bot-import/snapshotJson.ts
@@ -0,0 +1,78 @@
+import type { ImportItem } from './types.js';
+
+/** Walk JSON without copying an item graph or building a snapshot-sized string.
+ * Native JSON.stringify still owns escaping/scalar semantics. Only the known
+ * file-byte fields are replaced, exactly as in the compact checkpoint format. */
+function* snapshotJson(items: ImportItem[], encodeBytes: (bytes: Buffer) => unknown): Generator<string> {
+ const ancestors = new Set<object>();
+ function* quoted(value: string): Generator<string> {
+ yield '"';
+ for (let start = 0; start < value.length;) {
+ let end = Math.min(start + 16 * 1024, value.length);
+ // Splitting a surrogate pair would change native JSON/UTF-8 semantics.
+ if (end < value.length && /[\uD800-\uDBFF]/.test(value[end - 1]!) && /[\uDC00-\uDFFF]/.test(value[end]!)) end--;
+ yield JSON.stringify(value.slice(start, end)).slice(1, -1);
+ start = end;
+ }
+ yield '"';
+ }
+ const omitted = (value: unknown) => value === undefined || typeof value === 'function' || typeof value === 'symbol';
+ const jsonValue = (value: unknown, key: string): unknown =>
+ value && typeof value === 'object' && 'toJSON' in value && typeof value.toJSON === 'function' ? value.toJSON(key) : value;
+ type Context = 'items' | 'item' | 'files' | 'file' | undefined;
+ function* visit(input: unknown, context: Context, key = '', normalized = false): Generator<string> {
+ const value = normalized ? input : jsonValue(input, key);
+ if (typeof value === 'string') { yield* quoted(value); return; }
+ if (!value || typeof value !== 'object') { yield omitted(value) ? 'null' : JSON.stringify(value); return; }
+ if (ancestors.has(value)) throw new TypeError('Circular snapshot metadata');
+ ancestors.add(value);
+ try {
+ if (Array.isArray(value)) {
+ yield '[';
+ for (let index = 0; index < value.length; index++) {
+ if (index) yield ',';
+ yield* visit(value[index], context === 'items' ? 'item' : context === 'files' ? 'file' : undefined, String(index));
+ }
+ yield ']';
+ } else {
+ yield '{';
+ let first = true;
+ // Avoid Object.entries/map materializing another wide metadata array.
+ for (const field in value) {
+ if (!Object.hasOwn(value, field)) continue;
+ let child = (value as Record<string, unknown>)[field];
+ if (context === 'file' && field === 'bytes') child = encodeBytes(child as Buffer);
+ child = jsonValue(child, field);
+ if (omitted(child)) continue;
+ if (!first) yield ',';
+ first = false;
+ yield* quoted(field); yield ':';
+ yield* visit(child, context === 'item' && field === 'files' ? 'files'
+ : context === 'item' && field === 'asset' ? 'file' : undefined, field, true);
+ }
+ yield '}';
+ }
+ } finally { ancestors.delete(value); }
+ }
+ yield* visit(items, 'items');
+}
+
+/** Byte-bounded work between event-loop turns; cancellation never retains a
+ * partial preview or continues a retry under a different signed-in owner. */
+export async function visitSnapshotJson(
+ items: ImportItem[], encodeBytes: (bytes: Buffer) => unknown,
+ consume: (text: string) => void, assertOwner: () => void = () => {},
+): Promise<void> {
+ assertOwner();
+ let bytes = 0;
+ const encode = (buffer: Buffer) => { bytes += buffer.length; return encodeBytes(buffer); };
+ for (const text of snapshotJson(items, encode)) {
+ consume(text);
+ bytes += Buffer.byteLength(text);
+ if (bytes >= 64 * 1024) {
+ await new Promise<void>(resolve => setImmediate(resolve));
+ assertOwner(); bytes = 0;
+ }
+ }
+ assertOwner();
+}
diff --git a/apps/desktop/src/main/bot-import/sources.ts b/apps/desktop/src/main/bot-import/sources.ts
index 60b7a6d2fd..b757a1a738 100644
--- a/apps/desktop/src/main/bot-import/sources.ts
+++ b/apps/desktop/src/main/bot-import/sources.ts
@@ -5,7 +5,7 @@ import JSON5 from 'json5';
import { redactEnvironmentValues } from './process.js';
import yaml from 'js-yaml';
import { parse as parseEnv } from 'dotenv';
-import { createImportBudget, fingerprint, optionalText, readImportFile, readImportTree, snapshotFingerprint, type ImportReadBudget } from './files.js';
+import { createImportBudget, fingerprint, optionalText, readImportFile, readImportTree, snapshotFingerprintAsync, type ImportReadBudget } from './files.js';
import { discoverImportSkills } from './skills.js';
import { indexAutomationDependencies, normalizeAutomation } from './sourceAutomations.js';
import { memoryFileContent } from './memoryFiles.js';
@@ -355,5 +355,5 @@ export async function inspectImportSource(source: ImportSource, deps: SourceRead
}
markImportEnvironmentChoices(items);
const resolved = resolveImportEnvironmentDependencies(items, items.filter(item => item.view.selected));
- return { source, items: resolved, ...(avatarImageBase64 ? { avatarImageBase64 } : {}), fingerprint: snapshotFingerprint(resolved) };
+ return { source, items: resolved, ...(avatarImageBase64 ? { avatarImageBase64 } : {}), fingerprint: await snapshotFingerprintAsync(resolved) };
}
diff --git a/apps/desktop/src/main/bot-import/transfer.ts b/apps/desktop/src/main/bot-import/transfer.ts
index 31cd0affa5..d30b836868 100644
--- a/apps/desktop/src/main/bot-import/transfer.ts
+++ b/apps/desktop/src/main/bot-import/transfer.ts
@@ -39,7 +39,7 @@ export interface TransferDeps {
/** Return serialized UTF-8 bytes when available, avoiding a second full serialization. */
saveReceipt(receipt: ImportReceipt): Promise<number | void>;
createCompanion(botId: string, selection: CompanionImportSelection): Promise<void>;
- validateItems?(items: ImportItem[]): void;
+ validateItems?(items: ImportItem[]): void | Promise<void>;
importItem(botId: string, item: ImportItem, snapshot: ImportSnapshot): Promise<void>;
saveEnvironment(botId: string, items: ImportItem[]): Promise<void>;
saveCheckpoint(botId: string, items: ImportItem[]): Promise<void>;
@@ -163,7 +163,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
// before storing credentials. Acceptance still waits for the full checkpoint.
if (!receipt.checkpointSaved || items.some(item => item.captureIssue)) {
const budget = createImportBudget();
- reserveSnapshotItems(snapshot.items, budget);
+ await reserveSnapshotItems(snapshot.items, budget, deps.assertOwner);
for (const item of items) {
if (item.captureIssue && item.sourceDirectory && item.filesComplete && !copied.has(item.view.id)) {
item.files = undefined; item.filesComplete = false;
@@ -238,7 +238,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
deps.assertOwner();
}
}
- deps.validateItems?.(items);
+ await deps.validateItems?.(items);
await save();
await deps.saveCheckpoint(botId, items);
deps.assertOwner();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillQueryIndex.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillQueryIndex.test.ts
index d493846776..9c039ced48 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botSkillQueryIndex.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillQueryIndex.test.ts
@@ -152,3 +152,22 @@ it('externally sorts 100,000 entries before enumeration completes and keeps the
expect(await fs.readFile(catalog, 'utf8')).toBe(text);
expect(await fs.readdir(directory)).toEqual(['query-catalog.jsonl']);
}, 30_000);
+
+it('keeps disabled Skill metadata discoverable without publishing read paths, then restores them on enable', async () => {
+ const file = await write('off', 'Off', 'Searchable disabled', true, 'Private disabled instructions');
+ const before = await fs.readFile(file, 'utf8');
+ const first = await listBotSkillsForSession({ callerSessionId: 's', query: 'disabled' }, deps());
+ expect(first).toMatchObject({ ok: true, skills: [{ slug: 'off', name: 'Off', description: 'Searchable disabled', enabled: false }] });
+ if (!first.ok) throw Error('Expected result');
+ expect(first.skills[0]).not.toHaveProperty('filePath');
+ expect(first.skills[0]).not.toHaveProperty('bodyStartLine');
+ expect(first.skills[0]).not.toHaveProperty('dirPath');
+ // A cached query and the full settings read keep the same disabled state.
+ expect((await query({ query: 'disabled' })).skills[0]).not.toHaveProperty('filePath');
+ expect((await listBotSkills(home, bot))[0]).toMatchObject({ enabled: false, filePath: file });
+ expect(await fs.readFile(file, 'utf8')).toBe(before);
+ await fs.mkdir(botSkillsDir(home, bot), { recursive: true });
+ await fs.rename(path.dirname(file), path.join(root(), 'skills/off'));
+ await vi.waitFor(async () => expect((await query({ query: 'disabled' })).skills[0])
+ .toMatchObject({ filePath: path.join(root(), 'skills/off/SKILL.md'), bodyStartLine: 5 }));
+});
diff --git a/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts b/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts
index e6f696cf1c..4d97728f93 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts
@@ -10,15 +10,15 @@ import {
/** A startup/output byte budget, never a limit on stored or discoverable Skills. */
export const BOT_SKILL_RUNTIME_INDEX_BYTES = 16 * 1024;
-export function botSkillRuntimeSummary(item: BotSkillSummary) {
+export function botSkillRuntimeSummary(item: BotSkillSummary):
+ Pick<BotSkillSummary, 'slug' | 'name' | 'description' | 'updatedAt' | 'enabled'>
+ & Partial<Pick<BotSkillSummary, 'filePath' | 'bodyStartLine'>> {
return {
slug: item.slug,
name: item.name.slice(0, BOT_SKILL_MAX_NAME_CHARS),
description: item.description.slice(0, BOT_SKILL_MAX_DESCRIPTION_CHARS),
updatedAt: item.updatedAt.slice(0, 64),
- filePath: item.filePath,
- bodyStartLine: item.bodyStartLine,
- ...(item.enabled === false ? { enabled: false } : {}),
+ ...(item.enabled === false ? { enabled: false as const } : { filePath: item.filePath, bodyStartLine: item.bodyStartLine }),
};
}