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(orca): preserve report ownership across direct user turns

fmfsaisai22f57ed7915c
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index f2f97a194c..62be49c8d7 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -409,11 +409,12 @@ describe('maker:event hot path ordering', () => {
const started = new Promise<void>((resolve) => { releaseStart = resolve; });
const waitForStart = vi.fn(() => started);
const handleWorkerTerminalTurn = vi.fn(async (_terminal: { capture: unknown }) => undefined);
+ const noteWorkerProductTerminal = vi.fn();
const finalize = new Function(
'workerTurnStartSequencer',
'orcaTeamServiceForEvents',
`${js}\nreturn ${name};`,
- )({ waitForStart }, { handleWorkerTerminalTurn }) as (
+ )({ waitForStart }, { handleWorkerTerminalTurn, noteWorkerProductTerminal }) as (
sessionId: string,
payload: unknown,
) => void;
@@ -423,6 +424,8 @@ describe('maker:event hot path ordering', () => {
};
finalize('worker-session', payload);
+ // Releasing a deferred failure closes A's report ownership before B can start.
+ expect(noteWorkerProductTerminal).toHaveBeenCalledExactlyOnceWith(capture);
expect(waitForStart).toHaveBeenCalledWith('worker-session');
expect(handleWorkerTerminalTurn).not.toHaveBeenCalled();
releaseStart();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
index 81ac68efab..6517d91765 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
@@ -1921,8 +1921,14 @@ describe('OrcaTeamService', () => {
});
it.each([true, false])('waits outside the transition lock for an in-flight manual report: accepted=%s', async accepted => {
- const h = createDeps();
+ let generation = 1;
+ const runtime = { isTurnRunning: () => true, getTurnGeneration: () => generation };
+ const h = createDeps({ getLiveSession: () => runtime });
await h.service.sendToWorker({ callerLeadSessionId: 'lead-1', targetSessionId: 'worker-session-1', message: 'A' });
+ // A vendor failure is captured but suppressed; auto-resume is still A's product turn.
+ h.service.captureWorkerTerminalTurn('worker-session-1');
+ generation++;
+ await h.service.handleWorkerTurnStarted('worker-session-1');
const finish = h.service.captureLocalWorkerReport('worker-session-1');
const terminal = h.service.handleWorkerTerminalTurn({ sessionId: 'worker-session-1', status: 'done', finalText: 'finished' });
// Observe the durable product terminal, not a timing delay or an implementation promise.
@@ -1989,17 +1995,19 @@ describe('OrcaTeamService', () => {
// PR #7309: a direct-user B does not replace A's auto-bridge identity. Its generation
// must protect the visible status and Stop mark without losing A's outstanding report.
it.each([
- { reported: true, stopB: false },
- { reported: false, stopB: false },
- { reported: true, stopB: true },
- { reported: false, stopB: true },
- ])('settles old A without ending direct-user B: %j', async ({ reported, stopB }) => {
+ { reported: true, stopB: false, stopA: false },
+ { reported: false, stopB: false, stopA: false },
+ { reported: true, stopB: true, stopA: false },
+ { reported: false, stopB: true, stopA: false },
+ { reported: false, stopB: true, stopA: true },
+ ])('settles old A without ending direct-user B: %j', async ({ reported, stopB, stopA }) => {
let generation = 1;
const runtime = { isTurnRunning: () => true, getTurnGeneration: () => generation };
const h = createDeps({ getLiveSession: () => runtime });
const sessionId = 'worker-session-1';
await h.service.sendToWorker({ callerLeadSessionId: 'lead-1', targetSessionId: sessionId, message: 'A' });
if (reported) await h.service.captureLocalWorkerReport(sessionId)(true);
+ if (stopA) h.setManualInterrupt('input_stop');
const capture = h.service.captureWorkerTerminalTurn(sessionId);
generation++;
await h.service.handleWorkerTurnStarted(sessionId);
@@ -2016,12 +2024,45 @@ describe('OrcaTeamService', () => {
expect(h.deps.broadcastOrcaWorkerChanged).not.toHaveBeenCalled();
expect(h.deps.clearManualInterrupt).not.toHaveBeenCalled();
expect(h.deps.getManualInterrupt(sessionId)).toBe(stopMark);
- expect(h.deps.sendAutoBridgeToLead).toHaveBeenCalledTimes(reported ? 0 : 1);
- if (!reported) expect(h.deps.sendAutoBridgeToLead).toHaveBeenCalledWith('lead-1', expect.stringContaining('A result'), 'worker-1');
+ expect(h.deps.sendAutoBridgeToLead).toHaveBeenCalledTimes(reported || stopA ? 0 : 1);
+ if (!reported && !stopA) expect(h.deps.sendAutoBridgeToLead).toHaveBeenCalledWith('lead-1', expect.stringContaining('A result'), 'worker-1');
expect(h.service.captureWorkerTerminalTurn(sessionId).autoBridgeIdentity).toBeNull();
await h.service.handleWorkerTerminalTurn({ sessionId, status: 'done', finalText: 'B result' });
expect(h.getWorker().status).toBe(stopB ? 'idle' : 'done');
- expect(h.deps.sendAutoBridgeToLead).toHaveBeenCalledTimes(reported ? 0 : 1);
+ expect(h.deps.sendAutoBridgeToLead).toHaveBeenCalledTimes(reported || stopA ? 0 : 1);
+ });
+
+ // PR #7309 second review: an unchanged report object must not let direct-user B
+ // pay A's debt. The old generation tests never sent a manual report from B.
+ // Unit: pause the real terminal handler at its first async read, then report from B.
+ it('keeps A outstanding when direct-user B reports before A terminal handling resumes', async () => {
+ let generation = 1;
+ const runtime = { isTurnRunning: () => true, getTurnGeneration: () => generation };
+ const h = createDeps({ getLiveSession: () => runtime });
+ const sessionId = 'worker-session-1';
+ await h.service.sendToWorker({ callerLeadSessionId: 'lead-1', targetSessionId: sessionId, message: 'A' });
+ const capture = h.service.captureWorkerTerminalTurn(sessionId);
+ let release!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const getLink = h.deps.getWorkerLinkBySessionId;
+ vi.mocked(getLink).mockImplementationOnce(async () => {
+ await gate;
+ return { workerId: 'worker-1', leadSessionId: 'lead-1', teamId: 'team-1', workerSessionId: sessionId };
+ });
+ const terminal = { sessionId, status: 'done' as const, finalText: 'A real result', capture };
+ const handling = h.service.handleWorkerTerminalTurn(terminal);
+ generation++;
+ await h.service.handleWorkerTurnStarted(sessionId);
+ await h.service.captureLocalWorkerReport(sessionId)(true);
+ const stillPendingAfterBReport = h.service.hasPendingWorkerReports('lead-1');
+ release();
+ await handling;
+ await h.service.handleWorkerTerminalTurn(terminal);
+ expect(stillPendingAfterBReport).toBe(true);
+ expect(h.deps.sendAutoBridgeToLead).toHaveBeenCalledExactlyOnceWith(
+ 'lead-1', expect.stringContaining('A real result'), 'worker-1',
+ );
+ expect(h.getWorker().status).toBe('running');
});
it('keeps an in-flight auto-report pending across duplicate terminal delivery', async () => {
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 6606107d7a..5a68b78c8e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@ -328,6 +328,7 @@ function harness() {
handleWorkerTurnStarted: effects.fn('worker-start'),
captureWorkerText: vi.fn(),
captureWorkerTerminalTurn: vi.fn(() => ({ owner: 'old-turn' })),
+ noteWorkerProductTerminal: vi.fn(),
handleWorkerTerminalTurn: effects.fn('worker-terminal'),
},
turnModelPromiseBySession: new Map<string, Promise<string>>(),
@@ -969,6 +970,7 @@ describe('production Session event pipeline', () => {
expect(effects.fn('resetTurnPersistState')).toHaveBeenCalledOnce();
await microtasks();
expect(h.deps.orcaTeamServiceForEvents.handleWorkerTerminalTurn).not.toHaveBeenCalled();
+ expect(h.deps.orcaTeamServiceForEvents.noteWorkerProductTerminal).not.toHaveBeenCalled();
effects.fn('recordTurnUsageOnMessage').mockClear();
vi.setSystemTime(5000);
h.emit(event('done', { total_cost_usd: 0, duration_ms: 20 }, { source }));
@@ -1293,6 +1295,7 @@ describe('production Session event pipeline', () => {
expect(effects.fn('markAssistantTurnCompleted')).not.toHaveBeenCalled();
expect(h.deps.autoResumeBookkeeping.stashOrcaSuppressedTerminal).toHaveBeenCalledOnce();
expect(h.deps.orcaTeamServiceForEvents.handleWorkerTerminalTurn).not.toHaveBeenCalled();
+ expect(h.deps.orcaTeamServiceForEvents.noteWorkerProductTerminal).not.toHaveBeenCalled();
expect(h.deps.onUnsuccessfulProductTurn).not.toHaveBeenCalled();
await h.dispose();
});
@@ -1479,6 +1482,8 @@ describe('production Session event pipeline', () => {
);
expect(effects.fn('refreshSessionListPreview')).not.toHaveBeenCalled();
expect(h.deps.orcaTeamServiceForEvents.handleWorkerTerminalTurn).not.toHaveBeenCalled();
+ // Seal A synchronously before the start barrier lets queued B report against A's debt.
+ expect(h.deps.orcaTeamServiceForEvents.noteWorkerProductTerminal).toHaveBeenCalledWith({ owner: 'old-turn' });
h.deps.orcaTeamServiceForEvents.captureWorkerTerminalTurn.mockReturnValue({
owner: 'new-turn',
});
diff --git a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
index 99b98fad62..892fec5cc2 100644
--- a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
@@ -557,6 +557,8 @@ export interface OrcaTeamService {
restoreWorkerPendingReport(sessionId: string, input: { workerId: string; leadSessionId: string }): void;
handleWorkerTurnStarted(sessionId: string): Promise<void>;
captureWorkerTerminalTurn(sessionId: string): WorkerTerminalTurnCapture;
+ /** Synchronous product boundary; never call for a suppressed vendor terminal. */
+ noteWorkerProductTerminal(capture: WorkerTerminalTurnCapture | undefined): void;
handleWorkerTerminalTurn(params: WorkerTerminalTurnParams): Promise<void>;
}
@@ -565,6 +567,7 @@ interface AutoBridgeState {
pending: boolean;
reportsInFlight: Set<Promise<void>>;
terminalObserved: boolean;
+ productTerminal?: Pick<WorkerTerminalTurnCapture, 'runtime' | 'turnGeneration'>;
ready: boolean;
inFlight: boolean;
workerId: string;
@@ -847,6 +850,18 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
};
}
+ function noteWorkerProductTerminal(capture: WorkerTerminalTurnCapture | undefined): void {
+ if (!capture?.runtime) return;
+ const current = autoBridge.get(capture.sessionId);
+ const previous = provisionalDispatches.get(capture.sessionId)?.previousPendingIdentity;
+ const state = current === capture.autoBridgeIdentity ? current
+ : previous === capture.autoBridgeIdentity ? previous : undefined;
+ if (!state) return;
+ // Auto-resume can advance the vendor generation within one product turn. Only
+ // its unsuppressed terminal closes report ownership, before queued user B starts.
+ state.productTerminal ??= { runtime: capture.runtime, turnGeneration: capture.turnGeneration };
+ }
+
function uniqueWorkers(workers: OrcaWorkerRecordSnapshot[]): OrcaWorkerRecordSnapshot[] {
const byId = new Map<string, OrcaWorkerRecordSnapshot>();
for (const worker of workers) {
@@ -2077,6 +2092,14 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
// Direct user turns have no Lead obligation. In particular, a late callback must
// not look up and settle a new assignment that did not exist at capture time.
if (!state) return async () => {};
+ const runtime = deps.getLiveSession(sessionId);
+ const generation = runtime?.getTurnGeneration?.();
+ if (state.productTerminal && (
+ state.productTerminal.runtime !== runtime
+ || state.productTerminal.turnGeneration !== generation
+ )) return async () => {};
+ // Capture before delivery: an already-started final report may be accepted
+ // after terminal capture or B's start and still belongs to A.
let release!: () => void;
const settled = new Promise<void>(resolve => { release = resolve; });
state.reportsInFlight.add(settled);
@@ -2123,6 +2146,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
state.retryAfterRejectedDelivery = true;
},
captureWorkerTerminalTurn,
+ noteWorkerProductTerminal,
async handleWorkerTurnStarted(sessionId) {
const link = await deps.getWorkerLinkBySessionId(sessionId);
if (!link) return;
@@ -2151,6 +2175,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
params.capture?.sessionId === params.sessionId
? params.capture
: captureWorkerTerminalTurn(params.sessionId);
+ noteWorkerProductTerminal(capture);
let manualInterruptOwnership = capture.manualInterrupt;
const autoBridgeAtEntry = capture.autoBridgeIdentity;
const ownsRuntime = () => !capture.runtime || (
@@ -2210,7 +2235,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
// Direct-user B can reuse A's report identity. Settle only A's obligation:
// its old terminal must not write B's status or clear B's Stop/provisional state.
const state = autoBridge.get(params.sessionId);
- if (state?.pending) completionState = state;
+ if (state?.pending && !manualInterruptOwnership) completionState = state;
else if (state) deletePendingReport(params.sessionId);
return;
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 53385abd66..cc5f7a32f3 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1991,6 +1991,7 @@ export function cancelSchedulerAutoResume(sessionId: string, runId: string): boo
* Worker 状态与 auto-bridge(把异常终止回报给 Lead)。
*/
function settleDeferredOrcaWorkerTerminal(sessionId: string, payload: OrcaSuppressedTerminal): void {
+ orcaTeamServiceForEvents?.noteWorkerProductTerminal(payload.capture as WorkerTerminalTurnCapture | undefined);
void (async () => {
try {
await workerTurnStartSequencer.waitForStart(sessionId);
diff --git a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
index 5c9cd92b55..ffcfacecf0 100644
--- a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
@@ -147,7 +147,7 @@ export interface FinishSessionTerminalEventDeps {
ReturnType<typeof createWorkerTurnStartSequencer>,
'waitForStart'
>;
- readonly orcaTeamServiceForEvents: Pick<OrcaTeamService, 'handleWorkerTerminalTurn'> | null;
+ readonly orcaTeamServiceForEvents: Pick<OrcaTeamService, 'handleWorkerTerminalTurn' | 'noteWorkerProductTerminal'> | null;
}
export function finishSessionTerminalEvent(
@@ -753,6 +753,7 @@ export function finishSessionTerminalEvent(
if (providerGroupHeldWorkerTerminal) {
// 已与产品终态一起暂存,由同一次恢复登记结算。
} else {
+ deps.orcaTeamServiceForEvents?.noteWorkerProductTerminal(workerTerminalCapture);
void (async () => {
try {
await deps.workerTurnStartSequencer.waitForStart(session.id);
diff --git a/docs/dev-rules/orca-team-architecture.md b/docs/dev-rules/orca-team-architecture.md
index 84ca36b71d..9f56eeb69d 100644
--- a/docs/dev-rules/orca-team-architecture.md
+++ b/docs/dev-rules/orca-team-architecture.md
@@ -392,7 +392,7 @@ Git worktree,不改变供应商、模型与 Worker 创建权限偏好。
4. **worker 主动回报会结清自动回报态(状态:不变量)**<br>
本机持有 Session 的 Worker(含 SSH Worker)主动 `send_to_lead` 被直发接收、入队或同轮插话接收后,只把本轮 auto-bridge 的 `pending` 置为 false,**不写 done**。回报身份保留到产品终态;真正结束才写 done / error,手动停止仍为 idle。已回报的轮次不再自动补报,失败投递仍欠回报;同轮多次显式回报各自送达,结清幂等。末步回报后的终态沿原事件即时收口,不加轮询或延时。实现指针:`orca-bridge-mcp.ts` 的 `send_to_lead` 与 `orcaTeamService.ts` 的 `captureLocalWorkerReport` / `handleWorkerTerminalTurn`。
- 回报在投递前捕获本轮身份,迟到的 queued accepted 不再结算;B 派发临时接管期间,A 的回报只能结清捕获的 previous pending,B 回滚不能复活 A 的欠账,B 提交不能被 A 清掉。产品终态与回报结算经同一 Worker transition 锁串行修改;等待投递、回报或 provisional settlement 必须在锁外,自动回报完成后再核对对象身份,不能删掉新一轮。无 Lead 派单的用户直接轮次不建立欠回报账。所有本地终态写状态前均按 main Session 实例 / generation 隔离;用户直发新轮不替换旧回报身份时,旧终态仍结清自己的欠回报(未回报则自动代报),但只移除同一旧对象,不写新轮状态、不清新轮的手动停止或 provisional 状态。运行设备 Worker 的 `settleReportedWorker` 与 remote commit 仍沿原有持久结算语义,本地规则不扩展到运行设备代理。
+ 回报在投递前捕获本轮身份,迟到的 queued accepted 不再结算;B 派发临时接管期间,A 的回报只能结清捕获的 previous pending,B 回滚不能复活 A 的欠账,B 提交不能被 A 清掉。产品终态与回报结算经同一 Worker transition 锁串行修改;等待投递、回报或 provisional settlement 必须在锁外,自动回报完成后再核对对象身份,不能删掉新一轮。无 Lead 派单的用户直接轮次不建立欠回报账。自动续跑 / host continuation 会推进 vendor generation,不能用派活时的 generation 拒绝同产品轮次的回报;只有未被 suppress、未被恢复接管的产品终态才同步记录 Session 实例与 generation(先于终态处理的异步等待)。此后直发 B 的回报照常送达,但不能结清 A 的欠账;终态前已开始投递的 A 回报仍可结算,末步回报无需延时。所有本地终态写状态前均按 main Session 实例 / generation 隔离;用户直发新轮不替换旧回报身份时,旧终态仍结清自己的欠回报(捕获时已手动停止则静默移除,否则未回报才自动代报),但只移除同一旧对象,不写新轮状态、不清新轮的手动停止或 provisional 状态。运行设备 Worker 的 `settleReportedWorker` 与 remote commit 仍沿原有持久结算语义,本地规则不扩展到运行设备代理。
`hasPendingWorkerReports` 只统计仍欠回报的 Worker,不代表仍在运行的 Worker。最后一份回报被接收时,沿已有 `onLeadWorkerReportsSettled` 通知灵动岛;Lead 自身忙碌或有队列时仍由其现有完成规则处理。相较旧实现等 Worker 终态再清 pending,这可能更早解除 Lead 的完成暂缓;不另增加「Worker 仍在工作」条件。