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: address review — detach Goal status dispatch

Chrisf33309827f9d
diff --git a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
index b72dd83b81..81dcc268e9 100644
--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
@@ -2849,6 +2849,96 @@ describe('GoalController', () => {
expect(h.session.sends.length).toBe(sends);
});
+ it('resumeOnOpen can return after recovery while prompt acceptance remains pending', async () => {
+ let markDispatchStarted!: () => void;
+ let releaseDispatch!: (result: SessionSendResult) => void;
+ const dispatchStarted = new Promise<void>((resolve) => {
+ markDispatchStarted = resolve;
+ });
+ const pendingDispatch = new Promise<SessionSendResult>((resolve) => {
+ releaseDispatch = resolve;
+ });
+ const local = makeController();
+ vi.spyOn(local.session, 'send').mockImplementation(async (
+ message: Parameters<FakeSession['send']>[0],
+ opts: Parameters<FakeSession['send']>[1],
+ ): Promise<SessionSendResult> => {
+ const content = typeof message === 'string' ? message : message.content;
+ local.session.sends.push({ content, originKind: opts?.origin?.kind });
+ opts?.onDispatching?.();
+ markDispatchStarted();
+ return pendingDispatch;
+ });
+ await local.storage.set(seededGoal({ status: 'active', objective: 'keep going' }));
+
+ await expect(
+ local.controller.resumeOnOpen('s1', { waitForDispatch: false }),
+ ).resolves.toBeUndefined();
+ await dispatchStarted;
+
+ expect(local.session.sends).toHaveLength(1);
+ expect(await local.storage.get('s1')).toMatchObject({ status: 'active' });
+
+ releaseDispatch({ accepted: true });
+ await Promise.resolve();
+ });
+
+ it('converges a detached resume-on-open dispatch failure to blocked', async () => {
+ let markDispatchStarted!: () => void;
+ let releaseDispatch!: () => void;
+ const dispatchStarted = new Promise<void>((resolve) => {
+ markDispatchStarted = resolve;
+ });
+ const dispatchGate = new Promise<void>((resolve) => {
+ releaseDispatch = resolve;
+ });
+ const local = makeController();
+ vi.spyOn(local.session, 'send').mockImplementation(async (
+ message: Parameters<FakeSession['send']>[0],
+ opts: Parameters<FakeSession['send']>[1],
+ ): Promise<SessionSendResult> => {
+ const content = typeof message === 'string' ? message : message.content;
+ local.session.sends.push({ content, originKind: opts?.origin?.kind });
+ opts?.onDispatching?.();
+ markDispatchStarted();
+ await dispatchGate;
+ throw new Error('provider unavailable');
+ });
+ await local.storage.set(seededGoal({ status: 'active', objective: 'recover safely' }));
+
+ await local.controller.resumeOnOpen('s1', { waitForDispatch: false });
+ await dispatchStarted;
+ expect(await local.storage.get('s1')).toMatchObject({ status: 'active' });
+
+ releaseDispatch();
+ await vi.waitFor(async () => {
+ expect(await local.storage.get('s1')).toMatchObject({
+ status: 'blocked',
+ lastReason: expect.stringContaining('provider unavailable'),
+ });
+ });
+ expect(local.session.sends).toHaveLength(1);
+ });
+
+ it('converges a detached resume-on-open preflight read failure to blocked', async () => {
+ const local = makeController();
+ const active = seededGoal({ status: 'active', objective: 'recover safely' });
+ await local.storage.set(active);
+ vi.spyOn(local.storage, 'get')
+ .mockResolvedValueOnce(active)
+ .mockRejectedValueOnce(new Error('goal state read unavailable'));
+
+ await local.controller.resumeOnOpen('s1', { waitForDispatch: false });
+
+ await vi.waitFor(async () => {
+ expect(await local.storage.get('s1')).toMatchObject({
+ status: 'blocked',
+ lastReason: expect.stringContaining('unable to read Goal state'),
+ });
+ });
+ expect(local.session.sends).toHaveLength(0);
+ });
+
it('resumeOnOpen activates a dormant active goal (attach + fire) when the conversation is opened', async () => {
// 模拟重启后 dormant:有 active 目标行,但没挂 listener、没 fire。
await h.storage.set(seededGoal({ status: 'active', objective: 'keep going', turnsUsed: 0 }));
diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts
index 80579264e8..e36576ab97 100644
--- a/apps/desktop/src/main/goal-host/controller.ts
+++ b/apps/desktop/src/main/goal-host/controller.ts
@@ -1342,7 +1342,10 @@ export class GoalController {
* 活化失败则转 blocked 并给出可见原因,不能继续显示成正在推进。
* 这样重开会话能让 active 目标自己跑下去,而不是卡死等用户重发 /goal。
*/
- async resumeOnOpen(sessionId: string): Promise<void> {
+ async resumeOnOpen(
+ sessionId: string,
+ opts?: { waitForDispatch?: boolean },
+ ): Promise<void> {
const pendingFailure = this.unpersistedDispatchFailures.get(sessionId);
if (pendingFailure) {
const persisted = await this.blockDispatchFailure(
@@ -1425,7 +1428,19 @@ export class GoalController {
if (this.turns.get(sessionId) !== lifecycleBoundary) return;
this.emit(state);
if (!this.isBusy(sessionId)) {
- await this.fireTurn(sessionId, { throwOnUnpersistedRestoreFailure: true });
+ const dispatch = this.fireTurn(sessionId, {
+ throwOnUnpersistedRestoreFailure: true,
+ });
+ if (opts?.waitForDispatch === false) {
+ void dispatch.catch((error) => {
+ this.deps.logger.warn('[goal] detached resume-on-open fire failed', {
+ sessionId,
+ error: String(error),
+ });
+ });
+ } else {
+ await dispatch;
+ }
}
}
@@ -2179,7 +2194,23 @@ export class GoalController {
const isCurrentLifecycle = (): boolean =>
this.turns.get(sessionId) === lifecycleBoundary &&
lifecycleBoundary.generation === lifecycleGeneration;
- const state = await this.deps.storage.get(sessionId);
+ let state: GoalState | null;
+ try {
+ state = await this.deps.storage.get(sessionId);
+ } catch (error) {
+ this.deps.logger.warn('[goal] fireTurn preflight state read failed', {
+ sessionId,
+ error: String(error),
+ });
+ const persisted = await this.blockDispatchFailure(
+ sessionId,
+ lifecycleBoundary,
+ 'turn dispatch failed: unable to read Goal state',
+ isCurrentLifecycle,
+ );
+ if (!persisted && opts?.throwOnUnpersistedRestoreFailure) throw error;
+ return;
+ }
// owner 身份拒绝 Stop / Resume 换代,generation 拒绝另一轮正常推进后的旧 fire;
// 两者都不能只信上面读到的 active 存档快照。
if (
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts
index 4fbc05da3a..8f19cb394d 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/goalHandlers.test.ts
@@ -99,7 +99,7 @@ describe('goal update IPC errors', () => {
code: 'INTERNAL',
message: expect.stringContaining('failed to read goal status'),
});
- expect(mocks.resumeOnOpen).toHaveBeenCalledWith('s1');
+ expect(mocks.resumeOnOpen).toHaveBeenCalledWith('s1', { waitForDispatch: false });
});
it('returns the post-recovery blocked state instead of a stale active snapshot', async () => {
@@ -117,7 +117,7 @@ describe('goal update IPC errors', () => {
const result = await handlerFor(MAKER_INVOKE.GOAL_GET_STATUS)({}, 's1');
expect(result).toEqual(blocked);
- expect(mocks.resumeOnOpen).toHaveBeenCalledWith('s1');
+ expect(mocks.resumeOnOpen).toHaveBeenCalledWith('s1', { waitForDispatch: false });
expect(mocks.getStatus).toHaveBeenCalledTimes(2);
});
@@ -136,6 +136,47 @@ describe('goal update IPC errors', () => {
expect(mocks.getStatus).toHaveBeenCalledTimes(1);
});
+ it('returns active status without waiting for detached prompt acceptance', async () => {
+ const active = { sessionId: 's1', status: 'active' };
+ const neverAccepted = new Promise<void>(() => {});
+ mocks.getStatus
+ .mockResolvedValueOnce(active)
+ .mockResolvedValueOnce(active);
+ mocks.resumeOnOpen.mockImplementationOnce(
+ async (_sessionId: string, opts?: { waitForDispatch?: boolean }) => {
+ if (opts?.waitForDispatch !== false) await neverAccepted;
+ },
+ );
+
+ const result = await handlerFor(MAKER_INVOKE.GOAL_GET_STATUS)({}, 's1');
+
+ expect(result).toEqual(active);
+ expect(mocks.resumeOnOpen).toHaveBeenCalledWith('s1', { waitForDispatch: false });
+ expect(mocks.getStatus).toHaveBeenCalledTimes(2);
+ });
+
+ it('maps an internal dormant recovery read failure to sanitized INTERNAL', async () => {
+ mocks.getStatus.mockResolvedValueOnce({ sessionId: 's1', status: 'active' });
+ mocks.resumeOnOpen.mockRejectedValueOnce(
+ new Error('sqlite path /private/user-data/goal.db failed'),
+ );
+
+ const result = handlerFor(MAKER_INVOKE.GOAL_GET_STATUS)({}, 's1');
+
+ let error: unknown;
+ try {
+ await result;
+ } catch (caught) {
+ error = caught;
+ }
+ expect(error).toMatchObject({
+ code: 'INTERNAL',
+ message: expect.stringContaining('failed to restore goal status'),
+ });
+ expect((error as Error).message).not.toContain('/private/user-data');
+ expect(mocks.getStatus).toHaveBeenCalledTimes(1);
+ });
+
it('maps GOAL_SET session restore failures to PRECONDITION_FAILED', async () => {
mocks.setGoal.mockRejectedValueOnce(new GoalSessionRestoreError());
diff --git a/apps/desktop/src/main/maker-ipc/goal.ts b/apps/desktop/src/main/maker-ipc/goal.ts
index 1e4b6e5fb8..5bf8f9950b 100644
--- a/apps/desktop/src/main/maker-ipc/goal.ts
+++ b/apps/desktop/src/main/maker-ipc/goal.ts
@@ -126,13 +126,22 @@ export function registerGoalHandlers(): void {
if (!controller) throwIpcError('INTERNAL', 'goal controller not started');
let status = await readGoalStatusForIpc(controller, id);
// Dormant recovery may synchronously converge an apparently active Goal to
- // blocked. Wait and re-read so this invoke response cannot overwrite the
- // newer status push with its stale pre-recovery active snapshot.
+ // blocked. Wait for storage/session recovery and re-read so this invoke
+ // response cannot overwrite the newer status push with a stale active
+ // snapshot. Actual turn dispatch stays detached: PI prompt acceptance may
+ // legitimately wait through long compaction and must not hold a read query.
if (status?.status === 'active') {
try {
- await controller.resumeOnOpen(id);
+ await controller.resumeOnOpen(id, { waitForDispatch: false });
} catch (error) {
- throwGoalControllerIpcError(error);
+ if (
+ error instanceof GoalControllerInputError ||
+ error instanceof GoalSessionRestoreError ||
+ error instanceof GoalUpdateSupersededError
+ ) {
+ throwGoalControllerIpcError(error);
+ }
+ throwIpcError('INTERNAL', 'failed to restore goal status');
}
status = await readGoalStatusForIpc(controller, id);
}