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.

Bot replies show without reopening the chat

Pixel (kwant bot)9bd673157538
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 8d75386a..2d74b56e 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -38,6 +38,7 @@ import { playSfx } from './audio/chiptune';
import { Toasts, Toast } from './components/Toasts';
import { clearAllTurns, resetTurns, turnEnded, turnStarted } from './kwantActivity';
import {
+ ChatLoads,
Delegation,
DelegationMeta,
Thread,
@@ -49,6 +50,7 @@ import {
messageContextId,
parseDelegationMeta,
queuePosition,
+ reloadOnTurnEnd,
shouldRenderDelta,
streamTarget,
threadBadge,
@@ -416,9 +418,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
};
const kwantName = (id: unknown) => (typeof id === 'string' ? kwantsRef.current.find((k) => k.id === id)?.name : undefined);
+ const chatLoadsRef = useRef(new ChatLoads());
/** Loads a chat's latest messages into the cache, and on screen if it's open. */
const refreshContext = async (ctx: string | null | undefined): Promise<void> => {
if (!ctx) return;
+ const n = chatLoadsRef.current.start(ctx);
try {
let data: ChatMessage[];
if (knownThreadsRef.current.has(ctx)) {
@@ -428,13 +432,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (!res.ok) throw new Error(`HTTP ${res.status}`);
data = await res.json();
}
+ // A newer load of this chat started meanwhile: it has the newer messages
+ if (!chatLoadsRef.current.isLatest(ctx, n)) return;
messagesCacheRef.current[ctx] = data;
if (openCtxRef.current === ctx) {
setMessages(data);
setMessagesError(null);
}
} catch {
- if (openCtxRef.current === ctx) setMessagesError('Could not load this chat.');
+ if (openCtxRef.current === ctx && chatLoadsRef.current.isLatest(ctx, n)) setMessagesError('Could not load this chat.');
}
};
@@ -632,7 +638,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
useEffect(() => {
const sse = new EventSource(eventsUrl(space.id));
let dropped = false;
- /** TurnComplete already refreshed these turns' chats; their turn_ended needn't again. */
+ /** Turns whose TurnComplete came: their live steps can go once the reply is on screen. */
const completed = new Set<string>();
/** After a reply: drop the chat's stream once nothing else runs or waits there. */
@@ -711,8 +717,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const key = d.turn_id ?? d.context_id;
if (event.type === 'turn_ended' || event.type === 'TurnEnded') {
turnEnded(d.kwant_id, key);
- if (d.turn_id && completed.delete(d.turn_id)) settle(ctx);
- else refreshContext(ctx).then(() => settle(ctx));
+ if (d.turn_id) completed.delete(d.turn_id);
+ // The reply is saved by now; TurnComplete's load may have come back without it
+ if (reloadOnTurnEnd(d.turn_id)) refreshContext(ctx).then(() => settle(ctx));
+ else settle(ctx);
} else {
if (event.type === 'turn_started' || event.type === 'TurnStarted') turnStarted(d.kwant_id, key);
if (!discussionInProgressRef.current || ctx !== streamingContextIdRef.current) markLive(ctx, kwantName(d.kwant_id));
diff --git a/frontend/src/threads.ts b/frontend/src/threads.ts
index 2e119d56..b79cba54 100644
--- a/frontend/src/threads.ts
+++ b/frontend/src/threads.ts
@@ -100,6 +100,36 @@ export function hydrateTurns(list: ActiveTurn[] | undefined): TurnMap {
return out;
}
+// ---------------------------------------------------------------------------
+// Bringing a finished reply onto the screen
+
+/**
+ * Whether `turn_ended` loads its chat again. Always: the model driver sends TurnComplete before
+ * kwnt saves the reply, so the load TurnComplete starts can come back without it. `turn_ended`
+ * is sent once the reply is saved, so its load is the one that is sure to show it.
+ */
+export function reloadOnTurnEnd(_turnId: string | null | undefined): boolean {
+ return true;
+}
+
+/**
+ * Loads of one chat can finish out of order (a slow first load landing after a later one). Each
+ * load takes a number when it starts; only the newest started load for a chat may replace what's
+ * on screen, so an older answer never hides a reply a newer one already showed.
+ */
+export class ChatLoads {
+ private seq: Record<string, number> = {};
+
+ start(ctx: string): number {
+ this.seq[ctx] = (this.seq[ctx] ?? 0) + 1;
+ return this.seq[ctx];
+ }
+
+ isLatest(ctx: string, n: number): boolean {
+ return this.seq[ctx] === n;
+ }
+}
+
/** Applies one SSE event; returns the same map when the event isn't about turns. */
export function applyTurnEvent(turns: TurnMap, ev: { type?: string; data?: any }): TurnMap {
const d = ev.data ?? {};
diff --git a/frontend/tests/liveReplies.test.mjs b/frontend/tests/liveReplies.test.mjs
new file mode 100644
index 00000000..80eb2c38
--- /dev/null
+++ b/frontend/tests/liveReplies.test.mjs
@@ -0,0 +1,56 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+import ts from 'typescript';
+
+const load = async (path) => {
+ const source = await readFile(new URL(path, import.meta.url), 'utf8');
+ const { outputText } = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext } });
+ return import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);
+};
+
+const t = await load('../src/threads.ts');
+
+// A chat on screen, kept the way App keeps it: TurnComplete loads the chat, turn_ended loads it
+// again when reloadOnTurnEnd says so, and a load only lands if ChatLoads says it is the newest.
+function chat() {
+ const server = [{ id: 'm1', text: 'hi' }];
+ const loads = new t.ChatLoads();
+ let screen = [];
+ const pending = [];
+ const reload = () => {
+ const n = loads.start('c');
+ const snapshot = server.slice();
+ const p = { done: () => { if (loads.isLatest('c', n)) screen = snapshot; } };
+ pending.push(p);
+ return p;
+ };
+ return { server, reload, screen: () => screen, pending };
+}
+
+test('a reply saved after TurnComplete still shows once the turn ends (no reopening)', () => {
+ const c = chat();
+ // TurnComplete: the driver is done, the reply isn't saved yet
+ c.reload().done();
+ // kwant saves the reply, then sends turn_ended
+ c.server.push({ id: 'm2', text: 'Stub reply' });
+ if (t.reloadOnTurnEnd('turn-1')) c.reload().done();
+ assert.deepEqual(c.screen().map((m) => m.id), ['m1', 'm2'], 'the bot reply is on screen');
+});
+
+test('a slow load that finishes last never hides the reply a newer load showed', () => {
+ const c = chat();
+ const early = c.reload(); // TurnComplete's load, slow over Docker networking
+ c.server.push({ id: 'm2', text: 'Stub reply' });
+ const late = c.reload(); // turn_ended's load
+ late.done();
+ early.done();
+ assert.deepEqual(c.screen().map((m) => m.id), ['m1', 'm2']);
+});
+
+test('App reloads on turn_ended through reloadOnTurnEnd and guards loads with ChatLoads', async () => {
+ const app = await readFile(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ assert.match(app, /reloadOnTurnEnd\(/, 'turn_ended asks reloadOnTurnEnd');
+ assert.match(app, /chatLoads(Ref)?\.current\.isLatest\(|chatLoads\.isLatest\(/, 'refreshContext drops stale loads');
+ assert.doesNotMatch(app, /completed\.delete\(d\.turn_id\)\) settle\(ctx\)/, 'turn_ended no longer skips the reload');
+});