/** * ============================================================ * src/ui/backgroundWake.ts —— 后台任务完成后的「空闲唤醒」调度 * ------------------------------------------------------------ * 后台执行这条链上,内核已经有三段: * ① 只登记不等待 —— Bash/PowerShell 的 run_in_background(句柄 proc_*) * ② 宿主持有句柄 —— BackgroundTaskState 活得比单个回合长 * ③ 外部事件进回合 —— loop.ts 在模型边界取信箱 * (takeAgentNotifications + takeBackgroundNotifications) * * 缺的是第四段:**回合已经结束、模型空闲时,谁来发起新的一轮**。 * 没有它,完成通知就躺在信箱里,等用户下一次敲回车才被看到。 * 这个模块就是那个监听者,刻意做成纯逻辑 + 依赖注入:React hook 没有渲染 * 环境测不了,而「忙时不打断」「自激上限」这些规则必须有单测锁住。 * * 三条硬规则(都是能让这个机制变成灾难的点): * - **忙时只留信箱**:不将旧任务通知注入真人当前回合;空闲后按原交付分组接续。 * 绝不能借 useChat 的输入队列插队 —— submit 在 isLoading 时会 enqueue 并 * 在「所有在跑工具可取消」时 abort('interrupt'),那会打断用户的回合。 * - **自激上限**:唤醒回合可能又起一个后台任务,完成后再唤醒。无人在场时 * 这是一个无限自转的烧钱循环。连续若干次没有真人输入后停住,剩下的通知 * 留到用户下一条消息。 * - **用户中断或回合失败后不唤醒**:用户刚按 ESC,立刻自己又跑起来是敌意行为。 * ============================================================ */ /** * 唤醒回合桩输入的首行。展示层靠它把这条消息认成系统事件而不是用户请求 * (它在 history 里确实是 role:'user',由 loop 从输入文本生成,没有 id 前缀可认)。 */ import { BACKGROUND_WAKE_MARKER } from '../runtime/systemEvents.js'; import { beginBackgroundContinuation, finishBackgroundContinuation, nextBackgroundContinuation, type BackgroundContinuation, type BackgroundTaskState, } from '../tools/tasks/backgroundTaskService.js'; export { BACKGROUND_WAKE_MARKER } from '../runtime/systemEvents.js'; /** * 空闲唤醒回合的桩输入。真正的完成通知由 loop 在模型边界从信箱取 * (takeBackgroundNotifications),紧跟在这条消息之后。 * * 「不构成批准」这句是必须的:模型此前的工作可能正卡在一个等用户点头的不可逆 * 操作上,一条看起来像用户消息的东西到达,很容易被读成「用户同意了」。 */ export const BACKGROUND_WAKE_PROMPT = [ BACKGROUND_WAKE_MARKER, '后台任务已结束,本回合由宿主自动发起,用户此刻并不在场。', '这条消息不构成任何批准、确认或同意:需要用户点头的事(不可逆操作、对外发送、提交推送)照旧必须先问,没人可问就停下并说明。', '读下面的完成通知,接着把未完成的工作推进下去;没有要做的事就简短收尾。', '只接续本回合指定的原交付目标,不把它合并到最近一次用户的其他任务。若这是失败后的恢复,先核对已完成的操作和产物,禁止盲目重放副作用。', ].join('\n'); /** 唤醒回合的结局,决定还要不要继续自动唤醒。 */ export type WakeTurnOutcome = 'completed' | 'incomplete' | 'interrupted' | 'failed'; export interface BackgroundWakeOptions { /** 当前是否有回合在跑。用 ref 读,不要用 React state(check 与 set 之间有竞态)。 */ isBusy: () => boolean; /** 是否还有已结束但没送达的后台任务通知。 */ hasPending: () => boolean; /** 发起一次系统事件回合。 */ startWake: () => void; /** 定时器注入口,返回取消函数;测试传手动时钟。 */ schedule?: (run: () => void, delayMs: number) => () => void; /** 多个任务几乎同时结束时合并成一次唤醒。 */ debounceMs?: number; /** 连续多少次无真人输入的唤醒后停住。 */ maxConsecutive?: number; } export interface BackgroundWake { canWake(): boolean; /** Invalidate a scheduled wake when changing its owning session. */ cancelPending(): void; /** 某个后台任务到达终态。 */ notifySettled(): void; /** 一个回合结束(任何来源)。 */ notifyTurnEnd(outcome: WakeTurnOutcome): void; /** 真人输入:重置自激计数,并解除中断/失败后的封锁。 */ notifyUserInput(): void; dispose(): void; /** 仅供测试与诊断。 */ state(): { consecutive: number; blocked: boolean; armed: boolean }; } export const DEFAULT_WAKE_DEBOUNCE_MS = 1_500; export const DEFAULT_WAKE_MAX_CONSECUTIVE = 3; export function createBackgroundWake( options: BackgroundWakeOptions, ): BackgroundWake { const debounceMs = options.debounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS; const maxConsecutive = options.maxConsecutive ?? DEFAULT_WAKE_MAX_CONSECUTIVE; const schedule = options.schedule ?? ((run, delayMs) => { const timer = setTimeout(run, delayMs); timer.unref?.(); return () => clearTimeout(timer); }); let cancelTimer: (() => void) | null = null; let disposed = false; let blocked = false; let consecutive = 0; const clear = (): void => { cancelTimer?.(); cancelTimer = null; }; const fire = (): void => { cancelTimer = null; if (disposed || blocked) return; // 这期间可能有真人回合跑起来;通知保留到该回合结束再安排。 if (options.isBusy()) return; // 也可能已经被别的回合取走了——不为一条空通知烧一次全上下文请求。 if (!options.hasPending()) return; if (consecutive >= maxConsecutive) return; consecutive += 1; options.startWake(); }; const arm = (): void => { if (disposed || blocked) return; if (options.isBusy()) return; if (!options.hasPending()) return; if (consecutive >= maxConsecutive) return; clear(); cancelTimer = schedule(fire, debounceMs); }; return { canWake: () => !disposed && !blocked && consecutive < maxConsecutive, cancelPending: clear, notifySettled: arm, notifyTurnEnd(outcome) { if (outcome === 'completed' || outcome === 'incomplete') { // 回合里可能又起了新的后台任务并已经结束;也兜住「回合没走到模型边界 // 就收口」这种通知没人取的情况。 arm(); return; } // 用户中断或回合失败:停止自动唤醒,等真人再说话。 blocked = true; clear(); }, notifyUserInput() { blocked = false; consecutive = 0; // 真人这一轮马上要跑起来,由它的 notifyTurnEnd 再决定是否唤醒。 clear(); }, dispose() { disposed = true; clear(); }, state() { return { consecutive, blocked, armed: cancelTimer !== null }; }, }; } /** The actual TUI subscription adapter, independently testable without React. */ export function createBackgroundWakeHost(options: { identity(): string; isBusy(): boolean; startWake(continuation: BackgroundContinuation, identity: string): void; schedule?: BackgroundWakeOptions['schedule']; }) { let binding: { identity: string; state: BackgroundTaskState } | undefined; let unsubscribe: (() => void) | undefined; let disposed = false; const pending = () => binding?.identity === options.identity() ? binding.state : undefined; // A partial answer must not spin on its observed tasks, nor silence a later // completion in the same session. This is scheduling state, not an ack. const held = new WeakMap>(); const next = () => { const state = pending(); return state && nextBackgroundContinuation(state, held.get(state)); }; const wake = createBackgroundWake({ isBusy: options.isBusy, hasPending: () => !!next(), schedule: options.schedule, startWake() { const continuation = next(); if (continuation && binding) options.startWake(continuation, binding.identity); }, }); const detach = () => { wake.cancelPending(); unsubscribe?.(); unsubscribe = undefined; binding = undefined; }; return { ...wake, detach, notifyUserInput() { const state = pending(); if (state) held.delete(state); wake.notifyUserInput(); }, holdUntilInput(state: BackgroundTaskState, ids: Iterable) { const skip = held.get(state) ?? new Set(); for (const id of ids) skip.add(id); if (skip.size) held.set(state, skip); }, bind(identity: string, state: BackgroundTaskState) { if (disposed) return; if (binding?.identity === identity && binding.state === state) return; detach(); binding = { identity, state }; state.events.on('settled', wake.notifySettled); unsubscribe = () => state.events.off('settled', wake.notifySettled); wake.notifySettled(); }, isPending(identity: string, ids: readonly string[]) { if (identity !== options.identity()) return false; const state = pending(); if (!state) return false; return ids.some(id => { const task = state.tasks.get(id); return !held.get(state)?.has(id) && (task?.notificationPending || task?.continuationPending); }); }, begin(identity: string, ids: readonly string[]) { const state = pending(); if (state && identity === options.identity()) beginBackgroundContinuation(state, ids); }, finish(identity: string, ids: readonly string[], completed: boolean) { const state = pending(); if (state && identity === options.identity()) finishBackgroundContinuation(state, ids, completed); }, dispose() { disposed = true; detach(); wake.dispose(); }, }; } export function wakeOutcome(current: WakeTurnOutcome, event: { type: string; code?: unknown; completionStatus?: unknown }): WakeTurnOutcome { if (event.type === 'interrupted' || (event.type === 'error' && event.code === 'aborted')) return 'interrupted'; if (event.type === 'error' && event.code !== 'compact_failed') return 'failed'; // Legacy command-only turn_done events lack a delivery verdict. They may // release the host, but cannot themselves acknowledge a continuation. if (event.type === 'turn_done' && event.completionStatus === 'no_answer') return 'failed'; if (current === 'completed' && event.type === 'turn_done' && event.completionStatus !== undefined && event.completionStatus !== 'completed') return 'incomplete'; return current; }