Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): protect Settings turns and continuation recovery notices
zqchriscadc66992c9c
diff --git a/apps/desktop/src/main/im/shared/runtimeRecoveryNotice.ts b/apps/desktop/src/main/im/shared/runtimeRecoveryNotice.tsindex 88fc640296..dc541bccad 100644--- a/apps/desktop/src/main/im/shared/runtimeRecoveryNotice.ts+++ b/apps/desktop/src/main/im/shared/runtimeRecoveryNotice.ts@@ -3,7 +3,12 @@ import { t } from '../../i18n';// One actual channel owner per runtime. A product terminal does not unsubscribe:// retirement can fail afterwards. Runtime termination/replacement releases it.-const owners = new WeakMap<Session, () => void>();+const owners = new WeakMap<Session, { cleanup(): void; generations: Set<number> }>();++/** Only Host continuation dispatch may extend the existing logical channel turn. */+export function advanceRuntimeRecoveryNotice(session: Session): void {+ owners.get(session)?.generations.add(session.getTurnGeneration());+}export function bindRuntimeRecoveryNotice(session: Session,@@ -11,16 +16,16 @@ export function bindRuntimeRecoveryNotice(log: { warn(message: string): void },): void {if (session.agentKind !== 'pi') return;- owners.get(session)?.();- const generation = session.getTurnGeneration();+ owners.get(session)?.cleanup();+ const generations = new Set([session.getTurnGeneration()]);const cleanup = (): void => {offEvent();offStatus();- if (owners.get(session) === cleanup) owners.delete(session);+ if (owners.get(session)?.cleanup === cleanup) owners.delete(session);};const offEvent = session.onEvent((event) => {if (!event.runtimeRecovery || event.sessionInstanceId !== session.instanceId- || event.sessionTurnGeneration !== generation || event.type !== 'text') return;+ || !generations.has(event.sessionTurnGeneration ?? -1) || event.type !== 'text') return;cleanup(); // Claim once before invoking any asynchronous channel operation.try {// No model consumes this post-terminal notice. Keep the machine receipt@@ -35,5 +40,5 @@ export function bindRuntimeRecoveryNotice(const offStatus = session.onStatusChange((status) => {if (status === 'closed' || status === 'error') cleanup();});- owners.set(session, cleanup);+ owners.set(session, { cleanup, generations });}diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.tsindex 1b05caefc9..19558afe12 100644--- a/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/pi-package-runtime-invalidation.test.ts@@ -1,3 +1,6 @@+import { bindRuntimeRecoveryNotice, advanceRuntimeRecoveryNotice } from '../../im/shared/runtimeRecoveryNotice.js';+import { readFileSync } from 'node:fs';+import { ScriptTarget, transpileModule } from 'typescript';import { Session, type Maker, type AgentEvent, type AgentSessionHandle } from '@cindy/maker-core';import { describe, expect, it, vi } from 'vitest';@@ -63,6 +66,72 @@ function live(id: string, closeGate: Promise<void> = Promise.resolve()) {}describe('Pi package runtime invalidation', () => {+ it.each([false, true])('delivers retirement recovery after Host continuation (refresh=%s)', async (refresh) => {+ const runtime = live('continued');+ const notices = vi.fn(async () => true);+ await runtime.instance.send('IM input', { beforeProviderStart: () => bindRuntimeRecoveryNotice(runtime.instance, notices, { warn() {} }) });+ const firstGeneration = runtime.instance.getTurnGeneration();+ runtime.finish('first segment');+ await vi.waitFor(() => expect(runtime.seen.some(event => event.type === 'done')).toBe(true));+ await runtime.instance.send('Host continuation', {+ onDispatching: () => { if (refresh) advanceRuntimeRecoveryNotice(runtime.instance); },+ });+ expect(runtime.instance.getTurnGeneration()).toBeGreaterThan(firstGeneration);+ runtime.close.mockRejectedValueOnce(new Error('exit unconfirmed'));+ await runtime.instance.closeAfterCurrentTurn({ failureEvent: () => ({+ type: 'text', source: 'pi', data: { isFinal: true, text: 'internal receipt' },+ }) });+ runtime.finish('final result');+ await vi.waitFor(() => expect(runtime.instance.getStatus()).toBe('error'));+ expect(notices).toHaveBeenCalledTimes(refresh ? 1 : 0);+ expect(runtime.handle.send).toHaveBeenCalledTimes(2);+ await runtime.instance.close();+ });++ it.each([+ ['install', undefined, true], ['update', undefined, true],+ ['set-enabled', true, true], ['set-enabled', false, false], ['remove', undefined, false],+ ] as const)('Settings %s enabled=%s retains only positive in-flight work', async (action, enabled, deferredClose) => {+ const busy = live('settings-busy');+ const idle = live('settings-idle');+ const maker: InvalidationMaker = {+ advanceLocalPiPackageRuntimeGeneration: vi.fn(),+ listActiveSessions: () => [busy.instance, idle.instance],+ getSessionMeta: vi.fn(async (id: string) => ({ id, agentKind: 'pi' as const, workDir: '/repo', model: 'm', title: id, createdAt: 1, updatedAt: 1 })),+ closeSessionIfCurrent: async (instance, _reason, opts) => opts?.afterCurrentTurn+ ? instance.closeAfterCurrentTurn(opts) : (await instance.close(), 'closed'),+ };+ const source = readFileSync(new URL('../../maker-ipc/register.ts', import.meta.url), 'utf8');+ const start = source.indexOf('ipcMain.handle(MAKER_INVOKE.PI_PACKAGES_MUTATE');+ const block = source.slice(start, source.indexOf('\n ipcMain.handle(', start + 1));+ let handler!: (event: unknown, raw: unknown) => Promise<unknown>;+ const dependencies = {+ ipcMain: { handle: (_: unknown, fn: typeof handler) => { handler = fn; } },+ MAKER_INVOKE: { PI_PACKAGES_MUTATE: 'mutate' }, maker,+ assertTrustedAppRendererEvent() {}, requireObject: (value: unknown) => value,+ requireEnum: (value: unknown) => value, throwIpcError: () => { throw new Error('bad input'); },+ runPiPackageMutationIpcBoundary: (run: () => Promise<unknown>) => run(),+ piPackageMutationNeedsGrant: () => false,+ mutatePiPackage: async (_: unknown, __: unknown, hooks: { onRuntimeInvalidationPublished(): Promise<void> }) => {+ await hooks.onRuntimeInvalidationPublished(); return { ok: true };+ },+ invalidateLocalPiPackageRuntimes, t: () => 'Restart Cindy', log: { warn() {} },+ };+ new Function(...Object.keys(dependencies), transpileModule(block, {+ compilerOptions: { target: ScriptTarget.ES2022 },+ }).outputText)(...Object.values(dependencies));+ await busy.instance.send('keep working');+ await handler({}, { action, enabled, source: 'npm:example' });+ expect(idle.close).toHaveBeenCalledOnce();+ expect(busy.close).toHaveBeenCalledTimes(deferredClose ? 0 : 1);+ if (deferredClose) {+ busy.finish('result delivered');+ await vi.waitFor(() => expect(busy.instance.getStatus()).toBe('closed'));+ expect(busy.seen.some(event => event.type === 'done')).toBe(true);+ }+ expect(busy.handle.send).toHaveBeenCalledOnce();+ });+it.each(['success', 'failure', 'close', 'timeout'] as const)('retains a finished caller through convergence delivery: %s', async (mode) => {const fails = mode !== 'success';const caller = live('caller');diff --git a/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts b/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.tsindex 0b33d68a11..1ee72cab9d 100644--- a/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts+++ b/apps/desktop/src/main/maker-host/pi-package-runtime-invalidation.ts@@ -152,7 +152,8 @@ export async function settleLocalPiPackageRuntimeSnapshot(export async function invalidateLocalPiPackageRuntimes(maker: InvalidationMaker,+ opts?: { afterCurrentTurn?: boolean; failureEvent?: () => AgentEvent },): Promise<PiPackageRuntimeInvalidationResult> {const snapshot = await captureLocalPiPackageRuntimeInvalidationSnapshot(maker);- return invalidateLocalPiPackageRuntimeSnapshot(maker, snapshot);+ return invalidateLocalPiPackageRuntimeSnapshot(maker, snapshot, opts);}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/piPackageEnableConfirmationIpc.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/piPackageEnableConfirmationIpc.test.tsindex d27e9d76cb..97d11f6004 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/piPackageEnableConfirmationIpc.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/piPackageEnableConfirmationIpc.test.ts@@ -59,7 +59,7 @@ describe('Pi package Settings authorization IPC contract', () => {const handler = mutationHandlerSource();expect(handler).toContain('await invalidateRuntimes();');expect(handler).toContain('piPackageMutationMayHaveChangedState(error)');- expect(handler).not.toContain("request.action === 'remove'");+ // Positive versus revoking mutations run through real Session behavior tests.});it('returns partial convergence without rewriting native mutation success', () => {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 43e0877998..8a32afbe35 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,3 +1,4 @@+import { advanceRuntimeRecoveryNotice } from '../im/shared/runtimeRecoveryNotice.js';import { registerPluginListHandler } from './pluginListHandler.js';import { initializeBotAuthorizationHost } from './botAuthorizationHost.js';import { resolveBotAuthorizationDelivery, buildBotAuthorizationContinuation, commitBotAuthorizationInput, type BotAuthorizationInputGuard, getBotAuthorizationService } from './botAuthorizationService.js';@@ -4130,6 +4131,7 @@ async function handleSilentStopTurnEnd({ type: 'user', content: SILENT_STOP_RESUME_PROMPT },{origin: turnOrigin,+ onDispatching: () => advanceRuntimeRecoveryNotice(session),onAccepted: async () => {await createDbMessage(session.id, {clientId,@@ -5856,7 +5858,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (runtimesInvalidated && phase === 'commit') return;runtimesInvalidated = true;try {- const invalidation = await invalidateLocalPiPackageRuntimes(maker);+ const invalidation = await invalidateLocalPiPackageRuntimes(maker, {+ afterCurrentTurn: request.action !== 'remove'+ && !(request.action === 'set-enabled' && request.enabled === false),+ failureEvent: () => ({+ type: 'text', source: 'pi',+ data: { isFinal: true, text: t('settings.piPackages.failure.runtimeRetirementFailed') },+ }),+ });if (invalidation.failedSessionIds.length > 0) {runtimeConvergencePartial = true;log.warn('Pi package changed but some local runtimes did not close', {