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。

merge: sync published plugin task snapshot fixes

Dash2e96c90534c2
diff --cc apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts
index 0000000000,6dc45eda87..1341b256a5
mode 000000,100644..100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskSnapshot.test.ts
@@@ -1,0 -1,149 +1,149 @@@
+ import { readFileSync } from 'node:fs';
+ import { mkdtemp, mkdir, realpath, rm, symlink, unlink } from 'node:fs/promises';
+ import os from 'node:os';
+ import path from 'node:path';
+ import { expect, it, vi } from 'vitest';
+ import ts from 'typescript';
-import { PluginTaskError } from '../pluginTaskService.js';
++import { PluginTaskError, readPluginTaskPlanReceipt } from '../pluginTaskService.js';
+ import type { PluginTaskRoute } from '../../../shared/pluginTasks.js';
+ import { resolvePluginWorkerDirectory } from '../pluginWorkerDirectory.js';
+
+ const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
+ function compile(text: string, deps: Record<string, unknown>) {
+ return new Function(...Object.keys(deps), ts.transpileModule(text, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText)(...Object.values(deps));
+ }
+ function handler(kind: string, next: string, deps: Record<string, unknown>) {
+ const branch = source.slice(source.indexOf(` case '${kind}':`), source.indexOf(` case '${next}':`));
+ return compile(`return async function(pluginId,request){switch(request.kind){${branch}}}`, deps);
+ }
+
+ it('freezes the directory returned by admission without mutating the caller plan', async () => {
+ const epoch = {};
+ const save = vi.fn();
+ const plan = { concurrency: 1, items: [{ label: 'sample', workingDir: '/root/link', route: {} }] };
+ const run = handler('setTeamPlan', 'releaseWorker', {
+ PluginTaskError, withSendToSessionLock: async (_: string, fn: () => unknown) => fn(),
+ getCurrentDbClientSnapshot: () => epoch,
+ service: { get: async () => ({ revision: 1, workingDir: '/root' }), setTeamPlan: save },
+ readGhostErrandConfig: () => ({ workingDir: '/root' }), isPluginTaskAuthorized: () => true,
+ isGhostPickedDir: () => false, resolvePluginWorkerDirectory: async () => '/root/original',
+ });
+ await run('plugin', { kind: 'setTeamPlan', taskId: 'task', plan });
+ expect(save).toHaveBeenCalledWith('plugin', 'task', {
+ ...plan, items: [{ ...plan.items[0], workingDir: '/root/original' }],
+ });
+ expect(plan.items[0].workingDir).toBe('/root/link');
+ });
+
+ it('retargeting a real symlink cannot change the stored plan directory', async () => {
+ const root = await realpath(await mkdtemp(path.join(os.tmpdir(), 'plugin-plan-target-')));
+ try {
+ const original = path.join(root, 'original'), other = path.join(root, 'other'), link = path.join(root, 'link');
+ await mkdir(original); await mkdir(other); await symlink(original, link, 'junction');
+ const epoch = {}, save = vi.fn();
+ const plan = { concurrency: 1, items: [{ label: 'sample', workingDir: link, route: {} }] };
+ const run = handler('setTeamPlan', 'releaseWorker', {
+ PluginTaskError, withSendToSessionLock: async (_: string, fn: () => unknown) => fn(),
+ getCurrentDbClientSnapshot: () => epoch,
+ service: { get: async () => ({ revision: 1, workingDir: root }), setTeamPlan: save },
+ readGhostErrandConfig: () => ({ workingDir: root }), isPluginTaskAuthorized: () => true,
+ isGhostPickedDir: () => false, resolvePluginWorkerDirectory,
+ });
+ await run('plugin', { kind: 'setTeamPlan', taskId: 'task', plan });
+ const stored = save.mock.calls[0][2].items[0].workingDir;
+ await unlink(link); await symlink(other, link, 'junction');
+ const resolve = (requested: string) => resolvePluginWorkerDirectory({ requested, leadDirectory: root, isPickedDirectory: () => false, assertCurrent: () => {} });
+ expect(await resolve(stored)).toBe(original);
+ expect(await resolve(link)).toBe(other);
+ } finally { await rm(root, { recursive: true, force: true }); }
+ });
+
+ it.each(['provider', 'receipt', 'directory', 'creator'])('keeps default-route configuration current through %s awaits', async phase => {
+ const resolveStart = source.indexOf(' const resolveRoute = async');
+ const resolveSource = source.slice(resolveStart, source.indexOf(' const readExecution', resolveStart));
+ const createStart = source.indexOf(' createSession: async');
+ const createSource = source.slice(createStart, source.indexOf(' readSession:', createStart)).trim().replace(/,$/, '');
+ for (const field of ['agentKind', 'model', 'providerId', 'effort', 'fastMode'] as const) {
+ const epoch = {};
+ const initial: PluginTaskRoute = { agentKind: 'codex', model: 'model', providerId: 'one', effort: 'high', fastMode: false };
+ const cfg = { ...initial, workingDir: '/root', permissionMode: 'plan' };
+ const change = () => {
+ if (field === 'agentKind') cfg.agentKind = 'pi';
+ if (field === 'model') cfg.model = 'other';
+ if (field === 'providerId') cfg.providerId = 'two';
+ if (field === 'effort') cfg.effort = 'low';
+ if (field === 'fastMode') cfg.fastMode = true;
+ };
+ let lookups = 0;
+ const create = vi.fn(async ({ shouldContinue }: { shouldContinue: () => boolean }) => {
+ if (phase === 'creator') change();
+ if (!shouldContinue()) throw new PluginTaskError('PERMISSION_DENIED', 'changed');
+ });
+ const api = compile(`${resolveSource}\nreturn {resolveRoute, create: ({${createSource}}).createSession};`, {
+ PluginTaskError, snapshot: epoch, assertPlugin: vi.fn(),
+ readGhostErrandConfig: () => ({ ...cfg }), getWorkerDefaultsFromNewMaker: () => ({}),
+ getDesktopProviderService: () => ({ listProviders: async () => {
+ if (++lookups === 1 && phase === 'provider') change();
+ return ['one', 'two'].map(id => ({ id, connected: true }));
+ } }), getActiveCatalog: () => ({}),
+ findCatalogModel: () => ({ efforts: ['high', 'low'], supportsFastMode: true }),
+ isModelSelectableForNewRoute: () => true,
+ routeUnavailable: () => { throw Error('unavailable'); },
+ resolvePluginWorkerDirectory: async () => { if (phase === 'directory') change(); return '/root'; },
+ createGhostErrandSession: create, clampErrandPermissionMode: (value: string) => value,
+ getCurrentDbClientSnapshot: () => epoch, isPluginTaskAuthorized: () => true,
+ notifyGhostSessionEvent: vi.fn(), broadcastSessionCreated: vi.fn(),
+ });
+ const route = await api.resolveRoute('plugin');
+ if (phase === 'receipt') change();
+ await expect(api.create('plugin', 'task', 'title', route, false)).rejects.toThrow();
+ if (phase !== 'creator') expect(create).not.toHaveBeenCalled();
+ }
+ });
+
+ it('forwards the explicit route when revalidating creation', async () => {
+ const start = source.indexOf(' createSession: async');
+ const property = source.slice(start, source.indexOf(' readSession:', start)).trim().replace(/,$/, '');
+ const epoch = {};
+ const route: PluginTaskRoute = { agentKind: 'codex', providerId: 'mine', model: 'explicit', effort: 'high', fastMode: false };
+ const resolveRoute = vi.fn(async () => route);
+ const create = vi.fn();
+ const run = compile(`return ({${property}}).createSession;`, {
+ PluginTaskError, snapshot: epoch, assertPlugin: vi.fn(),
+ readGhostErrandConfig: () => ({ model: 'different-default', permissionMode: 'plan' }),
+ resolveRoute, createGhostErrandSession: create, clampErrandPermissionMode: (x: string) => x,
+ getCurrentDbClientSnapshot: () => epoch, isPluginTaskAuthorized: () => true,
+ notifyGhostSessionEvent: vi.fn(), broadcastSessionCreated: vi.fn(),
+ });
+ await run('plugin', 'task', 'title', route, true, route);
+ expect(resolveRoute).toHaveBeenCalledWith('plugin', route);
+ expect(create).toHaveBeenCalledOnce();
+ });
+
+ it.each(['pending', 'empty', 'incomplete', 'error'])('restores Lead input before reporting team state: %s', async state => {
+ let restored = false;
+ let pending: string[] = [];
+ const query = { from: () => query, where: () => query, limit: async () => [{ totalTokenUsage: 0 }] };
+ const epoch = { client: { drizzle: { select: () => query } } };
+ const workspace = vi.fn(async () => ({ ok: true, workers: [] }));
+ const run = handler('getTeam', 'create', {
- PluginTaskError, getCurrentDbClientSnapshot: () => epoch, service: { get: async () => ({}) },
++ PluginTaskError, readPluginTaskPlanReceipt, getCurrentDbClientSnapshot: () => epoch, service: { get: async () => ({}) },
+ getOrcaWorkspaceInfoReadOnly: workspace, createOrcaDiagnosticsDeps: () => ({}),
+ maker: { getSession: () => undefined }, sessions: {}, eq: vi.fn(),
+ createPluginTaskStore: () => ({ get: async () => ({ payload: '{}' }) }),
+ readCollaborationSettings: () => ({ workerHardLimit: 4 }),
+ inputCoordinator: {
+ ensureQueueRestored: async () => {
+ if (state === 'error') throw Error('queue unavailable');
+ restored = state !== 'incomplete'; pending = state === 'pending' ? ['old input'] : [];
+ },
+ isQueueRestored: () => restored,
+ getQueueControlSnapshot: () => ({ pendingQueue: pending }),
+ },
+ });
+ const result = run('plugin', { kind: 'getTeam', taskId: 'task' });
+ if (state === 'incomplete' || state === 'error') await expect(result).rejects.toThrow();
+ else expect((await result).leadWorking).toBe(state === 'pending');
+ });