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(desktop): 清除目标时中断执行状态 (#1601)

lilsnake77ae49a51877
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 6f1cf55e0a..cca78a2c2c 100644
--- a/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/goal-host/__tests__/controller.test.ts
@@ -223,10 +223,11 @@ class FakeSession implements SessionLike {
async send(
message: { type: 'user'; content: string } | string,
- opts?: { origin?: { kind?: string } },
+ opts?: { origin?: { kind?: string }; onDispatching?: () => void; signal?: AbortSignal },
): Promise<SessionSendResult> {
const content = typeof message === 'string' ? message : message.content;
this.sends.push({ content, originKind: opts?.origin?.kind });
+ opts?.onDispatching?.();
return { accepted: true };
}
@@ -331,6 +332,7 @@ function makeController(depOverrides: Partial<GoalControllerDeps> = {}) {
getSession: (id) => (id === 's1' ? session : undefined),
ensureSession: async (id) => (hydratable && id === 's1' ? session : undefined),
isSessionInTurn: () => false,
+ stopActiveGoalTurn: () => {},
emitStatus: (u) => updates.push(u),
getDefaults: () => ({ ...DEFAULT_LIMITS }),
persistGoalSettingsOverride: (l) => persistedLimits.push(l),
@@ -530,6 +532,7 @@ describe('GoalController', () => {
getSession: () => undefined, // dormant:此刻没有 live session
ensureSession: async () => codexSession, // resume 出真正的 Codex 会话
isSessionInTurn: () => false,
+ stopActiveGoalTurn: () => {},
emitStatus: () => {},
getDefaults: () => ({ ...DEFAULT_LIMITS }),
persistGoalSettingsOverride: () => {},
@@ -1453,6 +1456,7 @@ describe('GoalController', () => {
const internals = local.controller as unknown as {
fireTurn(sessionId: string): Promise<void>;
firing: Map<string, object>;
+ goalDispatchAbortControllers: Map<string, { owner: object; controller: AbortController }>;
};
const oldFire = internals.fireTurn('s1');
@@ -1462,10 +1466,13 @@ describe('GoalController', () => {
const resumePromise = local.controller.resumeGoal('s1');
await vi.waitFor(() => expect(acquireCalls).toBe(3));
expect(internals.firing.has('s1')).toBe(true);
+ const resumedDispatchCancellation = internals.goalDispatchAbortControllers.get('s1');
+ expect(resumedDispatchCancellation).toBeDefined();
releaseOldAcquire(() => {});
await oldFire;
expect(internals.firing.has('s1')).toBe(true);
+ expect(internals.goalDispatchAbortControllers.get('s1')).toBe(resumedDispatchCancellation);
releaseNewAcquire(() => {});
await resumePromise;
@@ -1485,6 +1492,7 @@ describe('GoalController', () => {
): Promise<SessionSendResult> => {
const content = typeof message === 'string' ? message : message.content;
local.session.sends.push({ content, originKind: opts?.origin?.kind });
+ opts?.onDispatching?.();
sendCalls += 1;
return sendCalls === 2 ? blockedOldSend : { accepted: true };
});
@@ -2213,6 +2221,215 @@ describe('GoalController', () => {
expect(h.updates.at(-1)).toEqual({ sessionId: 's1', goal: null });
});
+ it('clearGoal interrupts the in-flight goal turn before removing the goal', async () => {
+ const stopActiveGoalTurn = vi.fn();
+ const local = makeController({ stopActiveGoalTurn });
+ await startGoal(local);
+
+ await local.controller.clearGoal('s1');
+
+ expect(stopActiveGoalTurn).toHaveBeenCalledOnce();
+ expect(stopActiveGoalTurn).toHaveBeenCalledWith('s1');
+ expect(await local.storage.get('s1')).toBeNull();
+ expect(local.updates.at(-1)).toEqual({ sessionId: 's1', goal: null });
+ });
+
+ it('clearGoal interrupts a goal turn after vendor dispatch starts but before send resolves', async () => {
+ const stopActiveGoalTurn = vi.fn();
+ const local = makeController({ stopActiveGoalTurn });
+ let releaseSend!: () => void;
+ const sendPending = new Promise<void>((resolve) => {
+ releaseSend = resolve;
+ });
+ 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?.();
+ await sendPending;
+ return { accepted: true };
+ });
+
+ const setPromise = startGoal(local);
+ await vi.waitFor(() => expect(local.session.sends).toHaveLength(1));
+ await local.controller.clearGoal('s1');
+
+ expect(stopActiveGoalTurn).toHaveBeenCalledOnce();
+ releaseSend();
+ await setPromise;
+ expect(await local.storage.get('s1')).toBeNull();
+ });
+
+ it('clearGoal cancels a goal send waiting before vendor dispatch', async () => {
+ const stopActiveGoalTurn = vi.fn();
+ const local = makeController({ stopActiveGoalTurn });
+ let releasePreDispatchGate!: () => void;
+ const preDispatchGate = new Promise<void>((resolve) => {
+ releasePreDispatchGate = resolve;
+ });
+ let signal: AbortSignal | undefined;
+ let vendorDispatches = 0;
+ 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 });
+ signal = opts?.signal;
+ await preDispatchGate;
+ if (signal?.aborted) {
+ return { accepted: false, reason: 'cancelled-before-dispatch' };
+ }
+ opts?.onDispatching?.();
+ vendorDispatches += 1;
+ return { accepted: true };
+ });
+
+ const setPromise = startGoal(local);
+ await vi.waitFor(() => expect(local.session.sends).toHaveLength(1));
+ await local.controller.clearGoal('s1');
+ releasePreDispatchGate();
+ await setPromise;
+
+ expect(signal?.aborted).toBe(true);
+ expect(vendorDispatches).toBe(0);
+ expect(stopActiveGoalTurn).not.toHaveBeenCalled();
+ expect(await local.storage.get('s1')).toBeNull();
+ });
+
+ it('clearGoal does not interrupt a non-goal turn', async () => {
+ const stopActiveGoalTurn = vi.fn();
+ const local = makeController({ stopActiveGoalTurn });
+ await local.storage.set(seededGoal());
+ local.session.running = true;
+
+ await local.controller.clearGoal('s1');
+
+ expect(stopActiveGoalTurn).not.toHaveBeenCalled();
+ expect(await local.storage.get('s1')).toBeNull();
+ });
+
+ it.each(['done', 'error'] as const)(
+ 'clearGoal does not interrupt a queued user turn after the goal %s terminal event',
+ async (terminalEvent) => {
+ const stopActiveGoalTurn = vi.fn();
+ const local = makeController({ stopActiveGoalTurn });
+ await startGoal(local);
+ const active = await local.storage.get('s1');
+ let releaseFinalizeGet!: (state: GoalState | null) => void;
+ const blockedFinalizeGet = new Promise<GoalState | null>((resolve) => {
+ releaseFinalizeGet = resolve;
+ });
+ vi.spyOn(local.storage, 'get').mockImplementationOnce(() => blockedFinalizeGet);
+
+ // The input coordinator can start the queued user turn as soon as it observes this
+ // terminal event, while GoalController's async persistence finalization is still pending.
+ if (terminalEvent === 'done') {
+ local.session.emitGoalTurn({
+ toolUse: true,
+ verdictJson: '```json\n{"goal_status":"continue","reason":"next"}\n```',
+ origin: 'goal',
+ });
+ } else {
+ local.session.emitErrorTurn({ message: 'goal turn failed' });
+ }
+ local.session.running = true;
+
+ await local.controller.clearGoal('s1');
+
+ expect(stopActiveGoalTurn).not.toHaveBeenCalled();
+ expect(await local.storage.get('s1')).toBeNull();
+ releaseFinalizeGet(active);
+ await tick();
+ },
+ );
+
+ it('does not re-mark a goal turn when its terminal event arrives before send resolves', async () => {
+ const stopActiveGoalTurn = vi.fn();
+ const local = makeController({ stopActiveGoalTurn });
+ let releaseFinalizeGet!: (state: GoalState | null) => void;
+ const blockedFinalizeGet = new Promise<GoalState | null>((resolve) => {
+ releaseFinalizeGet = resolve;
+ });
+ 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?.();
+ vi.spyOn(local.storage, 'get').mockImplementationOnce(() => blockedFinalizeGet);
+ local.session.emitGoalTurn({
+ toolUse: true,
+ verdictJson: '```json\n{"goal_status":"continue","reason":"next"}\n```',
+ origin: 'goal',
+ });
+ return { accepted: true };
+ });
+
+ await startGoal(local);
+ const active = seededGoal({ objective: 'make tests pass' });
+ local.session.running = true;
+
+ await local.controller.clearGoal('s1');
+
+ expect(stopActiveGoalTurn).not.toHaveBeenCalled();
+ expect(await local.storage.get('s1')).toBeNull();
+ releaseFinalizeGet(active);
+ await tick();
+ });
+
+ it('does not cancel the send signal after the goal crosses the dispatch boundary', async () => {
+ const local = makeController();
+ let releaseSend!: () => void;
+ const sendPending = new Promise<void>((resolve) => {
+ releaseSend = resolve;
+ });
+ let signal: AbortSignal | undefined;
+ 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 });
+ signal = opts?.signal;
+ opts?.onDispatching?.();
+ local.session.emitGoalTurn({
+ toolUse: true,
+ verdictJson: '```json\n{"goal_status":"complete","reason":"done"}\n```',
+ origin: 'goal',
+ });
+ await sendPending;
+ return signal?.aborted
+ ? { accepted: false, reason: 'cancelled-before-dispatch' }
+ : { accepted: true };
+ });
+
+ const setPromise = startGoal(local);
+ await vi.waitFor(() => expect(local.completions).toHaveLength(1));
+
+ expect(signal?.aborted).toBe(false);
+ releaseSend();
+ await setPromise;
+ expect(await local.storage.get('s1')).toBeNull();
+ });
+
+ it('clearGoal still removes persisted state when stopping the goal turn throws', async () => {
+ const local = makeController({
+ stopActiveGoalTurn: () => {
+ throw new Error('stop coordinator unavailable');
+ },
+ });
+ await startGoal(local);
+
+ await expect(local.controller.clearGoal('s1')).resolves.toBeUndefined();
+
+ expect(await local.storage.get('s1')).toBeNull();
+ expect(local.updates.at(-1)).toEqual({ sessionId: 's1', goal: null });
+ });
+
// ── updateGoal(纯代码改目标 / 上限,不写默认 override) ──
it('updateGoal resumes a budgetLimited max-turns goal when the new maxTurns allows more turns', async () => {
await h.storage.set(seededGoal({ status: 'budgetLimited', turnsUsed: 5, maxTurns: 5, lastReason: 'max turns reached' }));
diff --git a/apps/desktop/src/main/goal-host/controller.ts b/apps/desktop/src/main/goal-host/controller.ts
index ebdb124e7a..8ca329f494 100644
--- a/apps/desktop/src/main/goal-host/controller.ts
+++ b/apps/desktop/src/main/goal-host/controller.ts
@@ -359,6 +359,11 @@ export class GoalController {
private readonly turns = new Map<string, TurnAccumulator>();
/** 正在派发的 fire 及其 owner;旧代 finally 只能清理自己,不能删掉 Resume 新代。 */
private readonly firing = new Map<string, object>();
+ /** 尚在 Session.send 派发边界内的 Goal fire;Stop 必须能取消 dispatch 前的异步 gate。 */
+ private readonly goalDispatchAbortControllers = new Map<
+ string,
+ { owner: object; controller: AbortController }
+ >();
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
/** goal controller 自己发起且尚未收到终止事件的 turn。用于编辑时区分 goal turn / user turn。 */
private readonly goalTurnsInFlight = new Set<string>();
@@ -806,6 +811,10 @@ export class GoalController {
this.clarificationApplied.delete(sessionId);
this.consecutiveOverloadTurns.delete(sessionId);
this.cancelUsageResume(sessionId);
+ // 只中断 GoalController 自己发起的 turn。目标仍挂着时,用户可能已经让一条普通
+ // 消息进入队列;clear 必须保留它,并在旧 goal turn 终止后让 coordinator 正常
+ // drain。反过来,若当前跑的是用户 turn,清目标不应误停用户正在做的工作。
+ const hasActiveGoalTurn = this.goalTurnsInFlight.has(sessionId);
const previousBoundary = this.turns.get(sessionId);
this.stopSession(sessionId);
const clearBoundary = freshTurn(
@@ -814,6 +823,21 @@ export class GoalController {
previousBoundary?.pendingCompletion ?? null,
);
this.turns.set(sessionId, clearBoundary);
+ if (hasActiveGoalTurn) {
+ try {
+ // detach listener / 换 cancelled owner 必须早于 abort。否则 abort 的终态事件可能
+ // 被旧 Goal listener 消费,并与下面的 clear 持久化并发重建状态。生产依赖走
+ // input coordinator 的 Stop 边界,同时收口 vendor、输入锁和迟到事件。
+ this.deps.stopActiveGoalTurn(sessionId);
+ } catch (error) {
+ // 删除持久目标比中断回调更重要:即便停止协调器异常,也不能把 active 行留到
+ // 下次启动继续诈尸。异常留日志,存储 clear 仍继续执行。
+ this.deps.logger.warn('[goal] failed to stop active turn while clearing goal', {
+ sessionId,
+ error: String(error),
+ });
+ }
+ }
await this.awaitPendingLifecycle(clearBoundary);
if (this.turns.get(sessionId) !== clearBoundary) return;
await this.trackPersistence(clearBoundary, this.deps.storage.clear(sessionId));
@@ -1142,6 +1166,11 @@ export class GoalController {
clearTimeout(timer);
this.timers.delete(sessionId);
}
+ const pendingDispatch = this.goalDispatchAbortControllers.get(sessionId);
+ if (pendingDispatch) {
+ this.goalDispatchAbortControllers.delete(sessionId);
+ pendingDispatch.controller.abort();
+ }
this.firing.delete(sessionId);
this.goalTurnsInFlight.delete(sessionId);
this.turns.delete(sessionId);
@@ -1301,6 +1330,13 @@ export class GoalController {
return;
}
case 'done': {
+ // AgentInputCoordinator releases the input boundary on the same terminal
+ // event and may immediately start a queued user turn. Drop Goal ownership
+ // synchronously here, before finalizeTurn awaits storage, so Clear cannot
+ // mistake that new user turn for the completed Goal turn and abort it.
+ if (event.turnOrigin?.kind === 'goal') {
+ this.goalTurnsInFlight.delete(sessionId);
+ }
// Codex 的 per-turn 真实用量在 done.data.usage(promptTokens/completionTokens,
// 见 maker-core codex/index.ts task_complete:"永远是 per-turn 增量")。优先用它覆盖
// status 带来的累积上下文快照,避免 Codex 目标的 token 预算随上下文增长过早触顶。
@@ -1315,6 +1351,9 @@ export class GoalController {
}
default: {
if (isTerminalAgentErrorEvent(event)) {
+ if (event.turnOrigin?.kind === 'goal') {
+ this.goalTurnsInFlight.delete(sessionId);
+ }
void this.finalizeTurn(sessionId, event, true);
}
return;
@@ -1393,8 +1432,6 @@ export class GoalController {
? { errorKind: 'usage_limit' as const }
: {}),
};
- if (origin === 'goal') this.goalTurnsInFlight.delete(sessionId);
-
const decision = decideNextGoalState(
{
status: state.status,
@@ -1687,6 +1724,11 @@ export class GoalController {
}
const firingOwner = {};
this.firing.set(sessionId, firingOwner);
+ const dispatchAbortController = new AbortController();
+ this.goalDispatchAbortControllers.set(sessionId, {
+ owner: firingOwner,
+ controller: dispatchAbortController,
+ });
let dispatchBoundary: TurnAccumulator | undefined;
let dispatchGeneration: number | undefined;
const isCurrentDispatch = (): boolean =>
@@ -1753,7 +1795,24 @@ export class GoalController {
: { type: 'user' as const, content };
const result = await session.send(
outgoing as { type: 'user'; content: string },
- { origin: { kind: 'goal', goalSessionId: sessionId }, planMode: false },
+ {
+ origin: { kind: 'goal', goalSessionId: sessionId },
+ planMode: false,
+ // Session.send 只在 vendor dispatch 前的最后一个同步边界调用它。不能等
+ // send Promise 返回后才登记:派发调用尚未返回时用户点清除,clearGoal 必须
+ // 已经知道这个 turn 属于目标模式,才能立即走 Stop 边界。
+ onDispatching: () => {
+ if (!isCurrentDispatch()) return;
+ this.goalTurnsInFlight.add(sessionId);
+ // signal 只负责取消 dispatch 前的 gate。跨过这个边界后由 coordinator Stop
+ // 负责 active turn;否则快速终态的 stopSession 会把真实已派发轮次误报为
+ // cancelled-before-dispatch。
+ if (this.goalDispatchAbortControllers.get(sessionId)?.owner === firingOwner) {
+ this.goalDispatchAbortControllers.delete(sessionId);
+ }
+ },
+ signal: dispatchAbortController.signal,
+ },
);
if (pendingHandoff && result.accepted) {
agentHandoffPending.consume(sessionId);
@@ -1771,7 +1830,8 @@ export class GoalController {
baselineStarted = false;
return;
}
- this.goalTurnsInFlight.add(sessionId);
+ // onDispatching 是归属登记的唯一边界。不能在 await send 后再次 add:极快的
+ // turn 可能已经发出终态并同步释放归属,重新登记会把后续用户 turn 误认成 Goal。
baselineStarted = false;
}
} catch (e) {
@@ -1786,6 +1846,9 @@ export class GoalController {
this.deps.logger.warn('[goal] fireTurn send failed', { sessionId, kind, error: String(e) });
} finally {
releaseAgentSwitchLock();
+ if (this.goalDispatchAbortControllers.get(sessionId)?.owner === firingOwner) {
+ this.goalDispatchAbortControllers.delete(sessionId);
+ }
if (this.firing.get(sessionId) === firingOwner) {
this.firing.delete(sessionId);
}
diff --git a/apps/desktop/src/main/goal-host/index.ts b/apps/desktop/src/main/goal-host/index.ts
index 5ae3e9da95..33d465d074 100644
--- a/apps/desktop/src/main/goal-host/index.ts
+++ b/apps/desktop/src/main/goal-host/index.ts
@@ -14,6 +14,7 @@ import { createLogger } from '../logger.js';
import {
acquirePendingAgentSwitchForDirectSend,
isSessionInTurn,
+ stopActiveGoalTurnForClear,
} from '../maker-ipc/register.js';
import { createMessage } from '../localDb/ipc/messages.js';
import { readGoalSettings, writeGoalSettings } from '../maker-host/goal-settings-store.js';
@@ -51,6 +52,7 @@ export function startGoalController(deps: StartGoalControllerDeps): GoalControll
}),
acquirePendingAgentSwitch: acquirePendingAgentSwitchForDirectSend,
isSessionInTurn,
+ stopActiveGoalTurn: stopActiveGoalTurnForClear,
beforeDispatchUserTurn: deps.beforeDispatchUserTurn,
onUndispatchedUserTurn: deps.onUndispatchedUserTurn,
emitStatus: deps.broadcastStatus,
diff --git a/apps/desktop/src/main/goal-host/types.ts b/apps/desktop/src/main/goal-host/types.ts
index f8b7520942..4f86a72bfa 100644
--- a/apps/desktop/src/main/goal-host/types.ts
+++ b/apps/desktop/src/main/goal-host/types.ts
@@ -145,6 +145,7 @@ export interface SessionLike {
origin?: SendOrigin;
planMode?: boolean;
onAccepted?: () => void | Promise<void>;
+ onDispatching?: () => void;
signal?: AbortSignal;
},
): Promise<SessionSendResult>;
@@ -183,6 +184,11 @@ export interface GoalControllerDeps {
acquirePendingAgentSwitch?: (sessionId: string) => Promise<() => void>;
/** ← maker-ipc/register.isSessionInTurn(main 侧 turn 活跃跟踪)。 */
isSessionInTurn(sessionId: string): boolean;
+ /**
+ * 清除目标时中断由 GoalController 发起的当前 turn。生产环境接到 input coordinator
+ * 的 Stop 边界,以便 vendor abort、输入队列和迟到终态事件一起收口。
+ */
+ stopActiveGoalTurn(sessionId: string): void;
beforeDispatchUserTurn?: (sessionId: string) => void | Promise<void>;
onUndispatchedUserTurn?: (sessionId: string) => void;
/** 状态变化广播到 renderer(→ GOAL_STATUS_CHANGED);goal=null 表示已清除。 */
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 dcacc291c4..afa6f18d03 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
@@ -1376,6 +1376,36 @@ describe('AgentInputCoordinator send transaction', () => {
}
});
+ it('keeps queued user input runnable while stopping an external goal turn for clear', async () => {
+ const h = createHarness();
+ const sid = 'clear-external-goal-turn';
+ const queued = makeItem('q-1', 'adjust the goal direction');
+
+ // Goal turns bypass the coordinator, so the host is busy while activeTurn stays null.
+ h.setRunning(true);
+ h.coordinator.enqueue(sid, queued);
+ await flush();
+
+ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: false });
+
+ expect(h.abortSession).toHaveBeenCalledWith(sid);
+ expect(latestProjection(h.projections)).toMatchObject({
+ queuePaused: false,
+ pendingQueue: [expect.objectContaining({ clientId: 'q-1' })],
+ });
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'done');
+ await flush();
+
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ expect(h.sendToAgent.mock.calls[0]?.[1]).toEqual({
+ type: 'user',
+ content: 'adjust the goal direction',
+ });
+ });
+
it('replaces a stale retry timer before it fires after a generation change', async () => {
vi.useFakeTimers();
try {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index b5fc34fc05..57d27bbf3e 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -2124,6 +2124,21 @@ export async function withSendToSessionLock<T>(
}
let agentInputCoordinatorHolder: AgentInputCoordinator | null = null;
+
+/**
+ * GoalController 已确认当前 turn 归自己所有后调用:复用输入协调器的 Stop 边界中断
+ * vendor,同时保留用户已经排队的新指令并在终态收口后继续派发。
+ *
+ * 这里不判断 goal ownership,避免 register 反向依赖 goal-host;调用方必须先完成判定。
+ */
+export function stopActiveGoalTurnForClear(sessionId: string): void {
+ const coordinator = agentInputCoordinatorHolder;
+ if (!coordinator) {
+ throw new Error('Agent input coordinator is not initialized');
+ }
+ coordinator.stop(sessionId, { keepQueue: true, pauseQueue: false });
+}
+
const rewindInputSessions = new Set<string>();
const SESSION_REWIND_INPUT_LOCK_ID = 'session-rewind';
const SESSION_REWIND_STOP_TIMEOUT_MS = 15_000;