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。

test: fix goal command fixtures and isolate library archive helper IO

xd-bobo46edb4e5f71c
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
index 814617399e..66e220b4c0 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
@@ -22,8 +22,8 @@ import {
import { createHash } from 'node:crypto';
import { crc32 } from 'node:zlib';
import { LibraryBindingStore, relocateLibraryMetaOwner } from '../libraryBinding.js';
-import { LibraryVault } from '../libraryVault.js';
-import { initCustomLibraryTree, openExistingCustomLibrary } from '../libraryDirFd.js';
+import { LibraryVault, type LibraryVaultDeps } from '../libraryVault.js';
+import { initCustomLibraryTree, openExistingCustomLibrary, parseExistingStdout } from '../libraryDirFd.js';
import { createLibraryDbCore, type SqliteDatabaseConstructor } from '../libraryDbCore.js';
import { LibrarySqlService } from '../librarySqlService.js';
import { GhostManager } from '../GhostManager.js';
@@ -361,7 +361,8 @@ describe('GhostLibrarySlot', () => {
}
async function seedSourceDatabase(value: string, instanceId = GHOST_ID): Promise<void> {
- expect(await slot.handleLibraryRequest(instanceId, { op: 'db.open', dbPath: 'library.sqlite' }))
+ const opened = await slot.handleLibraryRequest(instanceId, { op: 'db.open', dbPath: 'library.sqlite' });
+ expect(opened, JSON.stringify(opened))
.toMatchObject({ ok: true, op: 'db.open' });
expect(await slot.handleLibraryRequest(instanceId, {
op: 'db.exec', dbPath: 'library.sqlite', sql: 'CREATE TABLE source_state (value TEXT)',
@@ -374,7 +375,48 @@ describe('GhostLibrarySlot', () => {
})).toMatchObject({ ok: true, op: 'db.exec', rows: [{ value }] });
}
+ function useInProcessCustomTreeForArchiveTests(): void {
+ // These cases exercise real SQLite data, binding relocation and rollback.
+ // Repeated PowerShell startup/Add-Type under parallel Windows CI can exceed
+ // the native helper's 15s deadline before any archive assertion runs. Keep
+ // fixture metadata on disk, but inject helper IO here only; the custom-root
+ // swap/held-fd cases below and libraryVault.test.ts retain the real helpers.
+ const readIfPresent = async (file: string): Promise<string | null> => {
+ try {
+ return await fs.promises.readFile(file, 'utf8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+ };
+ createVault.mockImplementation((deps: LibraryVaultDeps) => {
+ const metaDir = path.join(deps.rootDir(), '.cindy-library');
+ const metaFile = path.join(metaDir, 'meta.json');
+ return new LibraryVault({
+ ...deps,
+ openExistingCustom: async () => {
+ const meta = await readIfPresent(metaFile);
+ if (meta === null) return { ok: false, code: 'MISSING' };
+ const usage = await readIfPresent(path.join(metaDir, 'usage.json'));
+ return parseExistingStdout(`OK\n${meta}\n${usage ?? ''}`);
+ },
+ initCustomTree: async ({ metaJson }) => {
+ await fs.promises.mkdir(path.join(metaDir, 'tmp'), { recursive: true });
+ await fs.promises.mkdir(path.join(metaDir, 'backups'), { recursive: true });
+ try {
+ await fs.promises.writeFile(metaFile, metaJson, { flag: 'wx' });
+ return { ok: true, createdMeta: true };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return { ok: true, createdMeta: false };
+ throw error;
+ }
+ },
+ });
+ });
+ }
+
it.each(['default', 'custom'] as const)('source archive wrapper isolates the real SQLite %s Library from a replacement source', async (location) => {
+ useInProcessCustomTreeForArchiveTests();
if (location === 'custom') {
expect((await bindingStore.setBinding(GHOST_ID, candidate)).ok).toBe(true);
}
@@ -406,6 +448,7 @@ describe('GhostLibrarySlot', () => {
});
it.each(['default', 'custom'] as const)('source archive wrapper restores the real SQLite %s Library on inverse after failure', async (location) => {
+ useInProcessCustomTreeForArchiveTests();
if (location === 'custom') {
expect((await bindingStore.setBinding(GHOST_ID, candidate)).ok).toBe(true);
}
@@ -441,6 +484,7 @@ describe('GhostLibrarySlot', () => {
});
it.each(['default', 'custom'] as const)('delayed session creation does not block real Manager %s source archive rollback', async (location) => {
+ useInProcessCustomTreeForArchiveTests();
const manager = new GhostManager({
getRootDir: () => path.join(tmp, 'ghosts'),
onArchiveSourceState: relocateLibraryState,
diff --git a/apps/mobile/src/__tests__/mobileGoalCommands.test.ts b/apps/mobile/src/__tests__/mobileGoalCommands.test.ts
index fc7d3df4c7..9ecd3c4f05 100644
--- a/apps/mobile/src/__tests__/mobileGoalCommands.test.ts
+++ b/apps/mobile/src/__tests__/mobileGoalCommands.test.ts
@@ -25,13 +25,18 @@ const newCreate = callback('app/sessions/new.tsx', 'create');
const goalCreate = callback('app/sessions/new.tsx', 'createGoalSession');
const sessionSource = ts.createSourceFile('session.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let sendSource = '';
+let readRouteParamSource = '';
function findSend(node: ts.Node) {
if (ts.isFunctionDeclaration(node) && node.name?.text === 'send') sendSource = node.getText(sessionSource);
+ if (ts.isFunctionDeclaration(node) && node.name?.text === 'readRouteParam') readRouteParamSource = node.getText(sessionSource);
ts.forEachChild(node, findSend);
}
findSend(sessionSource);
if (!sendSource) throw new Error('Missing complete SessionScreen.send entry');
-const compiledExisting = ts.transpileModule(`${sendSource}\nreturn send;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+if (!readRouteParamSource) throw new Error('Missing SessionScreen.readRouteParam helper');
+// Keep page-local route parsing with send; missing closure dependencies would
+// otherwise be caught by send and surface only as a misleading outbox failure.
+const compiledExisting = ts.transpileModule(`${readRouteParamSource}\n${sendSource}\nreturn send;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
function newHarness(text = '/goal target') {
const noop = vi.fn();
@@ -73,6 +78,7 @@ function existingHarness(args = 'target') {
setError: vi.fn(), setGoalError: vi.fn(), t: (key: string) => key,
isRemoteSessionMissing: () => false, readSessionRowNow: () => session, goalBusy: false, setGoalBusy: vi.fn(),
executeMobileGoalCommand, sessionId: 'existing-task', deviceId: 'host', deviceIdRef: { current: 'host' },
+ params: {} as Record<string, string | string[] | undefined>,
outboxSessionAliveRef: { current: 'existing-task' }, getMobileAuthOwner: () => ({}), isMobileAuthOwnerCurrent: () => true,
maker: { goal: { set: vi.fn(async () => {}), clear: vi.fn(async () => {}), getStatus: vi.fn(async () => ({ status: 'active', objective: 'target' })) } },
remoteSessionStore: { setGoalStatus: vi.fn(), acquireSessionMessageWork: vi.fn(() => ({ release })), getSessionDeviceId: () => 'host' }, setContextSheetView: vi.fn(), setContextSheetOpen: vi.fn(),
@@ -213,6 +219,7 @@ describe('existing task /goal send boundary', () => {
h.bindings.attachmentsRef.current = [];
h.bindings.composerDocumentRef.current = textComposerDocument('ordinary follow-up');
await h.run();
+ expect(h.bindings.setError).toHaveBeenLastCalledWith(null);
expect(h.bindings.mobileDurableOutbox.add).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
item: expect.objectContaining({ sessionId: 'existing-task', text: 'ordinary follow-up' }),
}));
@@ -220,4 +227,22 @@ describe('existing task /goal send boundary', () => {
expect(h.bindings.sending).toBe(false);
expect(h.release).toHaveBeenCalledTimes(2);
});
+
+ it.each([false, true])('preserves the bot resource on a follow-up after Goal, array route params=%s', async arrayParams => {
+ const h = existingHarness();
+ const routeValue = (value: string) => arrayParams ? [value] : value;
+ h.bindings.params = {
+ resourceKind: routeValue('bot'),
+ resourceCollectionId: routeValue('companions'),
+ resourceId: routeValue('bot-1'),
+ };
+ await h.run();
+ h.bindings.composerDocumentRef.current = textComposerDocument('ordinary follow-up');
+ await h.run();
+ expect(h.bindings.setError).toHaveBeenLastCalledWith(null);
+ expect(h.bindings.mobileDurableOutbox.add).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
+ item: expect.objectContaining({ sessionId: 'existing-task', text: 'ordinary follow-up' }),
+ resourceRef: { collectionId: 'companions', kind: 'bot', id: 'bot-1' },
+ }));
+ });
});