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.

22d: the owner sees a customer's refused call in that customer's chat (#718)

Oleksandr Ivanchenkof8b6c6f59ea5
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 75f6030e..ffc2d4f5 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -74,7 +74,7 @@ import { IdeaDropToast, type IdeaDropToastState } from './components/IdeaDropToa
import { JAR_DROPPED, JAR_SEND_FAILED, ideaSendOutcome, useJarWobble, wobbleJar } from './ideaShell';
import { Bot, HelpCircle, Inbox, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';
import { TG_EVENT, TelegramEventDetail, forThisSpace } from './telegram';
-import { ChatApproval, OpenChat, addSettled, settledFromRecords, withdrawApproval, approvalFromEvent, lateAnswerText, approvalsForChat, approvalsFromAway, syncApprovals, upsertApproval, withoutApproval } from './approvals';
+import { ChatApproval, OpenChat, addSettled, refusedFromRecords, settledByTime, settledFromRecords, withdrawApproval, approvalFromEvent, lateAnswerText, approvalsForChat, approvalsFromAway, syncApprovals, upsertApproval, withoutApproval } from './approvals';
import type { AgentFormData } from './components/NewAgentModal';
import { NewTeamModal } from './components/NewTeamModal';
import { ReadyTeamsProvider, TeamNeedsTop, type ReadyTeam } from './components/ReadyTeams';
@@ -956,6 +956,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
skillsApi.list({ status: 'pending' }).then(setPendingSkills, () => undefined);
refreshAwayCount();
awayApi.approvals('allowed_once').then((rows) => setSettledApprovals((prev) => addSettled(prev, settledFromRecords(rows))), () => undefined);
+ // 22d: a customer's call nobody allowed, as a quiet line in that customer's chat.
+ awayApi.approvals('refused').then((rows) => setSettledApprovals((prev) => addSettled(prev, refusedFromRecords(rows))), () => undefined);
questionsApi.listOpen().then((list) => {
// Closed ones seen live stay; open ones come from the server.
setQuestions((prev) => {
@@ -4340,7 +4342,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
/>
) : undefined
}
- settledApprovals={approvalsForChat(settledApprovals, openChat)}
+ settledApprovals={settledByTime(approvalsForChat(settledApprovals, openChat))}
home={chatHome}
isStreaming={isCurrentContextStreaming}
streamingSpeakerName={live[openCtx] || undefined}
diff --git a/frontend/src/approvals.ts b/frontend/src/approvals.ts
index a78c1d9c..9df23e12 100644
--- a/frontend/src/approvals.ts
+++ b/frontend/src/approvals.ts
@@ -9,6 +9,8 @@ import type { AwayItem, AwayLink } from './away';
export interface ChatApproval extends PendingApproval {
kwant_id: string | null;
link: AwayLink | null;
+ /** 22d: a customer's call nobody allowed (a closed `refused` row), drawn as a quiet line, never a card. */
+ refused?: true;
}
const str = (v: unknown) => (typeof v === 'string' && v ? v : null);
@@ -135,6 +137,8 @@ export interface ApprovalRecord {
answered_via?: string | null;
created_at?: string | null;
details?: unknown;
+ /** 22a: the chat the call happened in, in a card's shape; null when the server didn't store one. */
+ link?: AwayLink | null;
}
/** How long after it was asked a Telegram-allowed approval is still drawn after a reload. */
@@ -159,6 +163,43 @@ export function settledFromRecords(rows: unknown, now = Date.now()): ChatApprova
return out.reverse(); // the server sends newest first; the chat reads oldest first
}
+/** A row's chat when it names exactly one; anything else (missing, empty, malformed) is no chat. */
+function recordLink(v: unknown): AwayLink | null {
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return null;
+ const l = v as Record<string, unknown>;
+ const link: AwayLink = { thread_id: str(l.thread_id), channel_id: str(l.channel_id), direct_kwant_id: str(l.direct_kwant_id) };
+ return [link.thread_id, link.channel_id, link.direct_kwant_id].filter(Boolean).length === 1 ? link : null;
+}
+
+/**
+ * 22d: `GET /api/approvals?status=refused` rows from the last day: a customer's call that didn't run
+ * because nobody allowed it. Each is drawn only in the chat it happened in, so a row without a chat
+ * (stored before 22a) is drawn nowhere, never in "every chat with this bot".
+ */
+export function refusedFromRecords(rows: unknown, now = Date.now()): ChatApproval[] {
+ if (!Array.isArray(rows)) return [];
+ const out: ChatApproval[] = [];
+ for (const r of rows as ApprovalRecord[]) {
+ if (!r || typeof r.id !== 'string' || r.status !== 'refused') continue;
+ const link = recordLink(r.link);
+ if (!link) continue;
+ const at = str(r.created_at) ? Date.parse(r.created_at as string) : NaN;
+ if (!Number.isFinite(at) || now - at > SETTLED_KEEP_MS) continue;
+ const details = r.details && typeof r.details === 'object' && !Array.isArray(r.details) ? (r.details as Record<string, unknown>) : {};
+ out.push({ id: r.id, tool_name: str(r.tool_name) ?? 'tool', details, kwant_id: str(r.kwant_id) ?? str(details.kwant_id), link, asked_at: r.created_at as string, refused: true });
+ }
+ return out.reverse();
+}
+
+/** Settled lines oldest first by when they were asked; a line with no time keeps its place after the timed ones. */
+export function settledByTime(list: ChatApproval[]): ChatApproval[] {
+ const t = (a: ChatApproval) => {
+ const v = a.asked_at ? Date.parse(a.asked_at) : NaN;
+ return Number.isFinite(v) ? v : Infinity;
+ };
+ return list.map((a, i) => [a, i] as const).sort((x, y) => t(x[0]) - t(y[0]) || x[1] - y[1]).map(([a]) => a);
+}
+
/** Adds settled cards once each, keeping the order they came in. */
export function addSettled(list: ChatApproval[], more: ChatApproval[]): ChatApproval[] {
const seen = new Set(list.map((a) => a.id));
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index f3c620cd..d4cc4797 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -37,6 +37,7 @@ import { DelegationMeta, parseDelegationMeta } from '../threads';
import { QuestionMeta, foldedAnswerIds, parseMetaObject, parseQuestionMeta } from '../questions';
import { fromTelegram, sentToTelegram } from '../telegram';
import { AllowedFromTelegram, ViaTelegram } from './TelegramMarks';
+import { RefusedCustomerCall } from './RefusedCustomerCall';
import { HumanStep, HumanStepMeta, parseHumanStepMeta } from '../humanSteps';
import { LiveActivity, foldLiveSteps, hasThinkingText, parseActivityMeta } from '../activity';
import { LiveActivityList, SavedActivityList } from './ActivityList';
@@ -240,8 +241,8 @@ export interface ChatViewProps {
pendingApprovals: PendingApproval[];
/** 0.8.0 B3: this bot's pre-push cards (Dev mode), shown above its approvals. */
prepush?: React.ReactNode;
- /** Approvals answered in Telegram while this chat was open (G4): kept as a resolved row. */
- settledApprovals?: PendingApproval[];
+ /** Approvals answered in Telegram (G4), kept as a resolved row; `refused` marks a customer's call nobody allowed (22d). */
+ settledApprovals?: (PendingApproval & { refused?: true })[];
isStreaming: boolean;
streamingSpeakerName?: string;
/** `attachments` are files already uploaded from the composer. */
@@ -2616,10 +2617,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* P4: the running bot's shares, already in the place its saved reply will give them */}
{liveRowShown && arranged.live.map((m) => renderMessage(m))}
- {/* Approvals allowed in Telegram (G4): "✓ Allowed once from Telegram", live and after a reload */}
- {settledApprovals.map((approval) => (
- <AllowedFromTelegram key={approval.id} lead={approvalLead(approval)} />
- ))}
+ {/* Approvals allowed in Telegram (G4): "✓ Allowed once from Telegram", live and after a reload;
+ 22d: a customer's call nobody allowed, in that customer's chat */}
+ {settledApprovals.map((approval) =>
+ approval.refused ? (
+ <RefusedCustomerCall key={approval.id} approval={approval} />
+ ) : (
+ <AllowedFromTelegram key={approval.id} lead={approvalLead(approval)} />
+ ),
+ )}
{/* 0.8.0 B3: checks before this bot pushes */}
{prepush}
diff --git a/frontend/src/components/RefusedCustomerCall.tsx b/frontend/src/components/RefusedCustomerCall.tsx
new file mode 100644
index 00000000..88811def
--- /dev/null
+++ b/frontend/src/components/RefusedCustomerCall.tsx
@@ -0,0 +1,35 @@
+// 22d: a customer's call nobody allowed, kept in that customer's chat as one quiet settled line.
+// Nothing to answer: the call is already refused and the customer was told nothing new.
+import React from 'react';
+import { ShieldX } from 'lucide-react';
+import { approvalAction, type PendingApproval } from './ModernApprovalCard';
+import { toolAction } from '../toolLabel';
+import { localClock } from '../clock';
+
+/** kwant's own tools (the server's SELF_SERVER_NAME): the owner reads "use memory search", not "(kwnt_tools)". */
+const OWN_TOOLS = 'kwnt_tools';
+
+/** The call in the card's words, without kwant's internal server name. */
+function refusedAction(approval: PendingApproval): string {
+ const d = approval.details ?? {};
+ const own = /^mcp__kwnt_tools__(.+)$/.exec(approval.tool_name ?? '');
+ if (d.server === OWN_TOOLS || own) return toolAction(typeof d.tool === 'string' && d.tool ? d.tool : own?.[1] ?? approval.tool_name);
+ return approvalAction(approval);
+}
+
+/** "A customer's message tried to <what the card would ask>. It didn't run, because nobody allowed it." */
+export const refusedCallText = (approval: PendingApproval): string =>
+ `A customer's message tried to ${refusedAction(approval)}. It didn't run, because nobody allowed it.`;
+
+/** The line, then " · <time>" when the row has one, in the line's own zinc-400 (zinc-500 fails AA at 12 px). */
+export const RefusedCustomerCall: React.FC<{ approval: PendingApproval }> = ({ approval }) => {
+ const time = localClock(approval.asked_at ?? null);
+ return (
+ <div className="flex items-start gap-2 ml-0 sm:ml-[50px] max-w-3xl px-3 py-2 rounded-xl border border-zinc-800 bg-zinc-900/50 text-xs text-zinc-400" data-refused-call={approval.id}>
+ <ShieldX size={14} className="mt-0.5 shrink-0 text-zinc-500" aria-hidden="true" />
+ <p className="min-w-0 break-words leading-5">
+ {refusedCallText(approval)}{time && <> · {time}</>}
+ </p>
+ </div>
+ );
+};
diff --git a/frontend/tests/refusedCallInChat.test.mjs b/frontend/tests/refusedCallInChat.test.mjs
new file mode 100644
index 00000000..fc19a659
--- /dev/null
+++ b/frontend/tests/refusedCallInChat.test.mjs
@@ -0,0 +1,100 @@
+// 22d: a customer's call nobody allowed (a closed `refused` row with 22a's `link`) is one quiet line in
+// that customer's chat, and nowhere else. The Telegram "Allowed once" line is unchanged.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+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';
+ export { refusedCallText } from './src/components/RefusedCustomerCall';
+ export { localClock } from './src/clock';
+ export const chat = (props) => renderToStaticMarkup(React.createElement(ChatView, props));
+`);
+
+const now = Date.parse('2026-11-15T22:00:00Z');
+const thread = { thread_id: 'th-ann', channel_id: null, direct_kwant_id: null };
+// Shaped like GET /api/approvals?status=refused (src/server/approval_modes.rs list, 16d details).
+const refusedRow = (over = {}) => ({
+ id: 'ap_r1', kwant_id: 'k-shop', tool_name: 'mcp__kwnt_tools__memory_search', status: 'refused', answered_via: null,
+ created_at: '2026-11-15T21:00:00Z', link: thread,
+ details: { source: 'mcp', server: 'kwnt_tools', tool: 'memory_search', arguments: { query: 'x' }, kwant_id: 'k-shop', kwant_name: 'Shop', customer_chat: true, refused: 'nobody_allowed' },
+ ...over,
+});
+const telegramRow = { id: 'ap_t1', kwant_id: 'k-shop', tool_name: 'Bash', status: 'allowed_once', answered_via: 'telegram', created_at: '2026-11-15T21:30:00Z', details: { kwant_name: 'Shop' } };
+
+const customerThread = { kind: 'kwant', kwantId: 'k-shop', threadId: 'th-ann' };
+const directChat = { kind: 'kwant', kwantId: 'k-shop', threadId: null };
+const chatProps = (settledApprovals) => ({
+ title: 'Shop', subtitle: '', messages: [], streamingText: '', streamingThinking: '', isStreaming: false,
+ pendingApprovals: [], settledApprovals, onSendMessage: () => {}, onResolveApproval: () => {}, kwants: [], teams: [],
+});
+const LINE = "A customer&#x27;s message tried to use memory search. It didn&#x27;t run, because nobody allowed it.";
+
+test('a refused row with a thread link is drawn only in that thread, as one quiet line with no buttons', () => {
+ const settled = a.refusedFromRecords([refusedRow()], now);
+ assert.equal(settled.length, 1);
+ assert.equal(settled[0].refused, true);
+ assert.deepEqual(a.approvalsForChat(settled, directChat), [], "not in the bot's direct chat");
+ assert.deepEqual(a.approvalsForChat(settled, { kind: 'kwant', kwantId: 'k-shop', threadId: 'th-bob' }), [], "not in another customer's chat");
+ assert.deepEqual(a.approvalsForChat(settled, { kind: 'channel', channelId: 'ch1', memberIds: ['k-shop'] }), []);
+ const here = a.approvalsForChat(settled, customerThread);
+ assert.equal(here.length, 1);
+ const html = ui.chat(chatProps(here));
+ assert.ok(html.includes(LINE), html);
+ assert.match(html, /data-refused-call="ap_r1"/);
+ // Round 2 (Mira): the line ends with " · <time>" from the row's asked_at, like the Telegram line.
+ const p = /data-refused-call="ap_r1"[^>]*>[^]*?<p class="[^"]*">([^]*?)<\/p>/.exec(html)[1].replace(/<!-- -->/g, '').replace(/&#x27;/g, "'");
+ assert.ok(p.endsWith(` · ${ui.localClock(here[0].asked_at)}`), p);
+ assert.ok(p.startsWith(ui.refusedCallText(here[0])), p);
+ const noTime = ui.chat(chatProps([{ ...here[0], asked_at: undefined }]));
+ assert.ok(noTime.includes(`${LINE}</p>`), 'no asked_at: no time and no dot');
+ assert.doesNotMatch(html, /kwnt_tools/, 'no internal server name');
+ assert.doesNotMatch(html.slice(html.indexOf('data-refused-call')), /^[^]*?<button[^>]*>[^<]*(Allow|Deny)/, 'nothing to answer');
+ assert.doesNotMatch(html, /Allowed once from Telegram/);
+});
+
+test('a refused row without a chat (stored before 22a), or with a malformed one, is drawn nowhere', () => {
+ for (const link of [null, undefined, {}, { thread_id: '', channel_id: null, direct_kwant_id: null }, { thread_id: 'a', channel_id: 'b', direct_kwant_id: null }, 'th-ann']) {
+ const settled = a.refusedFromRecords([refusedRow({ link })], now);
+ assert.deepEqual(settled, [], JSON.stringify(link));
+ }
+});
+
+test('only refused rows from the last day; other statuses and junk are ignored; oldest first', () => {
+ const rows = [
+ refusedRow({ id: 'ap_r3', created_at: '2026-11-15T21:50:00Z' }),
+ refusedRow({ id: 'ap_r2', created_at: '2026-11-15T20:00:00Z' }),
+ refusedRow({ id: 'ap_old', created_at: '2026-11-13T20:00:00Z' }),
+ refusedRow({ id: 'ap_w', status: 'waiting' }),
+ refusedRow({ id: 'ap_nt', created_at: null }),
+ null,
+ ];
+ assert.deepEqual(a.refusedFromRecords(rows, now).map((r) => r.id), ['ap_r2', 'ap_r3']);
+ assert.deepEqual(a.refusedFromRecords({ error: 'x' }, now), []);
+});
+
+test('a channel or direct-chat link places it there, and a non-kwant tool reads like its card', () => {
+ const ch = a.refusedFromRecords([refusedRow({ link: { thread_id: null, channel_id: 'ch1', direct_kwant_id: null } })], now);
+ assert.equal(a.approvalsForChat(ch, { kind: 'channel', channelId: 'ch1', memberIds: [] }).length, 1);
+ assert.equal(a.approvalsForChat(ch, customerThread).length, 0);
+ const gh = a.refusedFromRecords([refusedRow({ tool_name: 'mcp__github__create_pull_request', details: { source: 'mcp', server: 'github', tool: 'create_pull_request', arguments: {} } })], now);
+ assert.equal(ui.refusedCallText(gh[0]), "A customer's message tried to open a pull request on GitHub. It didn't run, because nobody allowed it.");
+});
+
+test('an allowed_once Telegram row still reads "Allowed once from Telegram", and lines sort by time', () => {
+ const settled = a.addSettled(a.settledFromRecords([telegramRow], now), a.refusedFromRecords([refusedRow()], now));
+ // The Telegram row has no link: it stays in every chat with its bot, exactly as before.
+ assert.deepEqual(a.approvalsForChat(settled, directChat).map((r) => r.id), ['ap_t1']);
+ const here = a.settledByTime(a.approvalsForChat(settled, customerThread));
+ assert.deepEqual(here.map((r) => r.id), ['ap_r1', 'ap_t1'], 'the 21:00 refusal before the 21:30 Telegram allow');
+ const html = ui.chat(chatProps(here));
+ assert.match(html, /Shop: Bash · <b[^>]*>✓ Allowed once from Telegram<\/b>/);
+ assert.ok(html.indexOf('data-refused-call') < html.indexOf('data-resolved-via="telegram"'));
+ // Lines without a time keep their order after the timed ones.
+ assert.deepEqual(a.settledByTime([{ id: 'x' }, { id: 'y', asked_at: '2026-11-15T21:00:00Z' }, { id: 'z' }]).map((r) => r.id), ['y', 'x', 'z']);
+});