Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(voice): Optimus questions no longer stall behind other work
Salman Qureshi7cbd8ac465da
diff --git a/src/core/agent.ts b/src/core/agent.tsindex cf01487c..4283c407 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1063,10 +1063,30 @@ export class Agent {queueMessage(message: ChannelMessage, workKey?: string): void {if (workKey && this.queuedWorkKeys.has(workKey)) return;- this.messageQueue.push({ message, workKey });+ // Someone is waiting on the line: a question asked on a call goes ahead+ // of queued chat work (behind earlier call questions, in order).+ if (message.metadata?.voiceCall === true) {+ let at = 0;+ while (at < this.messageQueue.length && this.messageQueue[at].message.metadata?.voiceCall === true) at++;+ this.messageQueue.splice(at, 0, { message, workKey });+ } else {+ this.messageQueue.push({ message, workKey });+ }if (workKey) this.queuedWorkKeys.add(workKey);}+ /**+ * Where work for one channel stands: running now, waiting in the queue,+ * or neither; and what Mercury is busy with when it's something else.+ */+ workStateFor(channelId: string): { state: 'running' | 'queued' | 'none'; busyWith?: string } {+ const current = this.currentMessage?.channelId;+ if (this.processing && current === channelId) return { state: 'running' };+ const busyWith = this.processing && current ? (this.currentActivity || 'another task').replace(/^\W+/u, '').trim() || 'another task' : undefined;+ if (this.messageQueue.some((i) => i.message.channelId === channelId)) return { state: 'queued', busyWith };+ return { state: 'none', busyWith };+ }+private async handleDuplicateWork(entry: WorkEntry): Promise<void> {if (entry.status === 'completed' && !entry.delivered && entry.finalResponse) {await this.deliverLedgerEntry(entry);@@ -4805,9 +4825,15 @@ export class Agent {* queued for it. Other chats keep going. Returns whether anything stopped.*/stopWorkFor(channelPrefix: string, reason = 'Stopped by the owner.'): boolean {- const before = this.messageQueue.length;+ const dropped = this.messageQueue.filter((i) => i.message.channelId.startsWith(channelPrefix));this.messageQueue = this.messageQueue.filter((i) => !i.message.channelId.startsWith(channelPrefix));- let stopped = this.messageQueue.length !== before;+ // Never started: cancel them, or a restart would run them after all.+ for (const item of dropped) {+ if (!item.workKey) continue;+ this.queuedWorkKeys.delete(item.workKey);+ try { this.workLedger.markCancelled(item.workKey, reason); } catch { /* entry may not exist */ }+ }+ let stopped = dropped.length > 0;if (this.currentMessage?.channelId.startsWith(channelPrefix) && this.currentAbort && !this.currentAbort.signal.aborted) {this.currentAbortReason = 'stopped';this.currentAbort.abort();diff --git a/src/core/voice-queue.test.ts b/src/core/voice-queue.test.tsnew file mode 100644index 00000000..9d7af863--- /dev/null+++ b/src/core/voice-queue.test.ts@@ -0,0 +1,68 @@+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import type { ChannelMessage } from '../types/channel.js';+import { Agent } from './agent.js';+import { WorkLedger } from './work-ledger.js';++/**+ * Questions asked on a call: someone is waiting on the line, so they go+ * ahead of queued chat work, and stopping the call cancels the ones that+ * never started (or a restart would run them after all).+ */++const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function msg(id: string, channelId: string, voiceCall = false): ChannelMessage {+ return { id, channelId, channelType: channelId.split(':')[0] as ChannelMessage['channelType'], senderId: 'local', content: id, timestamp: 1, metadata: voiceCall ? { voiceCall: true } : {} };+}++function bareAgent() {+ const dir = mkdtempSync(join(tmpdir(), 'mercury-voice-queue-'));+ dirs.push(dir);+ const workLedger = new WorkLedger({ filePath: join(dir, 'work-ledger.json') });+ const agent = Object.create(Agent.prototype) as Agent;+ Object.assign(agent, { messageQueue: [], queuedWorkKeys: new Set(), workLedger, processing: false, currentMessage: null, currentActivity: '', currentAbort: null });+ const enqueue = (m: ChannelMessage) => { const key = workLedger.accept(m).entry.key; agent.queueMessage(m, key); return key; };+ const order = () => (agent as unknown as { messageQueue: Array<{ message: ChannelMessage }> }).messageQueue.map((i) => i.message.id);+ return { agent, workLedger, enqueue, order };+}++describe('voice questions in the work queue', () => {+ it('go ahead of queued chat work, in the order they were asked', () => {+ const { agent, enqueue, order } = bareAgent();+ enqueue(msg('chat1', 'web:a'));+ enqueue(msg('chat2', 'web:b'));+ enqueue(msg('voice1', 'desktop:call:x', true));+ enqueue(msg('voice2', 'desktop:call:x', true));+ expect(order()).toEqual(['voice1', 'voice2', 'chat1', 'chat2']);+ expect(agent.workStateFor('desktop:call:x').state).toBe('queued');+ expect(agent.workStateFor('web:c').state).toBe('none');+ });++ it('say what Mercury is busy with when it is something else', () => {+ const { agent, enqueue } = bareAgent();+ enqueue(msg('voice1', 'desktop:call:x', true));+ Object.assign(agent, { processing: true, currentMessage: msg('long', 'web:a'), currentActivity: '📄 Reading report.md' });+ expect(agent.workStateFor('desktop:call:x')).toEqual({ state: 'queued', busyWith: 'Reading report.md' });+ Object.assign(agent, { currentMessage: msg('voice1', 'desktop:call:x', true) });+ expect(agent.workStateFor('desktop:call:x').state).toBe('running');+ });++ it('stopping a call cancels its queued questions, so a restart never replays them', () => {+ const { agent, workLedger, enqueue, order } = bareAgent();+ const chat = enqueue(msg('chat1', 'web:a'));+ const v1 = enqueue(msg('voice1', 'desktop:call:x', true));+ const v2 = enqueue(msg('voice2', 'desktop:call:x', true));+ expect(agent.stopWorkFor('desktop:call:x')).toBe(true);+ expect(order()).toEqual(['chat1']);+ expect(workLedger.get(v1)?.status).toBe('cancelled');+ expect(workLedger.get(v2)?.status).toBe('cancelled');+ expect(workLedger.get(chat)?.status).toBe('queued');+ // The same question asked again can be queued afresh.+ agent.queueMessage(msg('voice1', 'desktop:call:x', true), v1);+ expect(order()).toEqual(['voice1', 'chat1']);+ });+});diff --git a/src/index.ts b/src/index.tsindex 16be05e9..4054bd97 100644--- a/src/index.ts+++ b/src/index.ts@@ -56,7 +56,7 @@ import { buildConversationHistoryPayload, CloudSessionSynchronizer, SessionReposimport { UserMemoryStore } from './memory/user-memory.js';import { BotManager } from './bots/bot-manager.js';import { getPluginManager, peekPluginManager, setProviderLookup } from './plugins/manager.js';-import { setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing, setWorkStopper } from './plugins/channel-bridge.js';+import { setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing, setWorkProbe, setWorkStopper } from './plugins/channel-bridge.js';import { registerPluginsCli } from './cli/plugins-cli.js';import { PersonVerifier, personCheckPrompt, parsePersonCheck } from './memory/person-verifier.js';import { setPersonVerifier } from './web/api/brain.js';@@ -2732,6 +2732,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {setVoiceBriefing(() => agent.voiceBriefing());setCallLearning((ownerSaid, mercurySaid) => agent.learnFromConversation(ownerSaid, mercurySaid));setWorkStopper((prefix) => agent.stopWorkFor(prefix, 'Stopped by the owner on a voice call.'));+ setWorkProbe((channelId) => agent.workStateFor(channelId));setDesktopActivityHook((label) => {const cli = channels.get('cli');if (cli instanceof CLIChannel) cli.setDesktopActivity(label);diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.tsindex babfd639..80058d73 100644--- a/src/plugins/channel-bridge.ts+++ b/src/plugins/channel-bridge.ts@@ -365,20 +365,35 @@ export class PluginChannel extends BaseChannel {clearTimeout(previous.timer);previous.resolve('(superseded by a newer question)');}- const giveUp = () => {+ const chat = this.desktop ? 'your Mercury chat' : 'WhatsApp';+ const channelId = `${this.type}:${target}`;+ const giveUp = (message: string) => {+ this.callAsks.delete(target);+ this.overflow.add(target);+ resolve(message);+ };+ const tooLong = () => {// Waiting on the owner's approval isn't "stuck": keep the question open.if ([...this.callApprovals.values()].some((a) => a.callId === callId)) {const entry = this.callAsks.get(target);- if (entry) entry.timer = setTimeout(giveUp, 30_000);+ if (entry) entry.timer = setTimeout(tooLong, 30_000);return;}- this.callAsks.delete(target);- this.overflow.add(target);- resolve(this.desktop- ? 'Mercury is still working on that. It will send the answer to your Mercury chat when it\'s done.'- : 'Mercury is still working on that. It will send the answer to WhatsApp when it\'s done.');+ const work = workProbe?.(channelId);+ giveUp(work?.state === 'queued'+ ? `Mercury hasn't started that yet: it's still busy with another task (${work.busyWith ?? 'another task'}). Your question is next, and the answer will go to ${chat}.`+ : `Mercury is still working on that. It will send the answer to ${chat} when it's done.`);+ };+ // Stuck behind other work: say so early, instead of a long silence.+ const behind = () => {+ const work = workProbe?.(channelId);+ const entry = this.callAsks.get(target);+ if (work?.state !== 'queued' || entry?.resolve !== resolve) return;+ clearTimeout(entry.timer);+ giveUp(`Mercury hasn't started that yet: it's busy finishing another task (${work.busyWith ?? 'another task'}). Your question is next in line, and the answer will go to ${chat}.`);};- const timer = setTimeout(giveUp, 90_000);+ const timer = setTimeout(tooLong, 90_000);+ setTimeout(behind, behindMs);this.callAsks.set(target, { chunks: [], resolve, timer });const files = this.activeCalls.get(callId)?.files ?? [];const sentNote = files.length@@ -432,7 +447,20 @@ export class PluginChannel extends BaseChannel {try { learnFromCall(said.slice(0, 6000), replied.slice(0, 6000)); } catch { /* best effort */ }}}- this.activeCalls.delete(String(p.callId ?? ''));+ const endedId = String(p.callId ?? '');+ this.activeCalls.delete(endedId);+ // Nobody is on the line any more: end the work the call started, unless+ // its answer was already promised to the chat.+ const target = `call:${endedId}`;+ if (endedId && !this.overflow.has(target)) {+ workStopper?.(`${this.type}:${target}`);+ const ask = this.callAsks.get(target);+ if (ask) {+ clearTimeout(ask.timer);+ this.callAsks.delete(target);+ ask.resolve('(the call ended)');+ }+ }if (this.desktop) voiceFeed.ended(String(p.callId ?? ''), String(p.outcome ?? 'ended'));for (const [id, a] of this.callApprovals) if (a.callId === String(p.callId ?? '')) this.resolveCallApproval(id, 'no', 'timeout');const secs = typeof p.durationSec === 'number' ? Math.round(p.durationSec) : 0;@@ -854,6 +882,15 @@ export function setWorkStopper(fn: ((channelPrefix: string) => boolean) | null):workStopper = fn;}+let workProbe: ((channelId: string) => { state: 'running' | 'queued' | 'none'; busyWith?: string }) | null = null;+/** Where a call question's work stands (agent.workStateFor), to explain a wait honestly. */+/** A call question still not started after this long is waiting behind other work. */+let behindMs = 12_000;+export function setWorkProbe(fn: typeof workProbe, waitMs = 12_000): void {+ workProbe = fn;+ behindMs = waitMs;+}+let desktopActivityHook: ((label: string | null) => void) | null = null;/** Where desktop activity is shown (the TUI status bar). */export function setDesktopActivityHook(fn: ((label: string | null) => void) | null): void {diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.tsindex e4b71ad1..e53e3eda 100644--- a/src/plugins/channel.test.ts+++ b/src/plugins/channel.test.ts@@ -7,7 +7,7 @@ import type { Channel } from '../channels/base.js';import type { ChannelMessage } from '../types/channel.js';import { PluginManager, setProviderLookup } from './manager.js';import { PluginChannel } from './channel-bridge.js';-import { activityLabel, getPluginChannel, setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing, setWorkStopper, splitMessage, spokenPart, toWhatsAppText, voiceBriefing } from './channel-bridge.js';+import { activityLabel, getPluginChannel, setCallLearning, setChannelHost, setDesktopActivityHook, setVoiceBriefing, setWorkProbe, setWorkStopper, splitMessage, spokenPart, toWhatsAppText, voiceBriefing } from './channel-bridge.js';import { getPluginTools, resetToolBridge } from './tool-bridge.js';import { pluginDataDir } from './store.js';import { manifestSchema } from './types.js';@@ -582,6 +582,54 @@ describe('plugin channels (plugin API 1.1)', () => {}});+ it('a question stuck behind other work says so early, and the answer goes to the chat', async () => {+ setWorkProbe(() => ({ state: 'queued', busyWith: 'Rendering the promo video' }), 60);+ try {+ const ch = await installDesktop();+ await callsim('mercury/call/ask', { callId: 'q1', question: 'Search Twitter for Mercury' });+ await waitFor(() => lines('replies.jsonl').length === 1);+ expect(lines('replies.jsonl')[0].result.answer).toMatch(/hasn't started that yet[\s\S]*Rendering the promo video[\s\S]*Mercury chat/);+ await ch.send('Found 12 mentions.', 'desktop:call:q1');+ expect(notices.some((n) => /From your call[\s\S]*12 mentions/.test(n))).toBe(true);+ } finally {+ setWorkProbe(null);+ }+ });++ it('a question already running is left to finish', async () => {+ setWorkProbe(() => ({ state: 'running' }), 30);+ try {+ const ch = await installDesktop();+ await callsim('mercury/call/ask', { callId: 'q2', question: 'Open Gmail' });+ await waitFor(() => received.length === 1);+ await sleep(120);+ expect(lines('replies.jsonl')).toEqual([]);+ await ch.send('Gmail is open.', 'desktop:call:q2');+ ch.endTask('desktop:call:q2');+ await waitFor(() => lines('replies.jsonl').length === 1);+ expect(lines('replies.jsonl')[0].result.answer).toBe('Gmail is open.');+ } finally {+ setWorkProbe(null);+ }+ });++ it('when the session ends, the work it started stops (unless promised to the chat)', async () => {+ const stoppedFor: string[] = [];+ setWorkStopper((prefix) => { stoppedFor.push(prefix); return true; });+ try {+ await installDesktop();+ await callsim('mercury/call/ask', { callId: 'e1', question: 'Check my calendar' });+ await waitFor(() => received.length === 1);+ const end = getPluginTools(new PermissionManager())['optimus__callend'] as Tool & { execute: (a: unknown, o: unknown) => Promise<unknown> };+ await end.execute({ callId: 'e1', direction: 'incoming', outcome: 'completed', durationSec: 20, transcript: [] }, { toolCallId: 't', messages: [] });+ await waitFor(() => lines('replies.jsonl').length === 1);+ expect(lines('replies.jsonl')[0].result.answer).toBe('(the call ended)');+ expect(stoppedFor).toEqual(['desktop:call:e1']);+ } finally {+ setWorkStopper(null);+ }+ });+it('approvals are asked out loud only', async () => {const ch = await installDesktop();const answer = ch.askPermission('Submit the job application', 'desktop:call:d3');