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(tasks): scope capability refresh admission to bot chats (#5177)

Chris Zhang70b394fd1caf
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index a52fd21c88..9d80811a46 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -4454,6 +4454,40 @@ describe('Bot Session task end-to-end runtime', () => {
} finally { runtime.dispose(); }
});
+ it.each(['done', 'error'] as const)('continues after %s only once runtime stop is confirmed', async outcome => {
+ await seedPair();
+ let execution = { instanceId: 'native-terminal-test', generation: 1 };
+ const runtime = createDelegationRuntime({ taskControl: true, readSessionExecution: () => execution });
+ try {
+ const task = await runtime.delegation.startSessionTask({ callerSessionId: 'session-1', objective: 'Finish the requested work.' });
+ if (!task.ok) throw new Error('missing task');
+ const previous = { ...execution };
+ // A terminal receipt can precede native/Host tail settlement. It alone
+ // must never grant permission to start another execution.
+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome, execution,
+ resultText: outcome === 'done' ? 'Completed.' : undefined,
+ error: outcome === 'error' ? 'Provider failed.' : undefined,
+ pendingInputClientIds: [], hadPendingInputAtTerminal: false });
+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({
+ task: { status: outcome === 'done' ? 'completed' : 'failed', control: { state: 'terminal', stop_status: 'unconfirmed' } },
+ });
+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', mode: 'queue', text: 'Continue safely.' }))
+ .toMatchObject({ ok: false, errorCode: 'STOP_UNCONFIRMED' });
+ await runtime.settleChild(task.childSessionId, 'Native tail settled.', previous);
+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({
+ task: { control: { stop_status: 'stopped' } },
+ });
+ execution = { ...execution, generation: 2 };
+ expect(await runtime.delegation.messageSessionTask('session-1', task.delegationId, { kind: 'message', mode: 'queue', text: 'Continue safely.' }))
+ .toMatchObject({ ok: true, childSessionId: task.childSessionId, resumed: true });
+ await runtime.delegation.settleSession({ childSessionId: task.childSessionId, outcome, execution: previous,
+ resultText: 'Late old result.', error: 'Late old failure.' });
+ expect(await runtime.delegation.getSessionTask('session-1', task.delegationId)).toMatchObject({ task: { status: 'running' } });
+ expect(runtime.started.filter(turn => turn.sessionId === task.childSessionId)).toHaveLength(2);
+ expect(runtime.abortSession).not.toHaveBeenCalled();
+ } finally { runtime.dispose(); }
+ });
+
it('collects artifacts using only inputs accepted in the reopened run', async () => {
await seedPair();
let execution = { instanceId: 'native', generation: 1 };
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botCompactContinuity.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botCompactContinuity.test.ts
index 487953d43f..b24cf81064 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botCompactContinuity.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botCompactContinuity.test.ts
@@ -102,7 +102,8 @@ describe('Hermes capability epoch', () => {
});
it('只有指纹变化才复用安全的原地 runtime 重建,不换 canonical Session id', () => {
- expect(register).toContain('if (!snapshot?.runtimeEpochChanged) return');
+ expect(register).toContain('prepareBotCapabilityEpochBeforeSend(live,');
+ expect(register).toContain('return !!snapshot?.runtimeEpochChanged');
expect(register).toContain('botCompactRuntimeRefreshCoordinator.noteBoundary(live)');
expect(register).toContain('maker.getSession(expectedSession.id) === expectedSession');
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botCompactRuntimeRefresh.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botCompactRuntimeRefresh.test.ts
index dab1891a47..abdaa09a66 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botCompactRuntimeRefresh.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botCompactRuntimeRefresh.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import {
createBotCompactRuntimeRefreshCoordinator,
+ prepareBotCapabilityEpochBeforeSend,
refreshBotRuntimeAfterModelSelection,
replaceBotRuntimeAfterPreflight,
type BotCompactRuntimeSession,
@@ -198,3 +199,118 @@ describe('Bot compact runtime refresh coordinator', () => {
expect(coordinator.hasPending(oldRuntime.session.id)).toBe(false);
});
});
+
+describe('capability refresh input admission', () => {
+ const botChat = { role: 'canonical', source: 'bot', status: 'active', workingDir: '/virtual/bot' };
+
+ it.each([undefined, { ...botChat, role: 'delegation' }, { ...botChat, source: 'desktop' }])(
+ 'does not block ordinary or delegated input after mid-turn compaction (%j)', async row => {
+ const h = createSession();
+ h.setRunning(true);
+ const refresh = vi.fn(async () => 'not-bot' as const);
+ const preflight = vi.fn(async () => true);
+ const coordinator = createBotCompactRuntimeRefreshCoordinator({ hasPendingInteraction: () => false, refresh });
+ coordinator.noteBoundary(h.session);
+ const admit = () => prepareBotCapabilityEpochBeforeSend(h.session, {
+ readSession: async () => row, preflight, coordinator,
+ });
+ await expect(admit()).resolves.toBe('not-bot');
+ expect(refresh).not.toHaveBeenCalled();
+ expect(preflight).not.toHaveBeenCalled();
+ // The task's normal idle callback can retire the marker without replacing it.
+ h.setRunning(false);
+ await expect(coordinator.attempt(h.session)).resolves.toBe('not-bot');
+ expect(coordinator.hasPending(h.session.id)).toBe(false);
+ await expect(admit()).resolves.toBe('not-bot');
+ },
+ );
+
+ it.each(['canonical', 'group'])('keeps %s refresh blocked while busy and recovers at idle', async role => {
+ const h = createSession();
+ let interaction = false;
+ const refresh = vi.fn(async () => 'refreshed' as const);
+ const preflight = vi.fn(async () => true);
+ const coordinator = createBotCompactRuntimeRefreshCoordinator({ hasPendingInteraction: () => interaction, refresh });
+ const admit = () => prepareBotCapabilityEpochBeforeSend(h.session, {
+ readSession: async () => ({ ...botChat, role }), preflight, coordinator,
+ });
+ h.setRunning(true);
+ await expect(admit()).resolves.toBe('deferred');
+ h.setRunning(false);
+ interaction = true;
+ await expect(admit()).resolves.toBe('deferred');
+ interaction = false;
+ h.setBackgroundTasks(1);
+ await expect(admit()).resolves.toBe('deferred');
+ expect(refresh).not.toHaveBeenCalled();
+ h.setBackgroundTasks(0);
+ await expect(admit()).resolves.toBe('refreshed');
+ expect(refresh).toHaveBeenCalledOnce();
+ expect(preflight).toHaveBeenCalledOnce();
+ });
+
+ it('keeps failed refresh retryable without treating failure as permission to send', async () => {
+ const h = createSession();
+ const refresh = vi.fn().mockRejectedValueOnce(new Error('preflight unavailable')).mockResolvedValue('refreshed');
+ const coordinator = createBotCompactRuntimeRefreshCoordinator({ hasPendingInteraction: () => false, refresh });
+ const admit = () => prepareBotCapabilityEpochBeforeSend(h.session, {
+ readSession: async () => botChat, preflight: async () => true, coordinator,
+ });
+ await expect(admit()).resolves.toBe('deferred');
+ expect(coordinator.hasPending(h.session.id)).toBe(true);
+ await expect(admit()).resolves.toBe('refreshed');
+ expect(coordinator.hasPending(h.session.id)).toBe(false);
+ });
+
+ it('does not let a retired instance marker block the current unchanged runtime', async () => {
+ const old = createSession();
+ const current = createSession(old.session.id, 'replacement');
+ const refresh = vi.fn(async () => 'refreshed' as const);
+ const coordinator = createBotCompactRuntimeRefreshCoordinator({ hasPendingInteraction: () => false, refresh });
+ coordinator.noteBoundary(old.session);
+ await expect(prepareBotCapabilityEpochBeforeSend(current.session, {
+ readSession: async () => botChat, preflight: async () => false, coordinator,
+ })).resolves.toBe('not-bot');
+ expect(refresh).not.toHaveBeenCalled();
+ });
+
+ it.each(['same-instance', 'replacement'] as const)('preserves newer refresh work when an old callback settles (%s)', async kind => {
+ const old = createSession();
+ const next = kind === 'same-instance' ? old : createSession(old.session.id, 'replacement');
+ let finish!: (outcome: 'refreshed') => void;
+ const refresh = vi.fn().mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }))
+ .mockResolvedValue('refreshed');
+ const coordinator = createBotCompactRuntimeRefreshCoordinator({ hasPendingInteraction: () => false, refresh });
+ coordinator.noteBoundary(old.session);
+ const first = coordinator.attempt(old.session);
+ coordinator.noteBoundary(next.session);
+ const second = coordinator.attempt(next.session);
+ finish('refreshed');
+ await first;
+ await second;
+ expect(refresh).toHaveBeenCalledTimes(2);
+ expect(refresh.mock.calls[1][0]).toBe(next.session);
+ expect(coordinator.hasPending(next.session.id)).toBe(false);
+ });
+
+ it('does not clear a newer boundary unless its own refresh succeeds', async () => {
+ const h = createSession();
+ let finish!: (outcome: 'refreshed') => void;
+ const coordinator = createBotCompactRuntimeRefreshCoordinator({ hasPendingInteraction: () => false,
+ refresh: () => new Promise(resolve => { finish = resolve; }),
+ });
+ coordinator.noteBoundary(h.session);
+ const first = coordinator.attempt(h.session);
+ coordinator.noteBoundary(h.session);
+ finish('refreshed');
+ await first;
+ expect(coordinator.hasPending(h.session.id)).toBe(true);
+ // Closing cancels pending work; the old callback cannot recreate it.
+ const second = coordinator.attempt(h.session);
+ coordinator.clearForClosedSession(h.session);
+ finish('refreshed');
+ await second;
+ expect(coordinator.hasPending(h.session.id)).toBe(false);
+ await expect(coordinator.attempt(h.session)).resolves.toBe('not-bot');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/botCompactRuntimeRefresh.ts b/apps/desktop/src/main/maker-ipc/botCompactRuntimeRefresh.ts
index 236d8c7b5b..d4c0f6d58b 100644
--- a/apps/desktop/src/main/maker-ipc/botCompactRuntimeRefresh.ts
+++ b/apps/desktop/src/main/maker-ipc/botCompactRuntimeRefresh.ts
@@ -74,7 +74,10 @@ export function createBotCompactRuntimeRefreshCoordinator(
string,
{ session: BotCompactRuntimeSession; boundary: BotCompactBoundary }
>();
- const inFlight = new Map<string, Promise<BotCompactRuntimeRefreshOutcome>>();
+ const inFlight = new Map<string, {
+ entry: { session: BotCompactRuntimeSession; boundary: BotCompactBoundary };
+ operation: Promise<BotCompactRuntimeRefreshOutcome>;
+ }>();
function noteBoundary(session: BotCompactRuntimeSession): BotCompactBoundary {
const at = now();
@@ -107,14 +110,18 @@ export function createBotCompactRuntimeRefreshCoordinator(
return 'deferred';
}
const existing = inFlight.get(session.id);
- if (existing) return existing;
+ if (existing) {
+ if (existing.entry === entry) return existing.operation;
+ // A newer boundary/instance must not consume the old refresh's receipt.
+ await existing.operation;
+ return attempt(session);
+ }
- const operation = deps.refresh(session, entry.boundary)
+ const operation = (async () => deps.refresh(session, entry.boundary))()
.then((outcome) => {
if (
outcome !== 'deferred'
- && pending.get(session.id)?.session === session
- && pending.get(session.id)?.boundary.sessionInstanceId === session.instanceId
+ && pending.get(session.id) === entry
) {
pending.delete(session.id);
}
@@ -125,9 +132,9 @@ export function createBotCompactRuntimeRefreshCoordinator(
return 'deferred' as const;
})
.finally(() => {
- if (inFlight.get(session.id) === operation) inFlight.delete(session.id);
+ if (inFlight.get(session.id)?.operation === operation) inFlight.delete(session.id);
});
- inFlight.set(session.id, operation);
+ inFlight.set(session.id, { entry, operation });
return operation;
}
@@ -144,7 +151,11 @@ export function createBotCompactRuntimeRefreshCoordinator(
noteBoundary,
attempt,
clearForClosedSession,
- hasPending: (sessionId: string) => pending.has(sessionId),
+ hasPending: (sessionId: string, session?: BotCompactRuntimeSession) => {
+ const entry = pending.get(sessionId);
+ return !!entry && (!session || (entry.session === session
+ && entry.boundary.sessionInstanceId === session.instanceId));
+ },
resetForTest,
};
}
@@ -152,3 +163,31 @@ export function createBotCompactRuntimeRefreshCoordinator(
export type BotCompactRuntimeRefreshCoordinator = ReturnType<
typeof createBotCompactRuntimeRefreshCoordinator
>;
+
+/** Only live Bot chats require a capability refresh before accepting input.
+ * Ordinary and delegated tasks also emit compaction events, but keep their
+ * existing runtime and queue semantics. Resolve ownership before the busy gate.
+ */
+export async function prepareBotCapabilityEpochBeforeSend<T extends {
+ role: string;
+ source: string;
+ status: string;
+ workingDir: string | null;
+}>(session: BotCompactRuntimeSession, deps: {
+ readSession(): Promise<T | null | undefined>;
+ preflight(row: T & { workingDir: string }): Promise<boolean>;
+ coordinator: BotCompactRuntimeRefreshCoordinator;
+}): Promise<BotCompactRuntimeRefreshOutcome> {
+ const row = await deps.readSession();
+ if (!row || (row.role !== 'canonical' && row.role !== 'group')
+ || row.source !== 'bot' || row.status !== 'active' || !row.workingDir) {
+ return 'not-bot';
+ }
+ const { coordinator } = deps;
+ if (!coordinator.hasPending(session.id, session)) {
+ if (!await deps.preflight({ ...row, workingDir: row.workingDir })) return 'not-bot';
+ coordinator.noteBoundary(session);
+ }
+ const outcome = await coordinator.attempt(session);
+ return coordinator.hasPending(session.id, session) ? 'deferred' : outcome;
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index ce0d4af730..9d397c52b4 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -474,6 +474,7 @@ import { isSessionPermissionMode, persistPermissionModeWithoutRuntime } from './
import { updateBotRoutineLifecycle } from '../routines/service.js';
import {
createBotCompactRuntimeRefreshCoordinator,
+ prepareBotCapabilityEpochBeforeSend,
refreshBotRuntimeAfterModelSelection,
replaceBotRuntimeAfterPreflight,
type BotCompactBoundary,
@@ -7305,80 +7306,64 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
async function refreshBotCapabilityEpochBeforeSend(
live: WiredSession,
): Promise<void> {
- if (botCompactRuntimeRefreshCoordinator.hasPending(live.id)) {
- await botCompactRuntimeRefreshCoordinator.attempt(live);
- if (botCompactRuntimeRefreshCoordinator.hasPending(live.id)) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- '伙伴能力正在刷新,请稍后再发送',
+ const outcome = await prepareBotCapabilityEpochBeforeSend(live, {
+ coordinator: botCompactRuntimeRefreshCoordinator,
+ readSession: async () => {
+ const db = getDbClient().drizzle;
+ const [row] = await db
+ .select({
+ role: botSessionLinks.role,
+ source: sessions.source,
+ status: sessions.status,
+ title: sessions.title,
+ workingDir: sessions.workingDir,
+ workspaceKind: sessions.workspaceKind,
+ agentKind: sessions.agentKind,
+ model: sessions.model,
+ providerId: sessions.providerId,
+ effort: sessions.effort,
+ fastMode: sessions.fastMode,
+ permissionMode: sessions.permissionMode,
+ planModeEnabled: sessions.planModeEnabled,
+ sdkSessionId: sessions.sdkSessionId,
+ remoteHostId: sessions.remoteHostId,
+ orcaRole: sessions.orcaRole,
+ codexHistoryHasProductPrompt: sessions.codexHistoryHasProductPrompt,
+ })
+ .from(sessions)
+ .innerJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))
+ .where(eq(sessions.id, live.id))
+ .limit(1);
+ return row;
+ },
+ preflight: async (row) => {
+ const createOpts = buildCreateOptsWithStderr({
+ id: live.id,
+ agentKind: dbToMakerAgentKind(row.agentKind),
+ workingDir: row.workingDir,
+ workspaceKind: row.workspaceKind,
+ model: row.model ?? undefined,
+ providerId: row.providerId,
+ effort: (row.effort ?? undefined) as CreateOpts['effort'],
+ fastMode: !!row.fastMode,
+ permissionMode: permissionModeOrAsk(row.permissionMode),
+ planMode: !!row.planModeEnabled,
+ title: row.title ?? undefined,
+ resumeSessionId: row.sdkSessionId ?? undefined,
+ remoteHostId: row.remoteHostId ?? undefined,
+ orcaRole: row.orcaRole as CreateOpts['orcaRole'],
+ codexHistoryHasProductPrompt: row.codexHistoryHasProductPrompt ?? undefined,
+ });
+ await synthesizeOrcaVendorOptionsFromDb(live.id, createOpts);
+ const extraDirs = await readSessionExtraDirsFromDb(live.id).catch(() => []);
+ if (extraDirs.length > 0) createOpts.extraDirs = extraDirs;
+ const snapshot = await preflightBotRuntimeResources(
+ createOpts as MakerSessionCreateOpts,
);
- }
- return;
- }
-
- const db = getDbClient().drizzle;
- const [row] = await db
- .select({
- role: botSessionLinks.role,
- source: sessions.source,
- status: sessions.status,
- title: sessions.title,
- workingDir: sessions.workingDir,
- workspaceKind: sessions.workspaceKind,
- agentKind: sessions.agentKind,
- model: sessions.model,
- providerId: sessions.providerId,
- effort: sessions.effort,
- fastMode: sessions.fastMode,
- permissionMode: sessions.permissionMode,
- planModeEnabled: sessions.planModeEnabled,
- sdkSessionId: sessions.sdkSessionId,
- remoteHostId: sessions.remoteHostId,
- orcaRole: sessions.orcaRole,
- codexHistoryHasProductPrompt: sessions.codexHistoryHasProductPrompt,
- })
- .from(sessions)
- .innerJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))
- .where(eq(sessions.id, live.id))
- .limit(1);
- if (
- !row
- || (row.role !== 'canonical' && row.role !== 'group')
- || row.source !== 'bot'
- || row.status !== 'active'
- || !row.workingDir
- ) {
- return;
- }
-
- const createOpts = buildCreateOptsWithStderr({
- id: live.id,
- agentKind: dbToMakerAgentKind(row.agentKind),
- workingDir: row.workingDir,
- workspaceKind: row.workspaceKind,
- model: row.model ?? undefined,
- providerId: row.providerId,
- effort: (row.effort ?? undefined) as CreateOpts['effort'],
- fastMode: !!row.fastMode,
- permissionMode: permissionModeOrAsk(row.permissionMode),
- planMode: !!row.planModeEnabled,
- title: row.title ?? undefined,
- resumeSessionId: row.sdkSessionId ?? undefined,
- remoteHostId: row.remoteHostId ?? undefined,
- orcaRole: row.orcaRole as CreateOpts['orcaRole'],
- codexHistoryHasProductPrompt: row.codexHistoryHasProductPrompt ?? undefined,
+ return !!snapshot?.runtimeEpochChanged;
+ },
});
- await synthesizeOrcaVendorOptionsFromDb(live.id, createOpts);
- const extraDirs = await readSessionExtraDirsFromDb(live.id).catch(() => []);
- if (extraDirs.length > 0) createOpts.extraDirs = extraDirs;
- const snapshot = await preflightBotRuntimeResources(
- createOpts as MakerSessionCreateOpts,
- );
- if (!snapshot?.runtimeEpochChanged) return;
-
- botCompactRuntimeRefreshCoordinator.noteBoundary(live);
- await botCompactRuntimeRefreshCoordinator.attempt(live);
- if (botCompactRuntimeRefreshCoordinator.hasPending(live.id)) {
+ if (outcome === 'deferred') {
throwIpcError(
'PRECONDITION_FAILED',
'伙伴能力正在刷新,请稍后再发送',