Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.8.0 P6: show a queued turn under the reply still running in the same chat (#476)

Oleksandr Ivanchenkoef997c2b268e
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 8f63db9c..ad9d4de9 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -81,6 +81,7 @@ import {
Delegation,
DelegationMeta,
Thread,
+ TrackedTurn,
TurnMap,
applyDelegation,
applyTurnEvent,
@@ -89,9 +90,11 @@ import {
messageContextId,
parseDelegationMeta,
queuePosition,
+ queuedInChat,
reloadOnTurnEnd,
shouldRenderDelta,
streamTarget,
+ waitsForOtherBot,
threadBadge,
threadsApi,
turnsIn,
@@ -3139,10 +3142,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// The open chat's running turn's live steps (the newest, when several reply at once).
const activityHere = Object.values(activity).filter((a) => a.ctx === openCtx && turns[a.turnId]).pop() ?? null;
const needsYouByKwant = openStepsByKwant(humanSteps);
- const waiting = openTurns.some((t) => t.state === 'running') ? undefined : openTurns.find((t) => t.state === 'queued');
- const queuedHere: QueuedState | null = waiting
- ? { position: queuePosition(turns, waiting.turn_id), reason: waiting.reason ?? 'agent_busy', slots: waiting.slots, speaker: kwantName(waiting.kwant_id) ?? live[openCtx] ?? 'The bot' }
- : null;
+ const chatQueue = queuedInChat(turns, openCtx);
+ const asQueued = (t: TrackedTurn): QueuedState => ({
+ position: queuePosition(turns, t.turn_id),
+ reason: t.reason ?? 'agent_busy',
+ slots: t.slots,
+ speaker: kwantName(t.kwant_id) ?? live[openCtx] ?? 'The bot',
+ turnId: t.turn_id,
+ });
+ const queuedHere: QueuedState | null = chatQueue.alone ? asQueued(chatQueue.alone) : null;
+ // P6: a turn waiting behind the reply that runs here shows under it, not hidden until it starts.
+ const queuedBeside: QueuedState[] = chatQueue.beside.map((t) => ({ ...asQueued(t), named: waitsForOtherBot(turns, openCtx, t) }));
// The bot's conversations, the open thread's controls, and "working on…" elsewhere.
const agentThreads = currentKwant ? threadsByKwant[currentKwant.id] : undefined;
@@ -3828,6 +3838,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
) : null
}
queued={queuedHere}
+ queuedBeside={queuedBeside}
renderDelegation={renderDelegation}
switchNotes={switchNotes}
renderQuestion={renderQuestion}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index c1bf18f4..05820776 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -1,5 +1,6 @@
import React, { Fragment, useState, useRef, useEffect, useLayoutEffect, useMemo } from 'react';
import { queuedText } from '../claudeVm';
+import { QueuedBeside } from './QueuedBeside';
import type { SwitchEntry } from '../watchLive';
import { emptyTrialReplyLine, trialCardsAfter, trialOf } from '../showOnce';
import { parsePick } from '../engines';
@@ -117,6 +118,10 @@ export interface QueuedState {
/** vm_busy only: how many replies run inside the VM at once. */
slots?: number;
speaker: string;
+ /** The waiting turn, when known (keys the chips under a running reply). */
+ turnId?: string;
+ /** Under a running reply: the waiting turn is for a different bot than the one replying (a room), so the line leads with `speaker`. */
+ named?: boolean;
}
/** "Drafter: Write" for a resolved approval row; the card's own words, nothing computed. */
@@ -261,6 +266,8 @@ export interface ChatViewProps {
titleExtra?: React.ReactNode;
/** Set while the open chat's turn waits in the queue. */
queued?: QueuedState | null;
+ /** P6: turns waiting behind the reply that runs in this chat, oldest first. Drawn under that reply. */
+ queuedBeside?: QueuedState[];
/** Draws a delegation note or result (messages with delegation `meta`). */
renderDelegation?: (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => React.ReactNode;
/** Draws a bot's question card (messages with `ask_user` meta). */
@@ -482,6 +489,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
topCard,
titleExtra,
queued,
+ queuedBeside,
renderDelegation,
renderQuestion,
switchNotes,
@@ -1797,6 +1805,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* A held reply is being decided: the line stands in for the streamed draft and the consults */}
{deciding && <DecidingLine botName={deciding.botName} consulted={deciding.consulted} />}
+ {/* P6: turns waiting behind the held reply stay visible while the team decides (under the line, aligned with its card) */}
+ {(deciding || (isStreaming && routingState?.phase === 'deciding')) && !queued && (queuedBeside?.length ?? 0) > 0 && (
+ <div className="w-full max-w-5xl pl-12" data-queued-beside-deciding="">
+ <div className="max-w-4xl">
+ <QueuedBeside items={queuedBeside} />
+ </div>
+ </div>
+ )}
+
{/* Live Streaming Assistant Message (or its place in the queue, in the same frame) */}
{isStreaming && !deciding && routingState?.phase !== 'deciding' && (
<div className="flex items-start gap-3.5 w-full max-w-5xl">
@@ -1878,6 +1895,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
</div>
)}
+
+ {!queued && <QueuedBeside items={queuedBeside} />}
</div>
</div>
)}
diff --git a/frontend/src/components/QueuedBeside.tsx b/frontend/src/components/QueuedBeside.tsx
new file mode 100644
index 00000000..5fd4cb79
--- /dev/null
+++ b/frontend/src/components/QueuedBeside.tsx
@@ -0,0 +1,42 @@
+import { queuedText } from '../claudeVm';
+import type { QueuedState } from './ChatView';
+
+/**
+ * P6 (#467): the person wrote again while the bot was still answering in this chat. The new turn
+ * waits (`agent_busy`) and starts when the running reply ends. Under that reply, one calm line per
+ * waiting turn says it was received and where it is in line: the same dot and words as the
+ * "In line" bubble, no spinner, no warning tone.
+ *
+ * The reason sentence is said once: a row repeats it only when its reason, slots or named bot differ
+ * from the row above ("#2 in line." alone otherwise). In a room, a turn waiting for a different bot
+ * than the one replying leads with that bot's name, so "this bot" never points at the wrong one.
+ * The list is one polite live region; its rows stay plain list items.
+ */
+export function QueuedBeside({ items }: { items?: QueuedState[] }) {
+ if (!items || items.length === 0) return null;
+ return (
+ <ul
+ className="mt-2 flex flex-col gap-1 w-full"
+ data-queued-beside=""
+ role="status"
+ aria-live="polite"
+ aria-label="Waiting to start"
+ >
+ {items.map((q, i) => {
+ const prev = items[i - 1];
+ const sameAsAbove =
+ !!prev && prev.reason === q.reason && prev.slots === q.slots && !!prev.named === !!q.named && (!q.named || prev.speaker === q.speaker);
+ const place = q.position ? `#${q.position} in line.` : 'In line.';
+ return (
+ <li key={q.turnId ?? i} className="flex items-start gap-1.5 text-[11px] leading-snug text-zinc-400">
+ <span className="mt-[5px] w-1.5 h-1.5 rounded-full bg-zinc-500 shrink-0" aria-hidden="true" />
+ <span className="min-w-0">
+ <strong className="font-medium text-zinc-200">{q.named ? `${q.speaker} · ${place}` : place}</strong>
+ {!sameAsAbove && <> {queuedText(q.reason, q.slots)}</>}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
diff --git a/frontend/src/threads.ts b/frontend/src/threads.ts
index 1673b272..567a8300 100644
--- a/frontend/src/threads.ts
+++ b/frontend/src/threads.ts
@@ -212,6 +212,29 @@ export const turnsIn = (turns: TurnMap, contextId: string): TrackedTurn[] =>
.filter((t) => t.context_id === contextId)
.sort((a, b) => a.seq - b.seq);
+/**
+ * The open chat's waiting turns. `alone`: the first queued turn while nothing runs here, which takes
+ * the live bubble's place ("In line."). `beside`: every turn queued while a reply runs here (P6 #467:
+ * a second message to a bot still answering waits with `agent_busy`), oldest first, drawn under the
+ * running reply so the person sees it was received.
+ */
+export function queuedInChat(turns: TurnMap, contextId: string): { alone: TrackedTurn | null; beside: TrackedTurn[] } {
+ const here = turnsIn(turns, contextId);
+ const queued = here.filter((t) => t.state === 'queued');
+ if (!here.some((t) => t.state === 'running')) return { alone: queued[0] ?? null, beside: [] };
+ return { alone: null, beside: queued };
+}
+
+/**
+ * A turn waiting beside a running reply belongs to a different bot than any reply running in this
+ * chat (a room: Scout waits behind its own work elsewhere while Marketer answers here). Its line then
+ * names that bot instead of saying "this bot" under someone else's reply.
+ */
+export function waitsForOtherBot(turns: TurnMap, contextId: string, waiting: TrackedTurn): boolean {
+ const running = turnsIn(turns, contextId).filter((t) => t.state === 'running');
+ return running.length > 0 && !running.some((t) => t.kwant_id === waiting.kwant_id);
+}
+
/** The kwant's turns outside its direct chat (threads, delegations, team channels), oldest first. */
export const backgroundTurns = (turns: TurnMap, kwantId: string): TrackedTurn[] =>
Object.values(turns)
diff --git a/frontend/tests/queuedBesideRunning.test.mjs b/frontend/tests/queuedBesideRunning.test.mjs
new file mode 100644
index 00000000..0d774823
--- /dev/null
+++ b/frontend/tests/queuedBesideRunning.test.mjs
@@ -0,0 +1,152 @@
+// 0.8.0 P6 (#467): a second message to a bot still answering in the same chat waits (`turn_queued`,
+// reason agent_busy) and starts when the first reply ends. The app used to hide that wait whenever a
+// reply was running here, so "Screenshot give me!" looked ignored. Now the waiting turn shows under
+// the running reply, with its place in line, until it starts or is cancelled.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { QueuedBeside } from './src/components/QueuedBeside';
+ export * from './src/threads';
+ export const draw = (items) => renderToStaticMarkup(React.createElement(QueuedBeside, { items }));
+`);
+
+const ev = (type, data) => ({ type, data });
+const WAIT = 'Waiting for this bot’s other replies to finish.';
+// What App.tsx hands ChatView for one queued turn.
+const asQueued = (turns, x) => ({ position: m.queuePosition(turns, x.turn_id), reason: x.reason ?? 'agent_busy', slots: x.slots, speaker: 'Pixel', turnId: x.turn_id });
+const besideHtml = (turns, ctx) => m.draw(m.queuedInChat(turns, ctx).beside.map((x) => asQueued(turns, x)));
+
+// Oleks asks Pixel something in the direct chat, then writes again while it is still answering.
+const runningPlusQueued = () => {
+ let s = m.applyTurnEvent({}, ev('turn_started', { turn_id: 'r1', kwant_id: 'pixel', context_id: 'pixel' }));
+ s = m.applyTurnEvent(s, ev('turn_queued', { turn_id: 'q1', kwant_id: 'pixel', context_id: 'pixel', position: 1, reason: 'agent_busy' }));
+ return s;
+};
+
+test('one running and one queued turn in the same chat: both show, the queued one under the reply', () => {
+ const s = runningPlusQueued();
+ const q = m.queuedInChat(s, 'pixel');
+ assert.equal(q.alone, null, 'the running reply keeps the live bubble');
+ assert.deepEqual(q.beside.map((x) => x.turn_id), ['q1'], 'the waiting turn is not hidden');
+ const html = besideHtml(s, 'pixel');
+ assert.match(html, /role="status"/);
+ assert.ok(html.includes('#1 in line.'), html);
+ assert.ok(html.includes(WAIT), html);
+
+ // A third message keeps its own place in line.
+ const s2 = m.applyTurnEvent(s, ev('turn_queued', { turn_id: 'q2', kwant_id: 'pixel', context_id: 'pixel', position: 2, reason: 'agent_busy' }));
+ const html2 = besideHtml(s2, 'pixel');
+ assert.ok(html2.indexOf('#1 in line.') >= 0 && html2.indexOf('#2 in line.') > html2.indexOf('#1 in line.'), html2);
+});
+
+test('the queued chip clears when that turn starts, and when it is cancelled', () => {
+ let s = runningPlusQueued();
+ s = m.applyTurnEvent(s, ev('turn_ended', { turn_id: 'r1', kwant_id: 'pixel', context_id: 'pixel', outcome: 'completed' }));
+ // Between the two events the old "In line" bubble stands in, as before.
+ assert.equal(m.queuedInChat(s, 'pixel').alone?.turn_id, 'q1');
+ s = m.applyTurnEvent(s, ev('turn_started', { turn_id: 'q1', kwant_id: 'pixel', context_id: 'pixel' }));
+ assert.deepEqual(m.queuedInChat(s, 'pixel'), { alone: null, beside: [] });
+ assert.equal(besideHtml(s, 'pixel'), '', 'nothing drawn once it runs');
+
+ // Cancelled while waiting: the server ends the queued turn.
+ let c = runningPlusQueued();
+ c = m.applyTurnEvent(c, ev('turn_ended', { turn_id: 'q1', kwant_id: 'pixel', context_id: 'pixel', outcome: 'cancelled' }));
+ assert.deepEqual(m.queuedInChat(c, 'pixel').beside, []);
+ assert.equal(besideHtml(c, 'pixel'), '');
+});
+
+test("another chat's queued turn doesn't show here", () => {
+ let s = runningPlusQueued();
+ s = m.applyTurnEvent(s, ev('turn_queued', { turn_id: 'q-th', kwant_id: 'pixel', context_id: 'thread-9', thread_id: 'thread-9', reason: 'agent_busy' }));
+ assert.deepEqual(m.queuedInChat(s, 'pixel').beside.map((x) => x.turn_id), ['q1']);
+ // A chat with only someone else's waiting turn, and nothing running, is untouched.
+ assert.deepEqual(m.queuedInChat(s, 'thread-9'), { alone: s['q-th'], beside: [] });
+ assert.deepEqual(m.queuedInChat(s, 'elsewhere'), { alone: null, beside: [] });
+});
+
+test('the old path is unchanged: queued with nothing running takes the bubble (agent, server and VM waits)', () => {
+ for (const reason of ['agent_busy', 'server_busy', 'vm_busy']) {
+ const s = m.applyTurnEvent({}, ev('turn_queued', { turn_id: 'q', kwant_id: 'pixel', context_id: 'pixel', reason, slots: 2 }));
+ const q = m.queuedInChat(s, 'pixel');
+ assert.equal(q.alone?.turn_id, 'q', reason);
+ assert.equal(q.alone?.reason, reason);
+ assert.deepEqual(q.beside, [], `${reason}: no extra chip`);
+ }
+ assert.equal(m.draw([]), '');
+ assert.equal(m.draw(undefined), '');
+});
+
+test('ChatView draws the chips under the running reply, never next to the "In line" bubble', () => {
+ const chat = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');
+ const live = chat.indexOf('Live Streaming Assistant Message');
+ const chip = chat.indexOf('{!queued && <QueuedBeside items={queuedBeside} />}');
+ assert.ok(live > 0 && chip > live, 'inside the live reply block, after the bubble');
+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ assert.match(app, /queuedBeside=\{queuedBeside\}/);
+ assert.doesNotMatch(app, /openTurns\.some\(\(t\) => t\.state === 'running'\) \? undefined : openTurns\.find/, 'the hiding rule is gone');
+});
+
+// Round 1 review (#476): M1, M2, S1, S2.
+
+test('M1: with two agent_busy waits the reason is said once; the second row is just its place', () => {
+ let s = runningPlusQueued();
+ s = m.applyTurnEvent(s, ev('turn_queued', { turn_id: 'q2', kwant_id: 'pixel', context_id: 'pixel', position: 2, reason: 'agent_busy' }));
+ const html = besideHtml(s, 'pixel');
+ assert.equal(html.split(WAIT).length - 1, 1, html);
+ assert.ok(html.includes('#2 in line.</strong></span></li>'), html);
+ // A row whose reason differs from the one above says its own sentence.
+ const mixed = m.draw([
+ { position: 1, reason: 'agent_busy', speaker: 'Pixel' },
+ { position: 2, reason: 'server_busy', speaker: 'Pixel' },
+ ]);
+ assert.ok(mixed.includes(WAIT), mixed);
+ assert.equal((mixed.match(/<li/g) ?? []).length, 2);
+ assert.ok(!mixed.includes('#2 in line.</strong></span></li>'), 'server_busy row keeps its reason');
+});
+
+test('M2: in a room, a turn waiting for another bot leads with its name; the replying bot\'s own wait does not', () => {
+ // Marketer answers in the room; Scout's turn there waits behind Scout's work in another chat.
+ let s = m.applyTurnEvent({}, ev('turn_started', { turn_id: 'r1', kwant_id: 'marketer', context_id: 'room-1' }));
+ s = m.applyTurnEvent(s, ev('turn_queued', { turn_id: 'qs', kwant_id: 'scout', context_id: 'room-1', reason: 'agent_busy' }));
+ s = m.applyTurnEvent(s, ev('turn_queued', { turn_id: 'qm', kwant_id: 'marketer', context_id: 'room-1', reason: 'agent_busy' }));
+ const names = { marketer: 'Marketer', scout: 'Scout' };
+ const items = m.queuedInChat(s, 'room-1').beside.map((x) => ({
+ position: m.queuePosition(s, x.turn_id), reason: 'agent_busy', speaker: names[x.kwant_id], turnId: x.turn_id,
+ named: m.waitsForOtherBot(s, 'room-1', x),
+ }));
+ assert.deepEqual(items.map((x) => [x.turnId, x.named]), [['qs', true], ['qm', false]]);
+ const html = m.draw(items);
+ assert.ok(html.includes('Scout · #1 in line.'), html);
+ assert.ok(!html.includes('Marketer ·'), 'the replying bot\'s own wait is not named');
+ // Different bots: each row says its own sentence, so "this bot" sits next to the right name.
+ assert.equal(html.split(WAIT).length - 1, 2, html);
+
+ // A one-bot chat looks as before: no name.
+ const one = runningPlusQueued();
+ assert.equal(m.waitsForOtherBot(one, 'pixel', one.q1), false);
+ assert.ok(!besideHtml(one, 'pixel').includes('Pixel ·'));
+});
+
+test('S1: the waiting line also shows while "Team is deciding…" stands in for the reply', () => {
+ const chat = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');
+ const line = chat.indexOf('<DecidingLine botName=');
+ const block = chat.indexOf('data-queued-beside-deciding');
+ const live = chat.indexOf('Live Streaming Assistant Message');
+ assert.ok(line > 0 && block > line && block < live, 'right under the deciding line');
+ const cond = chat.slice(chat.lastIndexOf('{(', block), block);
+ assert.match(cond, /deciding \|\| \(isStreaming && routingState\?\.phase === 'deciding'\)/);
+ assert.match(cond, /!queued/);
+ assert.ok(chat.slice(block, chat.indexOf('</div>', block)).includes('<QueuedBeside items={queuedBeside} />'));
+});
+
+test('S2: one polite live region on the list; the rows stay plain list items', () => {
+ const html = besideHtml(runningPlusQueued(), 'pixel');
+ assert.match(html, /^<ul[^>]*role="status"[^>]*aria-live="polite"/);
+ assert.match(html, /<li class="[^"]*">/);
+ assert.ok(!/<li[^>]*role=/.test(html), html);
+});