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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
29p deny-with-reason-card: Say why on the approval card (ships with 29o) (#839)
Oleksandr Ivanchenkob9cacde39e46
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 6409a9a2..8af4cf27 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -160,7 +160,7 @@ import {questionsApi,turnsAwaitingAnswer,} from './questions';-import { AwayError, AwayItem, affectsAway, awayApi } from './away';+import { AwayError, AwayItem, affectsAway, awayApi, resolveBody } from './away';import { asksHere, closedId, isHandOff, dismissKind, dropClosed, loadAskWindow, openTarget as askOpenTarget, resendTarget, retryRoute, switchFor, type AskAction, type Here } from './askHere';import { NeedsYouStrip } from './components/NeedsYouStrip';import { chainBudgetApi } from './chainBudget';@@ -2110,7 +2110,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({method: 'POST',headers: { 'Content-Type': 'application/json' },// 22f: the person's own "Allow without a backup" on a deploy kwant only guessed changes the database.- body: JSON.stringify(opts?.withoutBackup && decision === 'allow_once' ? { decision, without_backup: true } : { decision }),+ // 29p: a Deny with words from "Say why" carries them as `reason`.+ body: JSON.stringify(resolveBody(decision, opts)),});// Production floor (Dev mode): Allow without a fresh backup is refused and the card stays waiting.if (res.status === 409) {diff --git a/frontend/src/away.ts b/frontend/src/away.tsindex d83cfdfc..4a751c8d 100644--- a/frontend/src/away.ts+++ b/frontend/src/away.ts@@ -300,12 +300,29 @@ async function call<T>(method: string, url: string, body?: unknown): Promise<T>const enc = encodeURIComponent;+/** 29p: the longest reason a Deny carries (the card's field stops at this too). */+export const DENY_REASON_MAX = 500;++/**+ * The body of `POST /api/approvals/:id/resolve`, for the chat card and the Inbox alike. `without_backup` only+ * with Allow once (22f); `reason` only with a Deny that has text (29p, trimmed, cut to 500). Every other answer+ * sends just `{ decision }`, as before.+ */+export function resolveBody(+ decision: ApprovalDecision,+ opts: { withoutBackup?: boolean; reason?: string } = {},+): { decision: ApprovalDecision; without_backup?: true; reason?: string } {+ if (opts.withoutBackup && decision === 'allow_once') return { decision, without_backup: true };+ const reason = decision === 'deny' && typeof opts.reason === 'string' ? opts.reason.trim().slice(0, DENY_REASON_MAX).trim() : '';+ return reason ? { decision, reason } : { decision };+}+export const awayApi = {get: (since?: string) => call<AwayResponse>('GET', `/api/away${since ? `?since=${enc(since)}` : ''}`).then(normalizeAway),seen: () => call<{ last_seen: string }>('POST', '/api/away/seen'),answer: (id: string, choice: number) => call<unknown>('POST', `/api/questions/${enc(id)}/answer`, { choice }),- resolve: (id: string, decision: ApprovalDecision, withoutBackup = false) =>- call<unknown>('POST', `/api/approvals/${enc(id)}/resolve`, withoutBackup && decision === 'allow_once' ? { decision, without_backup: true } : { decision }),+ resolve: (id: string, decision: ApprovalDecision, withoutBackup = false, reason?: string) =>+ call<unknown>('POST', `/api/approvals/${enc(id)}/resolve`, resolveBody(decision, { withoutBackup, reason })),/** Approval records with this stored status, newest first (`answered_via` says where). */approvals: (status: string) => call<unknown>('GET', `/api/approvals?status=${enc(status)}`),/** 0.9.5: ask again for an approval that expired unanswered (starts a new turn; grants nothing). */diff --git a/frontend/src/components/AwayView.tsx b/frontend/src/components/AwayView.tsxindex f487a415..f9bbbdd6 100644--- a/frontend/src/components/AwayView.tsx+++ b/frontend/src/components/AwayView.tsx@@ -52,7 +52,7 @@ export interface AwayViewProps {onBack?: () => void;onOpen: (item: AwayItem) => void;onAnswer: (item: AwayItem, choice: number) => void;- onResolve: (item: AwayItem, decision: ApprovalDecision, withoutBackup?: boolean) => void;+ onResolve: (item: AwayItem, decision: ApprovalDecision, withoutBackup?: boolean, reason?: string) => void;/** Above the lists: what holds every bot (today's spending stop), not one bot's item. */top?: React.ReactNode;}@@ -115,7 +115,7 @@ export const AwayView: React.FC<AwayViewProps> = ({ data, loading, error, notice{item.kind === 'approval' && (<div className="px-3 pb-1 sm:pl-[54px] [&>div]:my-0 [&>div]:mb-2">- <ModernApprovalCard approval={approvalFromAway(item)} disabled={disabled} onResolve={(_, decision, opts) => onResolve(item, decision as ApprovalDecision, opts?.withoutBackup)} />+ <ModernApprovalCard approval={approvalFromAway(item)} disabled={disabled} onResolve={(_, decision, opts) => onResolve(item, decision as ApprovalDecision, opts?.withoutBackup, opts?.reason)} /></div>)}@@ -325,9 +325,9 @@ export const AwayPage: React.FC<AwayPageProps> = ({ since = null, onSince, onOpetop={top}onOpen={onOpen}onAnswer={(item, choice) => act(item, () => awayApi.answer(item.id, choice))}- onResolve={(item, decision, withoutBackup) =>+ onResolve={(item, decision, withoutBackup, reason) =>// Lapsed meanwhile: the chat's card is stale too (but not on a backup refusal: it is still waiting).- act(item, () => resolveFromList(item.id, onApprovalResolved, () => awayApi.resolve(item.id, decision, withoutBackup)), decision === 'deny')+ act(item, () => resolveFromList(item.id, onApprovalResolved, () => awayApi.resolve(item.id, decision, withoutBackup, reason)), decision === 'deny')}/>);diff --git a/frontend/src/components/InboxNew.tsx b/frontend/src/components/InboxNew.tsxindex b33b9fef..44916d53 100644--- a/frontend/src/components/InboxNew.tsx+++ b/frontend/src/components/InboxNew.tsx@@ -212,7 +212,7 @@ interface RowProps {busy: string | null;onPick: (i: InboxItem) => void;onAnswer: (i: InboxItem, choice: number) => void;- onResolve: (i: InboxItem, d: ApprovalDecision, withoutBackup?: boolean) => void;+ onResolve: (i: InboxItem, d: ApprovalDecision, withoutBackup?: boolean, reason?: string) => void;/** 0.9.5: Retry on a stopped item whose approval expired unanswered. */onRetry?: (i: InboxItem, approvalId: string) => void;/** A routine's review task in Done: its run's first line, as the run's own row would show it. */@@ -354,7 +354,7 @@ const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, o{item.kind === 'approval' && (<div className="px-3 pb-1 pl-[54px] [&>div]:my-0 [&>div]:mb-2">- <ModernApprovalCard approval={approvalFromAway(item as AwayItem)} disabled={disabled} onResolve={(_, d, opts) => onResolve(item, d as ApprovalDecision, opts?.withoutBackup)} />+ <ModernApprovalCard approval={approvalFromAway(item as AwayItem)} disabled={disabled} onResolve={(_, d, opts) => onResolve(item, d as ApprovalDecision, opts?.withoutBackup, opts?.reason)} /></div>)}@@ -822,10 +822,10 @@ export const InboxNew: React.FC<InboxNewProps> = ({const onAnswer = (item: InboxItem, choice: number) => act(item, () => awayApi.answer(item.id, choice));const onRetry = (item: InboxItem, approvalId: string) => act(item, () => awayApi.retryApproval(approvalId));- const onResolve = (item: InboxItem, decision: ApprovalDecision, withoutBackup?: boolean) =>+ const onResolve = (item: InboxItem, decision: ApprovalDecision, withoutBackup?: boolean, reason?: string) =>act(item,- () => resolveFromList(item.id, onApprovalResolved, () => awayApi.resolve(item.id, decision, withoutBackup)),+ () => resolveFromList(item.id, onApprovalResolved, () => awayApi.resolve(item.id, decision, withoutBackup, reason)),decision === 'deny',);diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsxindex 716c46d0..6d30516f 100644--- a/frontend/src/components/ModernApprovalCard.tsx+++ b/frontend/src/components/ModernApprovalCard.tsx@@ -1,5 +1,5 @@-import React, { useId, useState } from 'react';-import { ShieldAlert, Check, CheckCheck, X, FileText, Clock, CreditCard, GraduationCap, ChevronDown, Lock } from 'lucide-react';+import React, { useId, useRef, useState } from 'react';+import { ShieldAlert, Check, CheckCheck, X, MessageSquare, FileText, Clock, CreditCard, GraduationCap, ChevronDown, Lock } from 'lucide-react';import { playSfx } from '../audio/chiptune';import { formatArgs, parseMcpToolName } from '../mcp';import { tierReason } from '../flightSchool';@@ -8,6 +8,7 @@ import { localClock } from '../clock';import { isPhoneLayout } from '../layout';import { parseProdFloor, type BackupResult, type FloorBackup, type FloorResolveOpts } from '../dev/types';import { ProdFloorCard } from './dev/ProdFloorCard';+import { DENY_REASON_MAX } from '../away';export interface PendingApproval {id: string;@@ -263,6 +264,76 @@ const ApprovalDetails: React.FC<{ phone?: boolean; children: React.ReactNode }>);};+/** The card's secondary button (Deny, Always allow, Deny and tell). */+const SECONDARY =+ 'inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[36px] px-3 rounded-lg border border-[#3f3868] bg-[#231d4b] text-sm font-medium text-[#ecebfa] hover:bg-[#2c2552] transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#b8adff] disabled:opacity-50 disabled:cursor-not-allowed';++/**+ * 29p "Say why": a quiet button in the action row that opens a one-line field under it, with "Deny and tell+ * <bot>". Its own component so the card itself keeps no state. Fragment children of the action row: the form+ * takes a whole line of its own (basis-full) on a wide screen and comes last on a phone.+ */+const SayWhy: React.FC<{ botName: string | null; disabled: boolean; onDeny: (reason: string) => void }> = ({ botName, disabled, onDeny }) => {+ // null while closed, else the reason typed so far.+ const [why, setWhy] = useState<string | null>(null);+ const id = useId();+ const ref = useRef<HTMLButtonElement>(null);+ const tellWho = botName ?? 'the bot';+ return (+ <>+ <button+ ref={ref}+ type="button"+ disabled={disabled}+ aria-expanded={why !== null}+ aria-controls={id}+ onClick={() => setWhy((w) => (w === null ? '' : null))}+ data-approval-say-why=""+ className="self-start sm:self-auto sm:mr-auto -ml-2 sm:ml-0 inline-flex items-center gap-1.5 min-h-[44px] sm:min-h-[32px] px-2 rounded-lg text-sm text-[#a39dcc] hover:text-zinc-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#b8adff] disabled:opacity-50 disabled:cursor-not-allowed"+ >+ <MessageSquare size={14} aria-hidden="true" />+ <span>Say why</span>+ </button>+ {why !== null && (+ <form+ id={id}+ data-approval-why=""+ className="sm:basis-full flex flex-col gap-2 sm:flex-row sm:items-center"+ onSubmit={(e) => {+ e.preventDefault();+ onDeny(why);+ }}+ >+ <input+ type="text"+ autoFocus+ value={why}+ maxLength={DENY_REASON_MAX}+ disabled={disabled}+ onChange={(e) => setWhy(e.target.value.slice(0, DENY_REASON_MAX))}+ onKeyDown={(e) => {+ if (e.key !== 'Escape') return;+ e.preventDefault();+ e.stopPropagation();+ setWhy(null);+ ref.current?.focus();+ }}+ aria-label={`Tell ${tellWho} why you’re denying this`}+ placeholder="What should it do instead?"+ enterKeyHint="send"+ autoComplete="off"+ className="min-w-0 w-full sm:flex-1 min-h-[44px] sm:min-h-[36px] px-3 rounded-lg border border-[#3f3868] bg-zinc-950/70 text-base sm:text-sm text-[#ecebfa] placeholder:text-[#a39dcc] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#b8adff] disabled:opacity-50"+ />+ <button type="submit" disabled={disabled} data-approval-deny-why="" className={`${SECONDARY} w-full sm:w-auto sm:max-w-[50%] min-w-0`}>+ <X size={14} aria-hidden="true" className="shrink-0" />+ <span className="min-w-0 break-words [overflow-wrap:anywhere] text-left">Deny and tell {tellWho}</span>+ </button>+ </form>+ )}+ </>+ );+};+const PRE = 'font-mono text-xs leading-[18px] whitespace-pre-wrap break-words [overflow-wrap:anywhere] max-h-[240px] overflow-y-auto rounded-md border border-zinc-800 bg-zinc-950/70 p-2';export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({@@ -303,6 +374,13 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({playSfx('click');onResolve(approval.id, decision);};+ // 29p: Deny with the person's words, so the bot hears why at once. An empty field is a plain Deny.+ const denyWithReason = (text: string) => {+ if (disabled) return;+ playSfx('click');+ const reason = text.trim();+ onResolve(approval.id, 'deny', reason ? { reason } : undefined);+ };const mcp = mcpView(approval);const shell = localShellView(approval);const builtin = shell || mcp ? null : builtinView(approval);@@ -322,6 +400,8 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({// 26f: a lock, door, garage door, gate or alarm call always asks; its own field, not `always_ask`.const homeAlwaysAsk = approval.details?.home_always_ask === true;const offerAlways = !shell && !waiting && !payment && !alwaysAsk && !homeAlwaysAsk;+ // 29p: a `waiting` card's turn has stopped, so nobody would hear the reason; plain Deny only there.+ const offerWhy = !waiting;const bot = botName ? <strong className="font-semibold text-zinc-50">{botName}</strong> : 'A bot';// "<Bot> wants to open a pull request on <Server>", the server in bold.@@ -390,8 +470,6 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({</>);- const secondary =- 'inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[36px] px-3 rounded-lg border border-[#3f3868] bg-[#231d4b] text-sm font-medium text-[#ecebfa] hover:bg-[#2c2552] transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#b8adff] disabled:opacity-50 disabled:cursor-not-allowed';return (<div@@ -498,7 +576,7 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({screen they sit in one row, right-aligned, with Allow last. Local shell approvals are neverremembered, a late answer only lets that one call run, and a payment or a turn kwantstarted on its own always asks again, so none of them gets an "always". */}- <div data-approval-actions className="mt-3 flex flex-col gap-2 sm:flex-row-reverse sm:items-center sm:justify-start">+ <div data-approval-actions className="mt-3 flex flex-col gap-2 sm:flex-row-reverse sm:flex-wrap sm:items-center sm:justify-start"><buttontype="button"disabled={disabled}@@ -510,7 +588,7 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({<span>{waiting ? 'Allow and continue' : 'Allow once'}</span></button><div className={`grid gap-2 sm:flex ${offerAlways ? 'grid-cols-2' : 'grid-cols-1'}`}>- <button type="button" disabled={disabled} onClick={() => handleDecision('deny')} className={secondary}>+ <button type="button" disabled={disabled} onClick={() => handleDecision('deny')} className={SECONDARY}><X size={14} aria-hidden="true" /><span>Deny</span></button>@@ -520,13 +598,15 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({disabled={disabled}onClick={() => handleDecision('always_allow')}title={perSession ? 'Allow this tool for this bot in this conversation' : mcp ? 'Allow this tool for this bot in this conversation, also after kwant restarts' : undefined}- className={secondary}+ className={SECONDARY}><CheckCheck size={14} aria-hidden="true" /><span>{perSession ? 'Always this session' : 'Always allow'}</span></button>)}</div>+ {/* 29p: quiet, next to Deny (left of it on a wide screen, under the buttons on a phone). Deny itself stays one tap. */}+ {offerWhy && <SayWhy botName={botName} disabled={disabled} onDeny={denyWithReason} />}</div></div>);diff --git a/frontend/src/dev/types.ts b/frontend/src/dev/types.tsindex 5803b6d8..d3d29af7 100644--- a/frontend/src/dev/types.ts+++ b/frontend/src/dev/types.ts@@ -223,6 +223,8 @@ export interface ProdFloor {/** How the card answers: `without_backup` only from the person's own confirm on a "guess" deploy (22f). */export interface FloorResolveOpts {withoutBackup?: boolean;+ /** 29p: Deny only, from the card's "Say why" field: what the person told the bot (sent trimmed, at most 500 chars). */+ reason?: string;}/** `POST /api/spaces/:id/dev/backup`. */diff --git a/frontend/tests/botCapabilities.test.mjs b/frontend/tests/botCapabilities.test.mjsindex 0a0c7279..ac00ebf4 100644--- a/frontend/tests/botCapabilities.test.mjs+++ b/frontend/tests/botCapabilities.test.mjs@@ -40,7 +40,7 @@ test('a Bash approval shows who, the command and the folder, with the three choiassert.match(t, /Run the strategy tests/);assert.match(html, /<pre[^>]*>go test \.\/internal\/strategy\/<\/pre>/);assert.match(t, /In folder: \/Users\/alex\/trader/);- assert.deepEqual(buttons(html), ['Hide details', 'Allow once', 'Deny', 'Always this session']);+ assert.deepEqual(buttons(html), ['Hide details', 'Allow once', 'Deny', 'Always this session', 'Say why']);assert.doesNotMatch(html, /"source"|claude_builtin|kwant_name/);});diff --git a/frontend/tests/denyWithReasonCard.test.mjs b/frontend/tests/denyWithReasonCard.test.mjsnew file mode 100644index 00000000..32b1a816--- /dev/null+++ b/frontend/tests/denyWithReasonCard.test.mjs@@ -0,0 +1,203 @@+// 29p deny-with-reason-card (Iris): "Say why" on the approval card. Deny stays one tap; a Deny with words+// carries them as `reason` in the resolve body, from the chat card and from the Inbox/Away card alike.+import assert from 'node:assert/strict';+import test, { afterEach } from 'node:test';+import { readFileSync } from 'node:fs';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });+g.IS_REACT_ACT_ENVIRONMENT = false;++const m = await loadBundled(`+ export * as away from './src/away';+ export * as fx from './src/dev/fixtures';+ export { ModernApprovalCard } from './src/components/ModernApprovalCard';+ export { AwayView } from './src/components/AwayView';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+ export { createRoot } from 'react-dom/client';+ export { createElement } from 'react';+`);+const h = m.createElement;++const mounted = new Set();+afterEach(() => {+ for (const u of mounted) u();+ document.body.replaceChildren();+});+const settle = async () => {+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));+};+const mount = async (C, props) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = m.createRoot(host);+ root.render(h(C, props));+ await settle();+ const u = () => {+ if (!mounted.delete(u)) return;+ root.unmount();+ host.remove();+ };+ mounted.add(u);+ return host;+};+const click = async (el) => {+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));+ await settle();+};+const key = async (el, k) => {+ el.dispatchEvent(new window.KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true }));+ await settle();+};+// A controlled React input: set the DOM value past React's tracker, then fire `input`.+const type = async (input, text) => {+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(input, text);+ input.dispatchEvent(new window.Event('input', { bubbles: true }));+ await settle();+};+const submit = async (form) => {+ form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));+ await settle();+};++// A GitHub MCP call from a named bot, like mobileCards' pr().+const pr = (over = {}) => ({+ id: 'ap1',+ tool_name: 'mcp__github__create_pull_request',+ details: { source: 'mcp', server: 'github', tool: 'create_pull_request', kwant_name: 'TechLead', arguments: { title: 'Spring sale', repo: 'acme/site' } },+ ...over,+});+const sayWhy = (host) => host.querySelector('[data-approval-say-why]');+const denyBtn = (host) => [...host.querySelectorAll('[data-approval-actions] button')].find((b) => b.textContent.trim() === 'Deny');++test('29p: resolveBody sends reason only for a deny with text; every other body is unchanged', () => {+ const b = m.away.resolveBody;+ assert.deepEqual(b('deny'), { decision: 'deny' });+ assert.deepEqual(b('deny', {}), { decision: 'deny' });+ assert.deepEqual(b('deny', { reason: ' ' }), { decision: 'deny' }, 'blank is a plain Deny');+ assert.deepEqual(b('deny', { reason: ' use the staging repo ' }), { decision: 'deny', reason: 'use the staging repo' });+ assert.deepEqual(b('allow_once', { reason: 'x' }), { decision: 'allow_once' }, 'never on Allow');+ assert.deepEqual(b('always_allow', { reason: 'x' }), { decision: 'always_allow' });+ assert.deepEqual(b('allow_once', { withoutBackup: true }), { decision: 'allow_once', without_backup: true });+ assert.deepEqual(b('deny', { withoutBackup: true }), { decision: 'deny' });+ assert.equal(b('deny', { reason: 'y'.repeat(501) }).reason.length, 500, 'cut to 500');+ assert.equal(m.away.DENY_REASON_MAX, 500);+});++test('29p: the Inbox/Away request carries the reason, and only on a deny', async () => {+ const realFetch = globalThis.fetch;+ const sent = [];+ globalThis.fetch = async (url, init) => {+ sent.push([url, JSON.parse(init.body)]);+ return new Response('{}', { status: 200 });+ };+ try {+ await m.away.awayApi.resolve('a1', 'deny', false, 'try the docs folder');+ await m.away.awayApi.resolve('a2', 'deny');+ await m.away.awayApi.resolve('a3', 'allow_once', true);+ await m.away.awayApi.resolve('a4', 'allow_once');+ } finally {+ globalThis.fetch = realFetch;+ }+ assert.deepEqual(sent, [+ ['/api/approvals/a1/resolve', { decision: 'deny', reason: 'try the docs folder' }],+ ['/api/approvals/a2/resolve', { decision: 'deny' }],+ ['/api/approvals/a3/resolve', { decision: 'allow_once', without_backup: true }],+ ['/api/approvals/a4/resolve', { decision: 'allow_once' }],+ ]);+});++test('29p: the chat path builds its body with resolveBody (App.tsx handleResolveApproval)', () => {+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');+ const fn = app.slice(app.indexOf('const handleResolveApproval'), app.indexOf('const handleResolveApproval') + 1200);+ assert.match(fn, /body: JSON\.stringify\(resolveBody\(decision, opts\)\)/);+});++test('29p: Deny stays one tap with no reason; Say why is closed at first', async () => {+ const calls = [];+ const host = await mount(m.ModernApprovalCard, { approval: pr(), onResolve: (...a) => calls.push(a) });+ assert.ok(sayWhy(host), 'Say why is offered');+ assert.equal(sayWhy(host).getAttribute('aria-expanded'), 'false');+ assert.equal(host.querySelector('[data-approval-why]'), null, 'the field is closed');+ await click(denyBtn(host));+ assert.deepEqual(calls, [['ap1', 'deny']], 'plain Deny: no opts, no reason');+});++test('29p: Say why opens a focused, labelled field; its button denies and tells the bot', async () => {+ const calls = [];+ const host = await mount(m.ModernApprovalCard, { approval: pr(), onResolve: (...a) => calls.push(a) });+ await click(sayWhy(host));+ assert.equal(sayWhy(host).getAttribute('aria-expanded'), 'true');+ const form = host.querySelector('[data-approval-why]');+ assert.equal(sayWhy(host).getAttribute('aria-controls'), form.id);+ const input = form.querySelector('input');+ assert.equal(document.activeElement, input, 'opening it focuses the field');+ assert.equal(input.getAttribute('aria-label'), 'Tell TechLead why you’re denying this');+ assert.equal(input.getAttribute('placeholder'), 'What should it do instead?');+ assert.equal(input.getAttribute('maxlength'), '500');+ assert.match(form.querySelector('[data-approval-deny-why]').textContent, /^Deny and tell TechLead$/);+ await type(input, ' Open it on the staging repo instead ');+ await submit(form); // Enter in a one-field form submits it+ assert.deepEqual(calls, [['ap1', 'deny', { reason: 'Open it on the staging repo instead' }]]);+});++test('29p: an empty field sends a plain deny; 501 chars are cut to 500', async () => {+ const calls = [];+ const host = await mount(m.ModernApprovalCard, { approval: pr(), onResolve: (...a) => calls.push(a) });+ await click(sayWhy(host));+ await click(host.querySelector('[data-approval-deny-why]'));+ assert.deepEqual(calls.pop(), ['ap1', 'deny', undefined]);+ const input = host.querySelector('[data-approval-why] input');+ await type(input, 'z'.repeat(501));+ assert.equal(input.value.length, 500, 'the field holds at most 500');+ await click(host.querySelector('[data-approval-deny-why]'));+ assert.equal(calls.pop()[2].reason.length, 500);+});++test('29p: Escape closes the field and gives focus back to Say why', async () => {+ const host = await mount(m.ModernApprovalCard, { approval: pr(), onResolve() {} });+ await click(sayWhy(host));+ await key(host.querySelector('[data-approval-why] input'), 'Escape');+ assert.equal(host.querySelector('[data-approval-why]'), null);+ assert.equal(document.activeElement, sayWhy(host));+ assert.equal(sayWhy(host).getAttribute('aria-expanded'), 'false');+});++test('29p: no bot name says "the bot"', async () => {+ const host = await mount(m.ModernApprovalCard, { approval: { id: 'n1', tool_name: 'write_file', details: { path: '/tmp/a.txt' } }, onResolve() {} });+ await click(sayWhy(host));+ assert.match(host.querySelector('[data-approval-deny-why]').textContent, /^Deny and tell the bot$/);+ assert.equal(host.querySelector('[data-approval-why] input').getAttribute('aria-label'), 'Tell the bot why you’re denying this');+});++test('29p: not on a waiting card, not on the production-floor card', () => {+ const waiting = m.renderToStaticMarkup(h(m.ModernApprovalCard, { approval: pr({ waiting: true }), onResolve() {} }));+ assert.match(waiting, />Deny</);+ assert.doesNotMatch(waiting, /Say why|data-approval-say-why/);+ const floor = m.renderToStaticMarkup(h(m.ModernApprovalCard, { approval: m.fx.FLOOR_GUESS_OLD, onResolve() {}, onLoadBackup: async () => null }));+ assert.doesNotMatch(floor, /Say why|data-approval-say-why/);+});++test('29p: the Inbox/Away card passes the reason through to its resolve', async () => {+ const item = {+ kind: 'approval', id: 'ap1', kwant_id: 'k1', kwant_name: 'TechLead', title: 'Use create_pull_request (github)',+ summary: 'acme/site', status: 'pending', timestamp: '2026-11-05T08:00:00Z',+ link: { thread_id: 't1', channel_id: null, direct_kwant_id: null },+ tool_name: 'mcp__github__create_pull_request', details: pr().details,+ };+ const data = { since: '2026-11-05T07:00:00Z', last_seen: null, now: '2026-11-05T08:05:00Z', stuck_after_minutes: 30, waiting: [item], finished: [], failed: [], unseen: { waiting: 1, finished: 0, failed: 0, total: 1 } };+ const calls = [];+ const noop = () => {};+ const host = await mount(m.AwayView, { data, loading: false, error: null, now: Date.parse('2026-11-05T08:05:00Z'), onRefresh: noop, onOpen: noop, onAnswer: noop, onResolve: (it, d, wb, reason) => calls.push([it.id, d, wb, reason]) });+ await click(sayWhy(host));+ await type(host.querySelector('[data-approval-why] input'), 'Ask me after lunch');+ await submit(host.querySelector('[data-approval-why]'));+ assert.deepEqual(calls, [['ap1', 'deny', undefined, 'Ask me after lunch']]);+});diff --git a/frontend/tests/mobileCards.test.mjs b/frontend/tests/mobileCards.test.mjsindex b6aa4058..ead6337a 100644--- a/frontend/tests/mobileCards.test.mjs+++ b/frontend/tests/mobileCards.test.mjs@@ -92,7 +92,7 @@ test('approval card on a phone: header, one sentence, two key facts, details cloassert.doesNotMatch(html, /data-approval-details=""/);assert.doesNotMatch(html, /"head"/);const b = buttons(html);- assert.deepEqual(b.map((x) => x.label), ['Show details', 'Allow once', 'Deny', 'Always allow']);+ assert.deepEqual(b.map((x) => x.label), ['Show details', 'Allow once', 'Deny', 'Always allow', 'Say why']); // 29p: Say why after Deny's rowassert.match(b[0].attrs, /aria-expanded="false"/);assert.match(b[0].attrs, /min-h-\[44px\]/);assert.match(b[1].attrs, /w-full/);@@ -119,7 +119,7 @@ test('approval card on desktop: details open, the JSON wraps between words, nevetest('a payment card offers no Always allow on a phone either: its second row is just Deny', () => {const payment = pr({ details: { ...pr().details, payment_reason: 'stripe create payment is a money action' } });const html = m.card({ approval: payment, onResolve: noop, phone: true });- assert.deepEqual(buttons(html).map((x) => x.label), ['Show details', 'Allow once', 'Deny']);+ assert.deepEqual(buttons(html).map((x) => x.label), ['Show details', 'Allow once', 'Deny', 'Say why']);assert.match(html, /<div class="grid gap-2 sm:flex grid-cols-1">/);assert.doesNotMatch(html, /Always/);});