/** * ============================================================ * src/messageQueue.ts —— 用户输入队列(支持优先级) * ------------------------------------------------------------ * 实现对话进行中用户插话的排队管理。 * * 设计原则: * - 极简:只保留 minimal-agent 需要的核心功能 * - 发布订阅:subscribe() 订阅队列变化,用于UI更新 * - 工厂函数:createInputQueue() 创建独立实例,支持多session/测试 * - 两级优先级:'now'(立即处理)> 'next'(排队等待) * ============================================================ */ export type QueuePriority = 'now' | 'next'; export interface QueuedInput { id: string; value: string; priority: QueuePriority; timestamp: number; } export interface InputQueue { enqueue(value: string, priority?: QueuePriority): void; dequeue(): QueuedInput | undefined; dequeueAll(): QueuedInput[]; peek(): QueuedInput | undefined; clear(): void; size(): number; subscribe(callback: () => void): () => void; getSnapshot(): readonly QueuedInput[]; } function randomUUID(): string { if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) { return crypto.randomUUID(); } return `q_${Date.now()}_${Math.random().toString(36).slice(2)}`; } export function createInputQueue(): InputQueue { const queue: QueuedInput[] = []; const subscribers = new Set<() => void>(); function notify(): void { for (const cb of subscribers) { cb(); } } function findBestIndex(): number { let bestIdx = 0; let bestPrio = 99; for (let i = 0; i < queue.length; i++) { const p = queue[i]!.priority === 'now' ? 0 : 1; if (p < bestPrio) { bestPrio = p; bestIdx = i; } } return bestIdx; } return { enqueue(value, priority = 'next') { queue.push({ id: randomUUID(), value, priority, timestamp: Date.now(), }); notify(); }, dequeue() { if (queue.length === 0) return undefined; const bestIdx = findBestIndex(); const item = queue.splice(bestIdx, 1)[0]; if (item) notify(); return item; }, dequeueAll() { if (queue.length === 0) return []; const sorted = [...queue].sort((a, b) => { const pa = a.priority === 'now' ? 0 : 1; const pb = b.priority === 'now' ? 0 : 1; if (pa !== pb) return pa - pb; return a.timestamp - b.timestamp; }); queue.length = 0; notify(); return sorted; }, peek() { if (queue.length === 0) return undefined; return queue[findBestIndex()]; }, clear() { if (queue.length === 0) return; queue.length = 0; notify(); }, size() { return queue.length; }, subscribe(callback) { subscribers.add(callback); return () => { subscribers.delete(callback); }; }, getSnapshot() { return Object.freeze([...queue]); }, }; }