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.

UI: pending approvals survive a reload, inline in the bot's chat and in While you were away

Lin (kwant bot)19ac1147fcba
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ce9df518..7773161a 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -14,7 +14,7 @@ import { HireCard, type HireDecision } from './components/HireCard';
import type { RoutineFocus } from './components/RoutinesPanel';
import { AwayPage } from './components/AwayView';
import { AlertTriangle, Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';
-import { PendingApproval } from './components/ModernApprovalCard';
+import { ChatApproval, OpenChat, approvalFromEvent, approvalsForChat, approvalsFromAway, syncApprovals, upsertApproval, withoutApproval } from './approvals';
import type { AgentFormData } from './components/NewAgentModal';
import { NewTeamModal } from './components/NewTeamModal';
import { ManageTeamModal } from './components/ManageTeamModal';
@@ -204,7 +204,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const activeSandboxIdRef = useRef<string>('default');
const currentKwantRef = useRef<Kwant | null>(null);
const currentTeamRef = useRef<Team | null>(null);
- const [pendingApproval, setPendingApproval] = useState<PendingApproval | null>(null);
+ // Every tool approval still waiting, from live events and, after a reload or reconnect, the server.
+ const [pendingApprovals, setPendingApprovals] = useState<ChatApproval[]>([]);
+ // Seen live since the last server list: kept even if that list was fetched just before.
+ const liveApprovalIdsRef = useRef<Set<string>>(new Set());
+ const dropApproval = (id: string) => {
+ liveApprovalIdsRef.current.delete(id);
+ setPendingApprovals((prev) => withoutApproval(prev, id));
+ };
const [tokensUsed, setTokensUsed] = useState(0);
// Space settings: open on one tab, or closed.
@@ -255,7 +262,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const refreshAwayCount = (delay = 0) => {
clearTimeout(awayTimerRef.current);
awayTimerRef.current = setTimeout(() => {
- awayApi.get().then((r) => setAwayCount(r.unseen.total), () => undefined);
+ awayApi.get().then((r) => {
+ setAwayCount(r.unseen.total);
+ const fromServer = approvalsFromAway(r.waiting);
+ const live = liveApprovalIdsRef.current;
+ setPendingApprovals((prev) => syncApprovals(prev, fromServer, live));
+ for (const a of fromServer) live.delete(a.id);
+ }, () => undefined);
}, delay);
};
const toastIdRef = useRef(0);
@@ -814,16 +827,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
else applyDecision();
break;
}
- case 'ApprovalRequired':
- setPendingApproval({
- id: event.data.id,
- tool_name: event.data.tool_name,
- details: event.data.details,
- });
+ case 'ApprovalRequired': {
+ const approval = approvalFromEvent(event.data);
+ liveApprovalIdsRef.current.add(approval.id);
+ setPendingApprovals((prev) => upsertApproval(prev, approval));
playSfx('alert');
break;
+ }
case 'ApprovalWithdrawn':
- setPendingApproval((current) => (current?.id === event.data.id ? null : current));
+ dropApproval(event.data.id);
break;
case 'discussion_started':
case 'DiscussionStarted': {
@@ -1129,14 +1141,22 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
decision: 'allow_once' | 'always_allow' | 'deny'
) => {
try {
- await fetch(`/api/approvals/${ticketId}/resolve`, {
+ const res = await fetch(`/api/approvals/${ticketId}/resolve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ decision }),
});
- setPendingApproval(null);
+ // 409/404: it lapsed meanwhile (turn ended, expired, answered elsewhere).
+ if (res.ok || res.status === 409 || res.status === 404) {
+ dropApproval(ticketId);
+ if (!res.ok) pushToast('This request expired', 'The bot is no longer waiting for this answer.');
+ refreshAwayCount(300);
+ } else {
+ pushToast("Couldn't send your answer", `Request failed (HTTP ${res.status}). Try again.`);
+ }
} catch (err) {
console.error('Failed resolving approval:', err);
+ pushToast("Couldn't send your answer", 'Check the connection and try again.');
}
};
@@ -1892,6 +1912,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const currentChannel = isChannel ? channels.find((c) => c.id === selectedId) : null;
const currentKwant = !isChannel ? kwants.find((k) => k.id === selectedId) : null;
+ // Approvals belong in the asking bot's chat, or a channel it's in.
+ const openChat: OpenChat | null = isChannel
+ ? currentChannel
+ ? { kind: 'channel', channelId: currentChannel.id, memberIds: [currentChannel.lead_kwant_id, ...(currentChannel.member_kwants ?? [])] }
+ : null
+ : selectedId
+ ? { kind: 'kwant', kwantId: selectedId, threadId: openThreadId }
+ : null;
+ const approvalsHere = approvalsForChat(pendingApprovals, openChat);
const currentTeam = selectedTeamId
? teams.find((t) => t.id === selectedTeamId)
: isChannel && currentChannel?.name.startsWith('team-')
@@ -2376,7 +2405,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
);
const away = (
- <AwayPage since={awaySinceRef.current} onSince={(t) => (awaySinceRef.current = t)} onOpen={openAwayItem} onCounts={setAwayCount}
+ <AwayPage since={awaySinceRef.current} onSince={(t) => (awaySinceRef.current = t)} onOpen={openAwayItem} onCounts={setAwayCount} onApprovalResolved={dropApproval}
onBack={isPhone ? () => { setShowAway(false); setPhoneView('list'); } : undefined}
/>
);
@@ -2391,7 +2420,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onJumpToLatest={() => setHistoryWindow(null)}
streamingText={isCurrentContextStreaming ? streamingText : ''}
streamingThinking={isCurrentContextStreaming ? streamingThinking : ''}
- pendingApproval={pendingApproval}
+ pendingApprovals={approvalsHere}
isStreaming={isCurrentContextStreaming}
streamingSpeakerName={live[openCtx] || undefined}
onSendMessage={handleSendMessage}
diff --git a/frontend/src/approvals.ts b/frontend/src/approvals.ts
new file mode 100644
index 00000000..9b842d8b
--- /dev/null
+++ b/frontend/src/approvals.ts
@@ -0,0 +1,84 @@
+// Pending tool approvals: one list fed by the live ApprovalRequired event and, after a reload or
+// reconnect, by `GET /api/away`'s waiting items, so a card never depends on the page having been
+// open when the bot asked. Pure helpers, shared by the app and the node tests.
+
+import type { PendingApproval } from './components/ModernApprovalCard';
+import type { AwayItem, AwayLink } from './away';
+
+/** A card plus where it belongs: the asking bot and, when the server knows it, the conversation. */
+export interface ChatApproval extends PendingApproval {
+ kwant_id: string | null;
+ link: AwayLink | null;
+}
+
+const str = (v: unknown) => (typeof v === 'string' && v ? v : null);
+
+/** From the live SSE event's data. */
+export function approvalFromEvent(data: { id: string; tool_name: string; details?: Record<string, unknown> }): ChatApproval {
+ const details = data.details ?? {};
+ return { id: data.id, tool_name: data.tool_name, details, kwant_id: str(details.kwant_id), link: null };
+}
+
+/**
+ * From a "While you were away" approval item. Servers that send `tool_name`/`details` give the full
+ * card; older ones only a title ("Use Bash") and a flat summary, which the card shows as text.
+ */
+export function approvalFromAway(item: AwayItem): ChatApproval {
+ const hasDetails = !!item.details && typeof item.details === 'object' && !Array.isArray(item.details);
+ const tool = item.tool_name || item.title.replace(/^Use\s+/, '').replace(/\s+\(.*\)$/, '');
+ const details: Record<string, unknown> = hasDetails
+ ? { kwant_name: item.kwant_name, ...item.details }
+ : { source: 'summary', tool, summary: item.summary, kwant_id: item.kwant_id, kwant_name: item.kwant_name };
+ const link = item.link && (item.link.thread_id || item.link.channel_id || item.link.direct_kwant_id) ? item.link : null;
+ return { id: item.id, tool_name: tool, details, kwant_id: item.kwant_id || str(details.kwant_id), link };
+}
+
+/** The server's waiting approvals, newest first, as cards. */
+export const approvalsFromAway = (waiting: AwayItem[]): ChatApproval[] =>
+ waiting.filter((i) => i.kind === 'approval').map(approvalFromAway);
+
+/** Adds or refreshes one card, keeping the richer details when the live event already brought them. */
+export function upsertApproval(list: ChatApproval[], next: ChatApproval): ChatApproval[] {
+ const i = list.findIndex((a) => a.id === next.id);
+ if (i < 0) return [...list, next];
+ const prev = list[i];
+ const keepPrev = prev.details.source !== 'summary' && next.details.source === 'summary';
+ const merged: ChatApproval = keepPrev ? { ...prev, link: next.link ?? prev.link } : { ...next, link: next.link ?? prev.link };
+ return list.map((a, j) => (j === i ? merged : a));
+}
+
+/**
+ * The server's list replaces ours (answered or expired ones drop out), but a card that arrived
+ * live after the fetch started stays until the next sync, and live details beat a summary.
+ */
+export function syncApprovals(list: ChatApproval[], fromServer: ChatApproval[], liveSince: Set<string> = new Set()): ChatApproval[] {
+ const live = list.filter((a) => liveSince.has(a.id) && !fromServer.some((s) => s.id === a.id));
+ const synced = fromServer.map((s) => {
+ const prev = list.find((a) => a.id === s.id);
+ return prev ? upsertApproval([prev], s)[0] : s;
+ });
+ return [...synced, ...live];
+}
+
+export const withoutApproval = (list: ChatApproval[], id: string): ChatApproval[] => list.filter((a) => a.id !== id);
+
+/** The open chat: a bot's direct chat (or one of its conversations), or a channel and its members. */
+export type OpenChat =
+ | { kind: 'kwant'; kwantId: string; threadId?: string | null }
+ | { kind: 'channel'; channelId: string; memberIds: string[] };
+
+/**
+ * The cards that belong in the open chat. With a conversation link, only there; else the asking
+ * bot's direct chat or any channel it's in. A card with no bot at all shows wherever you are.
+ */
+export function approvalsForChat(list: ChatApproval[], chat: OpenChat | null): ChatApproval[] {
+ if (!chat) return [];
+ return list.filter((a) => {
+ const l = a.link;
+ if (l?.channel_id) return chat.kind === 'channel' && chat.channelId === l.channel_id;
+ if (l?.thread_id) return chat.kind === 'kwant' && chat.threadId === l.thread_id;
+ if (l?.direct_kwant_id) return chat.kind === 'kwant' && chat.kwantId === l.direct_kwant_id;
+ if (!a.kwant_id) return true;
+ return chat.kind === 'kwant' ? chat.kwantId === a.kwant_id : chat.memberIds.includes(a.kwant_id);
+ });
+}
diff --git a/frontend/src/away.ts b/frontend/src/away.ts
index cb764bb9..fa89896d 100644
--- a/frontend/src/away.ts
+++ b/frontend/src/away.ts
@@ -23,6 +23,9 @@ export interface AwayItem {
link: AwayLink;
/** Questions only. */
choices?: string[];
+ /** Approvals only, from servers that send them: the tool and the card's details. */
+ tool_name?: string;
+ details?: Record<string, unknown>;
}
export interface AwayCounts {
diff --git a/frontend/src/components/AwayView.tsx b/frontend/src/components/AwayView.tsx
index 34ce353a..1aa5411a 100644
--- a/frontend/src/components/AwayView.tsx
+++ b/frontend/src/components/AwayView.tsx
@@ -1,6 +1,8 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
-import { AlertTriangle, Check, CheckCheck, CheckCircle2, ChevronLeft, Inbox, Loader2, RefreshCw, X } from 'lucide-react';
+import { AlertTriangle, CheckCircle2, ChevronLeft, Inbox, Loader2, RefreshCw } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
+import { ModernApprovalCard } from './ModernApprovalCard';
+import { approvalFromAway } from '../approvals';
import {
AWAY_SECTIONS,
ApprovalDecision,
@@ -76,7 +78,7 @@ export const AwayView: React.FC<AwayViewProps> = ({ data, loading, error, notice
</div>
<p className="mt-0.5 text-sm font-medium text-zinc-100 truncate">{item.title}</p>
{/* A question's summary just lists its choices, which are buttons below. */}
- {item.summary && !(item.kind === 'question' && item.choices?.length) && <p className="text-xs text-zinc-400 truncate">{item.summary}</p>}
+ {item.summary && item.kind !== 'approval' && !(item.kind === 'question' && item.choices?.length) && <p className="text-xs text-zinc-400 truncate">{item.summary}</p>}
</div>
</button>
@@ -97,16 +99,8 @@ export const AwayView: React.FC<AwayViewProps> = ({ data, loading, error, notice
)}
{item.kind === 'approval' && (
- <div role="group" aria-label={`Decide: ${item.title}`} className="px-3 pb-3 sm:pl-[54px] flex flex-wrap gap-2">
- <button type="button" disabled={disabled} onClick={() => onResolve(item, 'allow_once')} className={`${actionBtn} text-white bg-emerald-600 hover:bg-emerald-500`}>
- <Check size={13} aria-hidden="true" /> Allow once
- </button>
- <button type="button" disabled={disabled} onClick={() => onResolve(item, 'always_allow')} className={`${actionBtn} text-white bg-sky-600 hover:bg-sky-500`}>
- <CheckCheck size={13} aria-hidden="true" /> Always allow
- </button>
- <button type="button" disabled={disabled} onClick={() => onResolve(item, 'deny')} className={`${actionBtn} text-zinc-300 bg-zinc-800 hover:bg-zinc-700`}>
- <X size={13} aria-hidden="true" /> Deny
- </button>
+ <div className="px-3 pb-1 sm:pl-[54px] [&>div]:my-0 [&>div]:mb-2">
+ <ModernApprovalCard approval={approvalFromAway(item)} disabled={disabled} onResolve={(_, decision) => onResolve(item, decision)} />
</div>
)}
@@ -221,11 +215,13 @@ export interface AwayPageProps {
onOpen: (item: AwayItem) => void;
/** New unseen counts for the sidebar badge. */
onCounts: (total: number) => void;
+ /** An approval was answered here, so the chat drops its card too. */
+ onApprovalResolved?: (id: string) => void;
onBack?: () => void;
}
/** Loads the page, marks it seen, and runs the one-tap actions. */
-export const AwayPage: React.FC<AwayPageProps> = ({ since = null, onSince, onOpen, onCounts, onBack }) => {
+export const AwayPage: React.FC<AwayPageProps> = ({ since = null, onSince, onOpen, onCounts, onApprovalResolved, onBack }) => {
const [data, setData] = useState<AwayResponse | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -302,7 +298,19 @@ export const AwayPage: React.FC<AwayPageProps> = ({ since = null, onSince, onOpe
onBack={onBack}
onOpen={onOpen}
onAnswer={(item, choice) => act(item, () => awayApi.answer(item.id, choice))}
- onResolve={(item, decision) => act(item, () => awayApi.resolve(item.id, decision))}
+ onResolve={(item, decision) =>
+ act(item, async () => {
+ try {
+ const res = await awayApi.resolve(item.id, decision);
+ onApprovalResolved?.(item.id);
+ return res;
+ } catch (err) {
+ // Lapsed meanwhile: the chat's card is stale too.
+ if (err instanceof AwayError && (err.status === 409 || err.status === 404)) onApprovalResolved?.(item.id);
+ throw err;
+ }
+ })
+ }
/>
);
};
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 320958c1..968a96d2 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -105,7 +105,8 @@ export interface ChatViewProps {
messages: ChatMessage[];
streamingText: string;
streamingThinking: string;
- pendingApproval: PendingApproval | null;
+ /** Tool approvals waiting in this chat, oldest first. */
+ pendingApprovals: PendingApproval[];
isStreaming: boolean;
streamingSpeakerName?: string;
/** `attachments` are files already uploaded from the composer. */
@@ -274,7 +275,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
messages,
streamingText,
streamingThinking,
- pendingApproval,
+ pendingApprovals,
isStreaming,
streamingSpeakerName,
onSendMessage,
@@ -472,7 +473,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (scrollRef.current && stickRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
- }, [messages, streamingText, streamingThinking, pendingApproval, routingState, queued, contextKey]);
+ }, [messages, streamingText, streamingThinking, pendingApprovals.length, routingState, queued, contextKey]);
// Jump to a search hit: open its folded discussion if needed, then centre and flash it.
// Runs after the auto-scroll above, so it wins.
@@ -1095,12 +1096,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
{/* Pending Security Approval Ticket */}
- {pendingApproval && (
- <ModernApprovalCard
- approval={pendingApproval}
- onResolve={onResolveApproval}
- />
- )}
+ {pendingApprovals.map((approval) => (
+ <ModernApprovalCard key={approval.id} approval={approval} onResolve={onResolveApproval} />
+ ))}
</div>
{/* Suggestion Prompts Pill Bar */}
diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsx
index d6ae19e1..4d6c7438 100644
--- a/frontend/src/components/ModernApprovalCard.tsx
+++ b/frontend/src/components/ModernApprovalCard.tsx
@@ -12,6 +12,8 @@ export interface PendingApproval {
interface ModernApprovalCardProps {
approval: PendingApproval;
onResolve: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
+ /** While an answer is being sent. */
+ disabled?: boolean;
}
/** Server/tool/arguments of an MCP approval, or null for other tools. */
@@ -42,6 +44,17 @@ const BUILTIN_SHELL = ['Bash'];
const BUILTIN_FILE = ['Write', 'Edit', 'MultiEdit', 'NotebookEdit'];
const s = (v: unknown) => (typeof v === 'string' && v ? v : null);
+/**
+ * An approval known only by its tool and a one-line summary (a reload against a server that
+ * doesn't send the details yet), or null.
+ */
+export const summaryView = (approval: PendingApproval) => {
+ const d = approval.details ?? {};
+ if (d.source !== 'summary') return null;
+ const tool = s(d.tool) ?? approval.tool_name;
+ return { tool, kwant: s(d.kwant_name), summary: s(d.summary), builtin: BUILTIN_SHELL.includes(tool) || BUILTIN_FILE.includes(tool) };
+};
+
/**
* A Claude CLI built-in tool (Bash, Write, Edit, ...) the bot asks to use: the command or file in
* plain words, or null for other tools. Reads `details.arguments` (or `details.input`, the CLI's
@@ -51,7 +64,7 @@ export const builtinView = (approval: PendingApproval) => {
const d = approval.details ?? {};
const tool = s(d.tool) ?? approval.tool_name;
const known = BUILTIN_SHELL.includes(tool) || BUILTIN_FILE.includes(tool);
- if (d.source !== 'claude_builtin' && !known) return null;
+ if (d.source === 'summary' || (d.source !== 'claude_builtin' && !known)) return null;
const raw = d.arguments ?? d.input;
const args = (raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}) as Record<string, unknown>;
const base = { tool, kwant: s(d.kwant_name), cwd: s(d.cwd), outsideFolder: d.outside_folder === true };
@@ -77,15 +90,20 @@ export const builtinView = (approval: PendingApproval) => {
export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
approval,
onResolve,
+ disabled = false,
}) => {
const handleDecision = (decision: 'allow_once' | 'always_allow' | 'deny') => {
+ if (disabled) return;
playSfx('click');
onResolve(approval.id, decision);
};
const mcp = mcpView(approval);
const shell = localShellView(approval);
const builtin = shell || mcp ? null : builtinView(approval);
- const who = builtin?.kwant ? <span className="font-medium text-zinc-100">{builtin.kwant}</span> : 'A bot';
+ const summary = summaryView(approval);
+ const name = builtin?.kwant ?? summary?.kwant;
+ const who = name ? <span className="font-medium text-zinc-100">{name}</span> : 'A bot';
+ const perSession = !!builtin || !!summary?.builtin;
return (
<div className="my-3 border border-amber-500/30 bg-amber-950/20 rounded-xl p-4 text-zinc-100 max-w-2xl shadow-lg backdrop-blur-sm">
@@ -106,6 +124,13 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
</p>
)}
</div>
+ ) : summary ? (
+ <div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs space-y-2 mb-3">
+ <p className="text-zinc-300">
+ {who} wants to use <span className="font-medium text-sky-200">{summary.tool}</span>.
+ </p>
+ {summary.summary && <p className="text-[11px] text-zinc-400 break-words">{summary.summary}</p>}
+ </div>
) : builtin?.kind === 'shell' ? (
<div className="bg-zinc-900/90 rounded-lg p-3 border border-zinc-800 text-xs space-y-2 mb-3">
<p className="flex items-center gap-1.5 text-zinc-300">
@@ -194,8 +219,9 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
<div className="flex flex-wrap items-center justify-end gap-2">
<button
type="button"
+ disabled={disabled}
onClick={() => handleDecision('deny')}
- className="flex items-center gap-1.5 px-3 py-1.5 min-h-[40px] sm:min-h-0 rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 text-xs font-medium text-zinc-300 bg-zinc-800 hover:bg-zinc-700 transition-colors"
+ className="flex items-center gap-1.5 px-3 py-1.5 min-h-[40px] sm:min-h-0 rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 text-xs font-medium text-zinc-300 bg-zinc-800 hover:bg-zinc-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<X size={14} />
<span>Deny</span>
@@ -203,8 +229,9 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
<button
type="button"
+ disabled={disabled}
onClick={() => handleDecision('allow_once')}
- className="flex items-center gap-1.5 px-3 py-1.5 min-h-[40px] sm:min-h-0 rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 text-xs font-medium text-white bg-emerald-600 hover:bg-emerald-500 transition-colors shadow-sm"
+ className="flex items-center gap-1.5 px-3 py-1.5 min-h-[40px] sm:min-h-0 rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 text-xs font-medium text-white bg-emerald-600 hover:bg-emerald-500 transition-colors shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
>
<Check size={14} />
<span>Allow Once</span>
@@ -214,12 +241,13 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
{!shell && (
<button
type="button"
+ disabled={disabled}
onClick={() => handleDecision('always_allow')}
- title={mcp || builtin ? 'Allow this tool for this bot until the app restarts' : undefined}
- className="flex items-center gap-1.5 px-3 py-1.5 min-h-[40px] sm:min-h-0 rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm"
+ title={perSession ? 'Allow this tool for this bot in this conversation' : mcp ? 'Allow this tool for this bot until the app restarts' : undefined}
+ className="flex items-center gap-1.5 px-3 py-1.5 min-h-[40px] sm:min-h-0 rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors shadow-sm disabled:opacity-50 disabled:cursor-not-allowed"
>
<CheckCheck size={14} />
- <span>{builtin ? 'Always this session' : 'Always Allow'}</span>
+ <span>{perSession ? 'Always this session' : 'Always Allow'}</span>
</button>
)}
</div>
diff --git a/frontend/tests/approvals.test.mjs b/frontend/tests/approvals.test.mjs
new file mode 100644
index 00000000..28b31b88
--- /dev/null
+++ b/frontend/tests/approvals.test.mjs
@@ -0,0 +1,101 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+// Sound settings and the chat read localStorage on import.
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const a = await loadBundled(`export * from './src/approvals';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { ChatView } from './src/components/ChatView';
+ import { AwayView } from './src/components/AwayView';
+ export const chat = (props) => renderToStaticMarkup(React.createElement(ChatView, props));
+ export const away = (props) => renderToStaticMarkup(React.createElement(AwayView, props));
+`);
+
+// Shaped like a pending claude_builtin ticket in GET /api/away (BrokerApprover in mcp_runtime.rs).
+const bashItem = (over = {}) => ({
+ kind: 'approval', id: 'ap1', kwant_id: 'k-dev', kwant_name: 'Dev', title: 'Use Bash', status: 'pending',
+ summary: 'command: touch x, description: Create x', timestamp: '2026-10-19T21:00:00Z',
+ link: { thread_id: null, channel_id: null, direct_kwant_id: null },
+ tool_name: 'Bash',
+ details: {
+ source: 'claude_builtin', tool: 'Bash', arguments: { command: 'touch x', description: 'Create x' },
+ cwd: '/tmp/bots/dev', outside_folder: false, kwant_id: 'k-dev', kwant_name: 'Dev',
+ },
+ ...over,
+});
+const awayResp = (waiting) => ({
+ since: '2026-10-12T21:00:00Z', last_seen: null, now: '2026-10-19T21:05:00Z', stuck_after_minutes: 30,
+ waiting, finished: [], failed: [], unseen: { waiting: waiting.length, finished: 0, failed: 0, total: waiting.length },
+});
+
+const chatProps = (pendingApprovals) => ({
+ title: 'Dev', subtitle: 'Backend', messages: [], streamingText: '', streamingThinking: '', isStreaming: true,
+ pendingApprovals, onSendMessage: () => {}, onResolveApproval: () => {}, kwants: [], teams: [],
+});
+
+test('a Bash approval loaded after a reload renders as the built-in card inline in the bot chat', () => {
+ // The page opens after the ApprovalRequired event already fired: only the server's list has it.
+ const loaded = a.syncApprovals([], a.approvalsFromAway(awayResp([bashItem()]).waiting));
+ const here = a.approvalsForChat(loaded, { kind: 'kwant', kwantId: 'k-dev', threadId: null });
+ assert.equal(here.length, 1);
+ const html = ui.chat(chatProps(here));
+ assert.match(html, /Dev<\/span> wants to run a command/);
+ assert.match(html, /<pre[^>]*>touch x<\/pre>/);
+ assert.match(html, /In folder:.*\/tmp\/bots\/dev/);
+ assert.match(html, /Allow Once/);
+ assert.match(html, /Always this session/);
+ assert.match(html, /Deny/);
+ assert.doesNotMatch(html, /command: touch x/, 'not the old raw summary');
+});
+
+test('the card stays out of other chats, but shows in a channel the bot is in', () => {
+ const loaded = a.approvalsFromAway([bashItem()]);
+ assert.equal(a.approvalsForChat(loaded, { kind: 'kwant', kwantId: 'k-other' }).length, 0);
+ assert.equal(a.approvalsForChat(loaded, { kind: 'channel', channelId: 'c1', memberIds: ['k-x'] }).length, 0);
+ assert.equal(a.approvalsForChat(loaded, { kind: 'channel', channelId: 'c1', memberIds: ['k-dev'] }).length, 1);
+ assert.equal(a.approvalsForChat(loaded, null).length, 0);
+ // With the conversation known, only there.
+ const linked = a.approvalsFromAway([bashItem({ link: { thread_id: null, channel_id: 'c2', direct_kwant_id: null } })]);
+ assert.equal(a.approvalsForChat(linked, { kind: 'kwant', kwantId: 'k-dev' }).length, 0);
+ assert.equal(a.approvalsForChat(linked, { kind: 'channel', channelId: 'c2', memberIds: [] }).length, 1);
+});
+
+test('While you were away shows the same card and labels, not raw text', () => {
+ const html = ui.away({
+ data: awayResp([bashItem()]), loading: false, error: null, busy: null, notice: null,
+ onRefresh: () => {}, onOpen: () => {}, onAnswer: () => {}, onResolve: () => {},
+ });
+ assert.match(html, /<pre[^>]*>touch x<\/pre>/);
+ assert.match(html, /In folder:.*\/tmp\/bots\/dev/);
+ assert.match(html, /Always this session/);
+ assert.doesNotMatch(html, /Always allow</, 'no old lowercase raw-button row');
+ assert.doesNotMatch(html, /command: touch x/);
+});
+
+test('an older server without details still gets a card with the summary and session label', () => {
+ const old = bashItem({ tool_name: undefined, details: undefined });
+ const [card] = a.approvalsFromAway([old]);
+ assert.equal(card.tool_name, 'Bash');
+ assert.equal(card.kwant_id, 'k-dev');
+ const html = ui.chat(chatProps([card]));
+ assert.match(html, /Dev<\/span> wants to use <span[^>]*>Bash<\/span>/);
+ assert.match(html, /command: touch x, description: Create x/);
+ assert.match(html, /Always this session/);
+});
+
+test('live and loaded lists merge: answered ones drop, live details beat a summary, a fresh live one stays', () => {
+ const live = a.approvalFromEvent({ id: 'ap1', tool_name: 'Bash', details: bashItem().details });
+ const fresh = a.approvalFromEvent({ id: 'ap2', tool_name: 'Bash', details: { ...bashItem().details, arguments: { command: 'rm y' } } });
+ const gone = a.approvalFromEvent({ id: 'ap0', tool_name: 'Bash', details: bashItem().details });
+ const summaryOnly = a.approvalsFromAway([bashItem({ tool_name: undefined, details: undefined })]);
+ const next = a.syncApprovals([gone, live, fresh], summaryOnly, new Set(['ap2']));
+ assert.deepEqual(next.map((x) => x.id), ['ap1', 'ap2']);
+ assert.equal(next[0].details.source, 'claude_builtin', 'kept the live details');
+ assert.deepEqual(a.withoutApproval(next, 'ap1').map((x) => x.id), ['ap2']);
+ // Two asks at once both show.
+ assert.equal(a.upsertApproval([live], fresh).length, 2);
+});
diff --git a/frontend/tests/away.test.mjs b/frontend/tests/away.test.mjs
index 42ba12af..406465e6 100644
--- a/frontend/tests/away.test.mjs
+++ b/frontend/tests/away.test.mjs
@@ -109,7 +109,9 @@ test('three sections with agent, title, summary and time; one-tap actions', () =
assert.match(html, /From the last 7 days/);
assert.match(html, />Yes<\/button>/);
assert.match(html, />No<\/button>/);
- for (const b of ['Allow once', 'Always allow', 'Deny']) assert.match(html, new RegExp(b));
+ // An approval is the same card as in the chat, with its labels.
+ for (const b of ['Allow Once', 'Always Allow', 'Deny']) assert.match(html, new RegExp(b));
+ assert.match(html, /Lead<\/span> wants to use <span[^>]*>send<\/span>/);
assert.match(html, /Handoff done/);
assert.match(html, /Stuck/);
assert.doesNotMatch(html, /all caught up/);