Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(chat): a chat that waits for another says so

Salman Qureshi334ce01a61b9
diff --git a/src/channels/web.ts b/src/channels/web.ts
index 40bea138..a4efa269 100644
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@ -21,7 +21,7 @@ interface PendingInteraction {
}
export interface ChatEvent {
- type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched';
+ type: 'activity' | 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched' | 'queued';
data?: Record<string, unknown>;
}
@@ -185,6 +185,16 @@ export class WebChannel extends BaseChannel {
* attached terminal kept streaming the old id: replies to the new session
* never reached it, and it showed "Thinking" forever.
*/
+ /**
+ * This chat's message is waiting: Mercury runs one turn at a time, and
+ * another one (`busySessionId`, doing `busyWith`) is ahead of it. Sent when it
+ * joins the line and whenever the line moves; the turn's own events follow
+ * when it starts.
+ */
+ sendQueued(targetId: string, data: { position: number; busyWith?: string; busySessionId?: string }): void {
+ this.broadcast({ type: 'queued', data: { targetId, ...data } });
+ }
+
sendSessionSwitched(targetId: string, session: { id: string; shortId: string; alias: string; title: string }): void {
this.broadcast({ type: 'session_switched', data: { targetId, id: session.id, shortId: session.shortId, alias: session.alias, title: session.title } });
}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 44216440..4b493517 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -1076,6 +1076,49 @@ export class Agent {
this.messageQueue.push({ message, workKey });
}
if (workKey) this.queuedWorkKeys.add(workKey);
+ this.announceQueue();
+ }
+
+ /**
+ * Tell every waiting desktop/web chat where it stands: its place in line,
+ * and the turn running now (which chat, and what it's doing). Without this
+ * a waiting chat showed "Thinking" for a turn that hadn't started.
+ */
+ private announceQueue(running: ChannelMessage | null = this.processing ? this.currentMessage : null): void {
+ if (!running) return;
+ const web = this.channels.get('web' as any) as { sendQueued?: (t: string, d: { position: number; busyWith?: string; busySessionId?: string }) => void } | undefined;
+ if (!web?.sendQueued) return;
+ const busyWith = (this.currentActivity && this.currentMessage === running ? this.currentActivity : running.content)
+ .replace(/^\W+/u, '').replace(/\s+/g, ' ').trim().slice(0, 90) || 'another task';
+ const busySessionId = running.channelType === 'web' ? running.channelId : undefined;
+ this.messageQueue.forEach((item, i) => {
+ const m = item.message;
+ if (m.channelType !== 'web' || m.channelId === busySessionId) return;
+ web.sendQueued!(m.channelId, { position: i + 1, busyWith, busySessionId });
+ });
+ }
+
+ /** Where one chat's work stands, for a chat opened while it waits. */
+ queueStateFor(channelId: string): { state: 'running' | 'queued' | 'none'; position?: number; busyWith?: string; busySessionId?: string } {
+ if (this.processing && this.currentMessage?.channelId === channelId) return { state: 'running' };
+ const at = this.messageQueue.findIndex((i) => i.message.channelId === channelId);
+ if (at === -1) return { state: 'none' };
+ const running = this.processing ? this.currentMessage : null;
+ return {
+ state: 'queued',
+ position: at + 1,
+ busyWith: running ? (this.currentActivity || running.content).replace(/\s+/g, ' ').trim().slice(0, 90) : undefined,
+ busySessionId: running?.channelType === 'web' ? running.channelId : undefined,
+ };
+ }
+
+ /** "Do mine first": this chat's waiting messages move to the front of the line (in their order). */
+ prioritize(channelId: string): number {
+ const mine = this.messageQueue.filter((i) => i.message.channelId === channelId);
+ if (mine.length === 0) return 0;
+ this.messageQueue = [...mine, ...this.messageQueue.filter((i) => i.message.channelId !== channelId)];
+ this.announceQueue();
+ return mine.length;
}
/** Is a turn for this session running, or waiting in the queue? */
@@ -1902,6 +1945,8 @@ export class Agent {
const item = this.messageQueue.shift()!;
const msg = item.message;
if (item.workKey) this.queuedWorkKeys.delete(item.workKey);
+ // The line moved: everyone still waiting learns their new place and what runs now.
+ this.announceQueue(msg);
this.currentWorkKey = item.workKey ?? null;
try {
if (item.workKey) this.workLedger.markRunning(item.workKey);
diff --git a/src/core/chat-queue.test.ts b/src/core/chat-queue.test.ts
new file mode 100644
index 00000000..c7df9a20
--- /dev/null
+++ b/src/core/chat-queue.test.ts
@@ -0,0 +1,73 @@
+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';
+
+/**
+ * Two chats at once on the desktop: Mercury runs one turn at a time, so the
+ * second waits. It must say so (its place in line, and what's ahead of it)
+ * instead of showing "Thinking" for a turn that hasn't started — and the
+ * owner can put it first.
+ */
+
+const dirs: string[] = [];
+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
+
+function msg(id: string, channelId: string, content = id): ChannelMessage {
+ return { id, channelId, channelType: 'web', senderId: 'web_user', content, timestamp: 1, metadata: {} };
+}
+
+function agentWithWeb() {
+ const dir = mkdtempSync(join(tmpdir(), 'mercury-chat-queue-'));
+ dirs.push(dir);
+ const workLedger = new WorkLedger({ filePath: join(dir, 'work-ledger.json') });
+ const sent: Array<{ target: string; position: number; busyWith?: string; busySessionId?: string }> = [];
+ const web = { sendQueued: (target: string, d: { position: number; busyWith?: string; busySessionId?: string }) => sent.push({ target, ...d }) };
+ const agent = Object.create(Agent.prototype) as Agent;
+ Object.assign(agent, {
+ messageQueue: [], queuedWorkKeys: new Set(), workLedger, processing: false, currentMessage: null, currentActivity: '', currentAbort: null,
+ channels: { get: (t: string) => (t === 'web' ? web : undefined) },
+ });
+ const enqueue = (m: ChannelMessage) => agent.queueMessage(m, workLedger.accept(m).entry.key);
+ return { agent, enqueue, sent };
+}
+
+describe('a chat waiting for another', () => {
+ it('is told its place in line and what is running, as soon as it joins', () => {
+ const { agent, enqueue, sent } = agentWithWeb();
+ Object.assign(agent, { processing: true, currentMessage: msg('r', 'research', 'Research the top news on TechCrunch today') });
+ enqueue(msg('j', 'jokes', 'tell me a joke'));
+ expect(sent).toEqual([{ target: 'jokes', position: 1, busyWith: 'Research the top news on TechCrunch today', busySessionId: 'research' }]);
+ expect(agent.queueStateFor('jokes')).toMatchObject({ state: 'queued', position: 1, busySessionId: 'research' });
+ expect(agent.queueStateFor('research')).toEqual({ state: 'running' });
+ expect(agent.queueStateFor('other')).toEqual({ state: 'none' });
+ });
+
+ it('says nothing when nothing is running (the turn starts at once)', () => {
+ const { enqueue, sent } = agentWithWeb();
+ enqueue(msg('j', 'jokes'));
+ expect(sent).toEqual([]);
+ });
+
+ it('uses what the running turn is doing right now, when known', () => {
+ const { agent, enqueue, sent } = agentWithWeb();
+ const running = msg('r', 'research', 'Research the top news');
+ Object.assign(agent, { processing: true, currentMessage: running, currentActivity: '🔎 Searching the web' });
+ enqueue(msg('j', 'jokes'));
+ expect(sent[0].busyWith).toBe('Searching the web');
+ });
+
+ it('"do mine first" moves the chat to the front and tells everyone their new place', () => {
+ const { agent, enqueue, sent } = agentWithWeb();
+ Object.assign(agent, { processing: true, currentMessage: msg('r', 'research') });
+ enqueue(msg('a', 'alpha'));
+ enqueue(msg('b', 'beta'));
+ sent.length = 0;
+ expect(agent.prioritize('beta')).toBe(1);
+ expect(sent.map((s) => `${s.target}@${s.position}`)).toEqual(['beta@1', 'alpha@2']);
+ expect(agent.prioritize('nobody')).toBe(0);
+ });
+});
diff --git a/src/index.ts b/src/index.ts
index 666d4f85..7df20363 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -96,7 +96,7 @@ import { selectWithArrowKeys } from './utils/arrow-select.js';
import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/provider-models.js';
import { initCloudTokenStore } from './cloud/token-store.js';
import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';
-import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop, setSessionBusyLookup as setWebSessionBusy, setBudgetControls as setWebBudgetControls } from './web/server.js';
+import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager, setStopCallback as setWebStop, setSessionBusyLookup as setWebSessionBusy, setQueueControls as setWebQueueControls, setBudgetControls as setWebBudgetControls } from './web/server.js';
import { validateApiKey, validateBaseUrl, validateModelName } from './providers/provider-meta.js';
import { setFirstProviderHandler, setProvidersReload } from './web/api/providers.js';
import { setCloudReload } from './web/api/cloud.js';
@@ -3525,6 +3525,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
setCloudReload(() => agent.reloadProviders());
setWebStop(() => agent.stopAllWork('stopped'));
setWebSessionBusy((sessionId) => agent.isBusyWith(sessionId));
+ setWebQueueControls({ state: (id) => agent.queueStateFor(id), prioritize: (id) => agent.prioritize(id) });
setWebBudgetControls({ config: () => config, tokens: () => tokenBudget, saver: () => agent.saverMode });
// Titles made before they were checked: fix them once, quietly, after start-up.
if (!daemonOwnsRuntime) {
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index 8f5b1d6c..566a2709 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -78,6 +78,12 @@ let busyFn: ((sessionId: string) => boolean) | null = null;
export function setSessionBusyLookup(fn: ((sessionId: string) => boolean) | null): void {
busyFn = fn;
}
+type QueueState = { state: 'running' | 'queued' | 'none'; position?: number; busyWith?: string; busySessionId?: string };
+let queueControls: { state: (threadId: string) => QueueState; prioritize: (threadId: string) => number } | null = null;
+/** The agent's line of turns: where a chat stands, and moving one to the front ("do mine first"). */
+export function setQueueControls(controls: typeof queueControls): void {
+ queueControls = controls;
+}
/** The same stop the terminal's Esc and `/stop` use: abort the running turn, cancel its work entry. */
export function setStopCallback(fn: () => Promise<string>): void {
stopFn = fn;
@@ -747,6 +753,18 @@ chat.post('/api/chat/threads/:id/delete', async (c) => {
});
/** Save a thread to come back to later, or unsave it: { saved: boolean }. */
+// Where this chat's message stands: running, waiting in line (and behind what), or nothing.
+chat.get('/api/chat/threads/:id/queue', (c) => {
+ if (!queueControls) return c.json({ state: 'none' });
+ return c.json(queueControls.state(c.req.param('id')));
+});
+
+// "Do mine first": this chat's waiting messages go to the front of the line.
+chat.post('/api/chat/threads/:id/queue/first', (c) => {
+ if (!queueControls) return c.json({ error: 'Not available on this runtime' }, 503);
+ return c.json({ moved: queueControls.prioritize(c.req.param('id')) });
+});
+
chat.post('/api/chat/threads/:id/save', async (c) => {
const id = c.req.param('id');
if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);
diff --git a/src/web/server.ts b/src/web/server.ts
index 41037821..598034b0 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -21,7 +21,7 @@ import artifactRoutes from './api/artifacts.js';
import configRoutes from './api/config.js';
import systemRoutes, { setScheduler } from './api/system.js';
import brainRoutes, { setUserMemory } from './api/brain.js';
-import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setSessionRepository, setSessionSyncEnabledCallback, setStopCallback, setSessionBusyLookup } from './api/chat.js';
+import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setSessionRepository, setSessionSyncEnabledCallback, setStopCallback, setSessionBusyLookup, setQueueControls } from './api/chat.js';
import agentRoutes, { setAgentSupervisor, setBackgroundTaskManager } from './api/agents.js';
import botsRoutes, { setBotManager, setBotsWebhookSecret } from './api/bots.js';
import spotifyRoutes, { setSpotifyClient } from './api/spotify.js';
@@ -234,7 +234,7 @@ if (spaAvailable) {
}
export { setShutdownHandler, setMcpManager };
-export { setStopCallback, setSessionBusyLookup };
+export { setStopCallback, setSessionBusyLookup, setQueueControls };
export { updateStatus, setUserMemory, setWebChannel, setScheduler, setAgentSupervisor, setBackgroundTaskManager, setSpotifyClient, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders, setIDEProviders, setBotManager, setBotsWebhookSecret };
let webServer: ReturnType<typeof createAdaptorServer> | null = null;