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(teammates): preserve owner replies and reject cancelled run success

zqchris649e9266ad65
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 5b33e9d19e..63eda0e812 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -2335,6 +2335,8 @@ describe('AgentInputCoordinator send transaction', () => {
h.coordinator.enqueue(sid, { ...makeItem('typed', 'Update Cindy'), autoReviewUserText: 'Update Cindy' });
await flush();
expect(h.coordinator.isActiveInputOwnerAuthored(sid)).toBe(true);
+ expect(h.coordinator.isActiveInputOwnerAuthored(sid, 0)).toBe(true);
+ expect(h.coordinator.isActiveInputOwnerAuthored(sid, 1)).toBe(false);
await h.coordinator.steer(sid, {
...makeItem('from-task', 'please update'),
autoReviewUserText: 'please update',
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
index 5a68b78c8e..2db4ef6d4d 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@ -679,6 +679,23 @@ describe('production Session event pipeline', () => {
} finally { close(); await h.dispose(); }
});
+ it('shows the accepted owner reply during a quiet run without changing scheduler attribution', async () => {
+ const h = harness();
+ const close = beginQuietScheduledOutput('check', 'owner-steer-run');
+ const origin = { kind: 'scheduler' as const, scheduleId: 'check', scheduleName: 'Check', runId: 'owner-steer-run' };
+ const ownerAuthored = vi.fn(() => false);
+ Object.assign(h.deps.agentInputCoordinatorHolder, { isActiveInputOwnerAuthored: ownerAuthored });
+ try {
+ h.emit(event('text', { text: 'Background preamble' }, { turnOrigin: origin }));
+ expect(effects.fn('onAssistantTextEvent')).not.toHaveBeenCalled();
+ ownerAuthored.mockReturnValue(true);
+ h.emit(event('text', { text: 'Here is the progress', isFinal: true }, { turnOrigin: origin }));
+ expect(effects.fn('onAssistantTextEvent')).toHaveBeenCalledOnce();
+ expect(JSON.stringify(h.deps.broadcastToAllWindows.mock.calls)).toContain('owner-steer-run');
+ expect(origin.kind).toBe('scheduler');
+ } finally { close(); await h.dispose(); }
+ });
+
it('keeps redacted terminal fields redacted for quiet scheduler output', async () => {
const h = harness();
const close = beginQuietScheduledOutput('check', 'redaction-run');
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index fec4a6f9da..ce4530f67e 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -1356,7 +1356,10 @@ export class AgentInputCoordinator {
* this account's user typed on Desktop or a same-account remote device. Automation,
* other tasks, Orca, plugins, shared-task guests and automatic resumes never qualify.
*/
- isActiveInputOwnerAuthored(sessionId: string): boolean {
+ isActiveInputOwnerAuthored(sessionId: string, vendorGeneration?: number): boolean {
+ const active = this.states.get(sessionId)?.activeTurn;
+ if (vendorGeneration !== undefined && active?.vendorTurnGeneration != null
+ && vendorGeneration !== active.vendorTurnGeneration) return false;
return this.activeInputHasOwnerAuthor(sessionId, false);
}
diff --git a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
index 59c0fef61c..457d9abd5a 100644
--- a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts
@@ -1,6 +1,6 @@
import { taskResultClientIdForInput } from '../../shared/botCollaboration.js';
import { readChannelToolScope } from '../im/shared/channelToolScope.js';
-import { isQuietScheduledOutput } from '../scheduler-host/silent-output.js';
+import { isQuietScheduledOutput, revealScheduledOutput } from '../scheduler-host/silent-output.js';
import { captureTurnUsageContext, type TurnUsageContext } from './turnUsageContext.js';
import type { BotCompactRuntimeRefreshCoordinator } from './botCompactRuntimeRefresh.js';
import type {
@@ -120,7 +120,7 @@ export interface PrepareSessionEventDeps {
readonly agentInputCoordinatorHolder: Pick<
AgentInputCoordinator,
'onTurnEvent' | 'noteSuppressedTerminalError' | 'getActiveInputClientId' | 'getActiveInputClientIds' | 'getAcceptedInputProvenance' | 'isActiveTaskCoordination'
- > | null;
+ > & Partial<Pick<AgentInputCoordinator, 'isActiveInputOwnerAuthored'>> | null;
readonly handleSilentStopTurnEnd: (
session: Session,
doneAt: number,
@@ -184,6 +184,10 @@ export function prepareSessionEvent(
},
};
}
+ if (event.turnScope !== 'background'
+ && deps.agentInputCoordinatorHolder?.isActiveInputOwnerAuthored?.(session.id, event.sessionTurnGeneration)) {
+ revealScheduledOutput(event.turnOrigin);
+ }
const taskCoordination = event.turnScope !== 'background'
&& (deps.agentInputCoordinatorHolder?.isActiveTaskCoordination?.(session.id, event.sessionTurnGeneration) ?? false);
if (event.type === 'text' && event.standaloneText === true) {
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts
index 50f0f04a9c..c08f20ab4c 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerBackgroundTasks.test.ts
@@ -583,13 +583,28 @@ describe('MakerScheduleRunner background subagent task tracking', () => {
expect(notifiedRun(notifier).resultText).toBe('final summary');
});
+ it.each([
+ ...['cancelled', 'failed', 'interrupted', 'aborted'].map(status => ({ source: 'pi', data: { status }, status })),
+ { source: 'codex', data: { cancelled: true }, status: 'cancelled' },
+ ])('does not record $source $status as success when the scheduler signal is still live', async ({ source, data, status }) => {
+ const h = createSessionHarness(acceptingSend());
+ const { runner, notifier } = createRunnerHarness(h.session);
+ const ctx = createFireContext();
+ const fire = runner.fire(baseSchedule(), ctx);
+ await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalled());
+ h.emit({ type: 'done', source, data: { ...data, result: '' } });
+ await expect(fire).rejects.toThrow(`Scheduled turn ended with status: ${status}`);
+ expect(ctx.signal.aborted).toBe(false);
+ expect(notifiedRun(notifier)).toMatchObject({ status: 'failed', errorMsg: `Scheduled turn ended with status: ${status}` });
+ });
+
it('continuation task stopped after done 收到 provider cancellation 后立即收口', async () => {
const h = createSessionHarness(acceptingSend());
const { runner, notifier } = createRunnerHarness(h.session);
const firePromise = runner.fire(baseSchedule(), createFireContext());
let resolved = false;
- void firePromise.then(() => { resolved = true; });
+ void firePromise.then(() => { resolved = true; }, () => { resolved = true; });
await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalled());
h.emit(taskUpdate('bg-task-1', 'running'));
@@ -600,8 +615,8 @@ describe('MakerScheduleRunner background subagent task tracking', () => {
expect(resolved).toBe(false);
h.setContinuationState(3, 'cancelled', true);
- await firePromise;
- expect(notifiedRun(notifier).resultText).toBe('等待后台任务');
+ await expect(firePromise).rejects.toThrow('Scheduled turn continuation was cancelled');
+ expect(notifiedRun(notifier)).toMatchObject({ status: 'failed', errorMsg: 'Scheduled turn continuation was cancelled' });
});
it('host 消费父 done 前 continuation 已 active,仍等待第二个 done', async () => {
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
index 5e0a9817d6..e8a31fcebd 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSilentNotify.test.ts
@@ -54,7 +54,7 @@ vi.mock('../runners/_shared', () => ({
}));
import { MakerScheduleRunner } from '../runner';
-import { projectQuietScheduledOutput } from '../silent-output.js';
+import { projectQuietScheduledOutput, revealScheduledOutput, hasVisibleScheduledOutput } from '../silent-output.js';
type SessionSendOptions = Parameters<Session['send']>[1];
type SendImpl = (
@@ -563,6 +563,27 @@ describe('MakerScheduleRunner silent-run notification skip', () => {
},
);
+ it.each([true, false].flatMap(silenced => [true, false].map(terminalOnly => ({ silenced, terminalOnly }))))(
+ 'persists an owner-promoted reply once (silenced=$silenced, terminalOnly=$terminalOnly)',
+ async ({ silenced, terminalOnly }) => {
+ const h = createSessionHarness(acceptingSend());
+ const { runner, notifier } = createRunnerHarness(h.session, { silenced });
+ const promise = runner.fire(baseSchedule({ source: 'bot', silentWhenIdle: true }), createFireContext());
+ await vi.waitFor(() => expect(mocks.createMessage).toHaveBeenCalled());
+ h.emit({ type: 'text', data: { text: 'Hidden preamble' } });
+ revealScheduledOutput({ kind: 'scheduler', scheduleId: 'schedule-1', scheduleName: 'Check', runId: 'run-1' });
+ if (!terminalOnly) h.emit({ type: 'text', data: { text: 'Owner reply', isFinal: true } });
+ h.emit({ type: 'done', data: { result: 'Owner reply' } });
+ await promise;
+ const repairs = mocks.createMessage.mock.calls.filter(([, body]) => body.role === 'assistant');
+ // The normal text pipeline persists streamed replies; only a done-only reply needs repair.
+ expect(repairs).toHaveLength(terminalOnly ? 1 : 0);
+ if (terminalOnly) expect(repairs[0][1].content).toBe('Owner reply');
+ expect(notifier.notify).toHaveBeenCalledTimes(silenced ? 0 : 1);
+ expect(hasVisibleScheduledOutput('run-1')).toBe(false);
+ },
+ );
+
it('does not broadcast or notify into a new owner after persisting the final report', async () => {
const h = createSessionHarness(acceptingSend());
const { runner, notifier } = createRunnerHarness(h.session, { silenced: false });
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index a61d625b43..9d2ed9f1d8 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -1,4 +1,4 @@
-import { beginQuietScheduledOutput, hidesScheduledTranscript } from './silent-output.js';
+import { beginQuietScheduledOutput, hidesScheduledTranscript, hasVisibleScheduledOutput } from './silent-output.js';
import { untrustedJsonBlock } from '../../shared/untrustedPrompt.js';
import { BUILTIN_ROUTINE_SCHEDULE_PREFIX, routineInstructionFromPrompt } from '../../shared/botAutonomy.js';
import {
@@ -3337,7 +3337,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
// Save a canonical reply missing from the normal text-event persistence path,
// including done-only replacements of a partial stream. Matching replies need no extra row.
const missingFinalReply =
- !hidesScheduledTranscript(schedule) &&
+ !(hidesScheduledTranscript(schedule) && !hasVisibleScheduledOutput(ctx.runId)) &&
!finalTextMatchesStream &&
finalRun.status === 'success' &&
!!assistantText.trim();
@@ -3368,7 +3368,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
if (!silenced) ctx.onRunnerNotified?.(finalRun.status === 'success' ? 'success' : 'failure');
const ownerScope = captureDataOwnerBroadcastScope();
if (
- (hidesScheduledTranscript(schedule) || missingFinalReply) &&
+ ((hidesScheduledTranscript(schedule) && !hasVisibleScheduledOutput(ctx.runId)) || missingFinalReply) &&
finalRun.status === 'success' &&
assistantText.trim()
) {
@@ -3589,6 +3589,12 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 边界是本 run 的 auto-resume claim。旧 turn 的 done 即使迟到也不能提前
// 收口,恢复 turn 跨过 pre-vendor 边界时 claim 会先被清除。
if (isCurrentAutoResumePending()) return;
+ const terminalOutcome = ev.data as { status?: unknown; cancelled?: boolean } | null;
+ const terminalStatus = terminalOutcome?.cancelled === true ? 'cancelled' : terminalOutcome?.status;
+ if (['cancelled', 'aborted', 'interrupted', 'failed'].includes(String(terminalStatus))) {
+ fail(new Error(`Scheduled turn ended with status: ${terminalStatus}`));
+ return;
+ }
// silent-stop:上游空内容消息静默收尾,main 守卫会在 1.5s 后自动续跑
// (或弹耗尽横幅)。不 finish——等续跑 turn 的 done 或守卫 settle 通知。
// settle 通知覆盖守卫决策为非续跑的所有路径(skip/exhausted/send 失败),
@@ -3602,8 +3608,8 @@ export class MakerScheduleRunner implements ScheduleRunner {
: (owner.beginTurnContinuationWait?.(continuationId) ?? null);
if (continuationState === 'cancelled') {
// Provider already observed an explicit stop/teardown. Session
- // gets a separate ordered boundary; this run can settle now.
- finish();
+ // gets a separate ordered boundary; this run did not complete.
+ fail(new Error('Scheduled turn continuation was cancelled'));
return;
}
if (continuationState === 'awaiting' || continuationState === 'active') {
@@ -3620,7 +3626,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
pendingContinuationUnsub?.();
pendingContinuationUnsub = undefined;
- finish();
+ fail(new Error('Scheduled turn continuation was cancelled'));
},
);
this.deps.logger.info?.(
diff --git a/apps/desktop/src/main/scheduler-host/silent-output.ts b/apps/desktop/src/main/scheduler-host/silent-output.ts
index 1b6acf255f..05533d4ef5 100644
--- a/apps/desktop/src/main/scheduler-host/silent-output.ts
+++ b/apps/desktop/src/main/scheduler-host/silent-output.ts
@@ -32,19 +32,32 @@ export function hidesScheduledTranscript(
/** Run-scoped presentation gate. Raw provider events still reach the scheduler and usage ledger. */
const quietRuns = new Map<string, string>();
+const visibleRuns = new Set<string>();
export function beginQuietScheduledOutput(scheduleId: string, runId: string): () => void {
quietRuns.set(runId, scheduleId);
return () => {
if (quietRuns.get(runId) === scheduleId) quietRuns.delete(runId);
+ visibleRuns.delete(runId);
};
}
+/** Presentation only: keep the scheduler origin and its execution authority intact. */
+export function revealScheduledOutput(origin: SendOrigin | undefined): void {
+ if (origin?.kind === 'scheduler' && origin.runId
+ && quietRuns.get(origin.runId) === origin.scheduleId) visibleRuns.add(origin.runId);
+}
+
+export function hasVisibleScheduledOutput(runId: string): boolean {
+ return visibleRuns.has(runId);
+}
+
export function isQuietScheduledOutput(event: AgentEvent): boolean {
const origin = event.turnOrigin;
return (
origin?.kind === 'scheduler' &&
typeof origin.runId === 'string' &&
+ !visibleRuns.has(origin.runId) &&
quietRuns.get(origin.runId) === origin.scheduleId
);
}