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.

Show interrupted and stalled replies as notices with Retry

Lin (kwant bot)887106567ed3
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index bf54813b..36d54df6 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1069,7 +1069,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
});
};
- const handleSendMessage = async (text: string, attachments: AttachmentRef[] = []) => {
+ const handleSendMessage = async (text: string, attachments: AttachmentRef[] = []): Promise<boolean> => {
setHistoryWindow(null);
const targetId = openCtx;
const threadId = openThreadId;
@@ -1134,6 +1134,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
throw new Error(message);
}
+ return true;
} catch (err) {
console.error('Failed sending chat:', err);
const rest = (messagesCacheRef.current[targetId] || []).filter((m) => m.id !== tempId);
@@ -1145,6 +1146,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setRoutingState(null);
streamingContextIdRef.current = null;
}
+ return false;
}
};
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 8a51a4f2..7d81cc05 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -33,6 +33,8 @@ import { ranOnLabel } from '../engines';
import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';
import { SetupNeededCard, parseSetupMeta } from './SetupNeededCard';
import { routeReasonText } from '../routeReason';
+import { InterruptedNotice, SystemNotice } from './SystemNotice';
+import { isSystemNotice, parseInterruption, retryTargets } from '../interruptions';
export interface ChatMessage {
id: string;
@@ -110,7 +112,8 @@ export interface ChatViewProps {
isStreaming: boolean;
streamingSpeakerName?: string;
/** `attachments` are files already uploaded from the composer. */
- onSendMessage: (text: string, attachments: AttachmentRef[]) => void;
+ /** Resolves to false when the message couldn't be sent. */
+ onSendMessage: (text: string, attachments: AttachmentRef[]) => void | Promise<boolean | void>;
onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
kwants?: Array<{ id: string; name: string; title: string; avatar_sprite: string }>;
teams?: Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>;
@@ -653,7 +656,25 @@ export const ChatView: React.FC<ChatViewProps> = ({
}
};
+ const retries = retryTargets(messages);
+ const retrySend = async (target: { text: string; attachments: AttachmentRef[] }) => {
+ stickRef.current = true;
+ if ((await onSendMessage(target.text, target.attachments)) === false) throw new Error('not sent');
+ };
+
const renderMessage = (msg: ChatMessage) => {
+ const interruption = parseInterruption(msg);
+ if (interruption)
+ return (
+ <InterruptedNotice
+ key={msg.id}
+ messageId={msg.id}
+ interruption={interruption}
+ retry={retries.get(msg.id)}
+ onRetry={retrySend}
+ flash={flashId === msg.id}
+ />
+ );
const meta = msg.meta && renderDelegation ? parseDelegationMeta(msg.meta) : null;
if (meta && renderDelegation) return <React.Fragment key={msg.id}>{renderDelegation(msg, meta, flashId === msg.id)}</React.Fragment>;
const question = msg.meta && renderQuestion ? parseQuestionMeta(msg.meta) : null;
@@ -678,6 +699,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
/>
</div>
);
+ if (isSystemNotice(msg) && !parseAttachments(msg.meta).length)
+ return <SystemNotice key={msg.id} messageId={msg.id} text={msg.text} flash={flashId === msg.id} />;
const isUser = msg.sender_role === 'user';
const files = msg.meta ? parseAttachments(msg.meta) : [];
// A bot's share_file note: the file tiles say it all.
diff --git a/frontend/src/components/SystemNotice.tsx b/frontend/src/components/SystemNotice.tsx
new file mode 100644
index 00000000..43d104d0
--- /dev/null
+++ b/frontend/src/components/SystemNotice.tsx
@@ -0,0 +1,80 @@
+import React, { useRef, useState } from 'react';
+import { AlertTriangle, Check, Info, Loader2, RotateCcw } from 'lucide-react';
+import { Interruption, RetryState, RetryTarget, interruptionText, runRetryOnce } from '../interruptions';
+
+/** A note kwnt itself wrote (e.g. "Growth wasn't asked: …"): a quiet line, not a bot's reply. */
+export const SystemNotice: React.FC<{ messageId: string; text: string; flash?: boolean }> = ({ messageId, text, flash }) => (
+ <div
+ data-message-id={messageId}
+ data-system-notice
+ role="note"
+ className={`w-full max-w-5xl flex justify-center ${flash ? 'kw-flash rounded-xl' : ''}`}
+ >
+ <p className="flex items-start gap-1.5 max-w-full px-3 py-1.5 rounded-full text-xs text-zinc-400 bg-zinc-900/60 border border-zinc-800 break-words">
+ <Info size={12} className="mt-0.5 shrink-0 text-zinc-500" aria-hidden="true" />
+ <span className="min-w-0">
+ <span className="sr-only">Notice: </span>
+ {text}
+ </span>
+ </p>
+ </div>
+);
+
+export interface InterruptedNoticeProps {
+ messageId: string;
+ interruption: Interruption;
+ /** Set only on the newest notice the person hasn't moved past; without it there's no Retry. */
+ retry?: RetryTarget | null;
+ onRetry?: (target: RetryTarget) => void | Promise<unknown>;
+ flash?: boolean;
+}
+
+/** A reply that ended without an answer (restart or stall), with Retry for the person's message. */
+export const InterruptedNotice: React.FC<InterruptedNoticeProps> = ({ messageId, interruption, retry, onRetry, flash }) => {
+ const [state, setState] = useState<RetryState>('idle');
+ // Set synchronously, so a second click before the re-render can't send twice.
+ const lock = useRef<RetryState>('idle');
+ const headingId = `intr-${messageId}`;
+ const canRetry = !!retry && !!onRetry;
+
+ const run = () => {
+ if (retry && onRetry) void runRetryOnce(lock, retry, onRetry, setState);
+ };
+
+ return (
+ <section
+ data-message-id={messageId}
+ data-interrupted={interruption.kind}
+ aria-labelledby={headingId}
+ className={`w-full max-w-5xl rounded-xl border border-amber-500/30 bg-amber-950/20 px-3.5 py-2.5 sm:px-4 ${flash ? 'kw-flash' : ''}`}
+ >
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <p id={headingId} className="flex items-start gap-2 min-w-0 flex-1 basis-56 text-sm text-amber-200 break-words">
+ <AlertTriangle size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />
+ <span className="min-w-0">
+ {interruptionText(interruption)}
+ {canRetry && state !== 'sent' && <span className="text-amber-200/70"> Retry sends your message again.</span>}
+ </span>
+ </p>
+ {canRetry && (
+ <button
+ type="button"
+ onClick={run}
+ disabled={state !== 'idle'}
+ aria-describedby={headingId}
+ className="shrink-0 inline-flex items-center justify-center gap-1.5 min-h-[36px] px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors cursor-pointer disabled:cursor-default text-amber-100 bg-amber-500/15 border-amber-500/40 hover:bg-amber-500/25 disabled:opacity-70 disabled:hover:bg-amber-500/15 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400"
+ >
+ {state === 'sending' ? (
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : state === 'sent' ? (
+ <Check size={13} aria-hidden="true" />
+ ) : (
+ <RotateCcw size={13} aria-hidden="true" />
+ )}
+ <span>{state === 'sending' ? 'Sending…' : state === 'sent' ? 'Sent again' : 'Retry'}</span>
+ </button>
+ )}
+ </div>
+ </section>
+ );
+};
diff --git a/frontend/src/interruptions.ts b/frontend/src/interruptions.ts
new file mode 100644
index 00000000..bc5e308f
--- /dev/null
+++ b/frontend/src/interruptions.ts
@@ -0,0 +1,93 @@
+// Replies that ended without an answer: cut off by a restart (system note with
+// `turn_interrupted` meta) or stopped by the stall watchdog (the bot's own "⚠️ [Name] The model
+// sent nothing for N s" message). Both get a notice with Retry, which resends the person's message.
+import type { ChatMessage } from './components/ChatView';
+import { AttachmentRef, parseAttachments } from './attachments';
+import { parseMetaObject } from './questions';
+
+export interface Interruption {
+ kind: 'restart' | 'stall';
+ botName: string;
+ /** Seconds of silence before the watchdog stopped the reply (stall only). */
+ secs?: number;
+}
+
+// Written by routes.rs when the stall watchdog fires; there is no meta on that message.
+const STALL_RE = /^⚠️ \[(.+?)\] The model sent nothing for (\d+) s, so this reply was stopped\./;
+
+export function parseInterruption(msg: ChatMessage): Interruption | null {
+ if (msg.sender_role === 'system') {
+ const m = parseMetaObject(msg.meta);
+ if (m?.kind !== 'turn_interrupted' || m.interrupted !== true) return null;
+ const name = typeof m.kwant_name === 'string' && m.kwant_name.trim() ? m.kwant_name : 'The bot';
+ return { kind: 'restart', botName: name };
+ }
+ if (msg.sender_role === 'kwant') {
+ const s = STALL_RE.exec(msg.text.trim());
+ if (s) return { kind: 'stall', botName: s[1], secs: Number(s[2]) };
+ }
+ return null;
+}
+
+export function interruptionText(i: Interruption): string {
+ return i.kind === 'restart'
+ ? `${i.botName}'s reply was cut off when the app restarted.`
+ : `${i.botName} sent nothing for ${i.secs} s, so the reply was stopped.`;
+}
+
+export interface RetryTarget {
+ text: string;
+ attachments: AttachmentRef[];
+}
+
+/**
+ * The message Retry would resend, keyed by notice id. Only the newest notice gets one, and only
+ * while the person hasn't written since: after that it was already retried or moved past.
+ */
+export function retryTargets(messages: ChatMessage[]): Map<string, RetryTarget> {
+ const out = new Map<string, RetryTarget>();
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i];
+ if (msg.sender_role === 'user') return out;
+ if (!parseInterruption(msg)) continue;
+ for (let j = i - 1; j >= 0; j--) {
+ const prev = messages[j];
+ if (prev.sender_role !== 'user') continue;
+ const attachments = parseAttachments(prev.meta);
+ if (prev.text.trim() || attachments.length) out.set(msg.id, { text: prev.text, attachments });
+ break;
+ }
+ return out;
+ }
+ return out;
+}
+
+export type RetryState = 'idle' | 'sending' | 'sent';
+
+/**
+ * One Retry click: sends only from `idle`, holds `sending` until the send settles, then `sent`,
+ * or back to `idle` if it failed so the person can try again. Returns whether it sent.
+ */
+export async function runRetryOnce(
+ lock: { current: RetryState },
+ target: RetryTarget,
+ send: (target: RetryTarget) => void | Promise<unknown>,
+ setState: (s: RetryState) => void,
+): Promise<boolean> {
+ if (lock.current !== 'idle') return false;
+ lock.current = 'sending';
+ setState('sending');
+ try {
+ await send(target);
+ lock.current = 'sent';
+ setState('sent');
+ return true;
+ } catch {
+ lock.current = 'idle';
+ setState('idle');
+ return false;
+ }
+}
+
+/** kwnt's own notes (sender "system"): drawn as a notice line, never as a bot's reply. */
+export const isSystemNotice = (msg: ChatMessage) => msg.sender_role === 'system';
diff --git a/frontend/tests/interruptions.test.mjs b/frontend/tests/interruptions.test.mjs
new file mode 100644
index 00000000..fb9aa8e7
--- /dev/null
+++ b/frontend/tests/interruptions.test.mjs
@@ -0,0 +1,129 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+
+const m = await loadBundled(`
+ export { parseInterruption, retryTargets, interruptionText, runRetryOnce } from './src/interruptions';
+ export { InterruptedNotice, SystemNotice } from './src/components/SystemNotice';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { createElement } from 'react';
+`);
+
+// Shaped like interrupt_running_turns in src/server/routes.rs.
+const restartNote = (id, name = 'Architect') => ({
+ id,
+ sender_role: 'system',
+ sender_id: 'kwnt',
+ text: `This reply from ${name} was interrupted by a restart. Send your message again to retry.`,
+ meta: JSON.stringify({ kind: 'turn_interrupted', interrupted: true, kwant_id: 'k1', kwant_name: name, turn_id: 't1', started_at: '2026-10-21T19:00:00Z' }),
+});
+// The stall watchdog's message in routes.rs (saved as the bot's reply, no meta).
+const stallNote = (id, name = 'Writer', secs = 120) => ({
+ id,
+ sender_role: 'kwant',
+ sender_id: name,
+ text: `⚠️ [${name}] The model sent nothing for ${secs} s, so this reply was stopped. Send your message again to retry.`,
+});
+const user = (id, text, meta = null) => ({ id, sender_role: 'user', sender_id: 'PlayerHero', text, meta });
+const bot = (id, text) => ({ id, sender_role: 'kwant', sender_id: 'Architect', text });
+
+test('recognises restart and stall notices, and nothing else', () => {
+ assert.deepEqual(m.parseInterruption(restartNote('n1')), { kind: 'restart', botName: 'Architect' });
+ assert.deepEqual(m.parseInterruption(stallNote('n2', 'Lead Dev', 90)), { kind: 'stall', botName: 'Lead Dev', secs: 90 });
+ assert.equal(m.parseInterruption(bot('b', 'The model sent nothing, all fine')), null);
+ assert.equal(m.parseInterruption({ ...restartNote('x'), meta: JSON.stringify({ kind: 'delegation_stalled' }) }), null);
+ assert.equal(m.parseInterruption({ ...restartNote('x'), meta: 'not json' }), null);
+ // A person quoting the stall line is not a notice.
+ assert.equal(m.parseInterruption({ ...stallNote('s'), sender_role: 'user' }), null);
+});
+
+test('Retry targets the person message before the newest notice only', () => {
+ const att = { id: '0f8fad5b-d9cb-469f-a165-70867728950e', name: 'a.png', mime: 'image/png', size: 3 };
+ const msgs = [
+ user('u1', 'first'),
+ restartNote('n1'),
+ user('u2', 'second', JSON.stringify({ attachments: [att] })),
+ bot('b1', 'partial'),
+ restartNote('n2'),
+ ];
+ const t = m.retryTargets(msgs);
+ assert.deepEqual([...t.keys()], ['n2']);
+ assert.deepEqual(t.get('n2'), { text: 'second', attachments: [att] });
+});
+
+test('no Retry once the person has written after the notice, or with nothing to resend', () => {
+ assert.equal(m.retryTargets([user('u1', 'hi'), stallNote('n1'), user('u2', 'hi')]).size, 0);
+ assert.equal(m.retryTargets([restartNote('n1')]).size, 0);
+ assert.equal(m.retryTargets([user('u1', 'go'), stallNote('n1'), bot('b', 'later reply')]).get('n1').text, 'go');
+});
+
+const render = (props) => m.renderToStaticMarkup(m.createElement(m.InterruptedNotice, props));
+
+test('the notice shows the reason and an enabled Retry button when it can retry', () => {
+ const html = render({ messageId: 'n1', interruption: { kind: 'restart', botName: 'Architect' }, retry: { text: 'hi', attachments: [] }, onRetry: () => {} });
+ assert.match(html, /Architect&#x27;s reply was cut off when the app restarted/);
+ assert.match(html, /<button[^>]*type="button"[^>]*>.*Retry<\/span><\/button>/);
+ assert.doesNotMatch(html, /<button[^>]*\sdisabled=""/);
+ const stall = render({ messageId: 'n2', interruption: { kind: 'stall', botName: 'Writer', secs: 120 }, retry: { text: 'hi', attachments: [] }, onRetry: () => {} });
+ assert.match(stall, /Writer sent nothing for 120 s, so the reply was stopped/);
+ assert.match(stall, /data-interrupted="stall"/);
+});
+
+test('an older or already-retried notice has no button', () => {
+ const html = render({ messageId: 'n1', interruption: { kind: 'restart', botName: 'Architect' }, retry: null, onRetry: () => {} });
+ assert.doesNotMatch(html, /<button/);
+ assert.doesNotMatch(html, /Retry sends/);
+});
+
+test('system notes render as a notice, not a bot reply', () => {
+ const html = m.renderToStaticMarkup(m.createElement(m.SystemNotice, { messageId: 's1', text: "Growth wasn't asked: inside code" }));
+ assert.match(html, /role="note"/);
+ assert.match(html, /data-system-notice/);
+ assert.match(html, /Notice: <\/span>Growth wasn&#x27;t asked: inside code/);
+});
+
+// What a Retry click does (the button's onClick calls runRetryOnce with a ref lock).
+test('Retry sends once per click and stays disabled while sending', async () => {
+ const lock = { current: 'idle' };
+ const states = [];
+ const sent = [];
+ let finish;
+ const send = (t) => {
+ sent.push(t.text);
+ return new Promise((res) => (finish = res));
+ };
+ const target = { text: 'again please', attachments: [] };
+ const first = m.runRetryOnce(lock, target, send, (s) => states.push(s));
+ // A double click while the first send is in flight does nothing.
+ assert.equal(await m.runRetryOnce(lock, target, send, (s) => states.push(s)), false);
+ assert.deepEqual(sent, ['again please']);
+ assert.deepEqual(states, ['sending']);
+ finish();
+ assert.equal(await first, true);
+ assert.deepEqual(states, ['sending', 'sent']);
+ // After it went through, further clicks don't resend.
+ assert.equal(await m.runRetryOnce(lock, target, send, () => {}), false);
+ assert.equal(sent.length, 1);
+});
+
+test('a failed Retry goes back to idle so the person can try again', async () => {
+ const lock = { current: 'idle' };
+ const states = [];
+ let calls = 0;
+ const send = () => {
+ calls++;
+ return calls === 1 ? Promise.reject(new Error('down')) : Promise.resolve();
+ };
+ assert.equal(await m.runRetryOnce(lock, { text: 'x', attachments: [] }, send, (s) => states.push(s)), false);
+ assert.deepEqual(states, ['sending', 'idle']);
+ assert.equal(await m.runRetryOnce(lock, { text: 'x', attachments: [] }, send, (s) => states.push(s)), true);
+ assert.equal(calls, 2);
+});
+
+test('an idle Retry button is not disabled', () => {
+ // The rendered button carries the real disabled attribute (not only the Tailwind variant).
+ const html = render({ messageId: 'n1', interruption: { kind: 'restart', botName: 'A' }, retry: { text: 'x', attachments: [] }, onRetry: () => {} });
+ assert.doesNotMatch(html, /<button[^>]*\sdisabled=""/);
+});