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.

Proactive bots: decided chips with Change, "Team is deciding…", "While you were away", settings

Pixel (kwant bot)232572e66a1f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dafa9cc7..e24c06f3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
most once until you write again, and is capped per space per day. App settings has a switch for it.
- **Questions say why only you can answer.** A bot's question card now says why it needs you and what
it checked first; a question without a reason goes back to the bot to decide itself.
+- **See and change what bots decided.** A bot's choice shows as a chip, for example "Decided: B: Wax
+ seal", with the reason and who it asked first; **Change** lists the other options and the bot redoes
+ what depended on it. While the team is deciding, the chat shows "Team is deciding…" instead of a
+ half-written reply, and work done while you were away arrives as a quiet, folded message. App
+ settings has a **Bots on their own** section with both switches and a daily limit.
## [Mac 0.1.2] - 2026-10-26
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 4f403b7d..01677d34 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,4 +1,5 @@
import React, { Suspense, lazy, useState, useEffect, useRef, useCallback, useMemo } from 'react';
+import { DecidingMap, applyDecideEvent, decisionsApi, hydrateDeciding } from './decideFirst';
import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar';
import { SpaceSettings, SpaceSettingsTab } from './components/SpaceSettings';
import { SpaceTile } from './components/Spaces';
@@ -204,6 +205,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// Chat the last send or discussion started in; untagged events (team discussions) go here.
const streamingContextIdRef = useRef<string | null>(null);
const [turns, setTurns] = useState<TurnMap>({});
+ // Chats where a held reply is being decided ("Team is deciding…"), from decide_updated.
+ const [deciding, setDeciding] = useState<DecidingMap>({});
const turnsRef = useRef(turns);
turnsRef.current = turns;
const [threadsByKwant, setThreadsByKwant] = useState<Record<string, Thread[] | undefined>>({});
@@ -513,6 +516,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
try {
const { turns: list } = await threadsApi.turns();
const map = hydrateTurns(list);
+ setDeciding(hydrateDeciding(list));
for (const t of Object.values(map)) if (t.thread_id) knownThreadsRef.current.add(t.thread_id);
turnsRef.current = map;
setTurns(map);
@@ -787,7 +791,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (ctx === openCtxRef.current) refreshContext(ctx);
break;
}
- if (list.some((x) => x.id === m.id)) break;
+ // The same message again is an update (e.g. a decision the person changed): replace it.
+ if (list.some((x) => x.id === m.id)) {
+ const replaced = list.map((x) => (x.id === m.id ? m : x));
+ messagesCacheRef.current[ctx] = replaced;
+ if (ctx === openCtxRef.current) setMessages(replaced);
+ break;
+ }
// The person's own message replaces its optimistic copy.
let base = list;
if (m.sender_role === 'user') {
@@ -799,6 +809,24 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (ctx === openCtxRef.current) setMessages(updated);
break;
}
+ case 'decide_updated':
+ case 'DecideUpdated': {
+ const d = event.data ?? {};
+ const ctx: string | null = d.context_id ?? d.thread_id ?? d.kwant_id ?? null;
+ setDeciding((prev) => applyDecideEvent(prev, event));
+ if (!ctx) break;
+ // The held draft is never saved: drop it, the line stands in for it.
+ if (d.state === 'deciding') {
+ if (streamsRef.current[ctx]) streamsRef.current[ctx] = { text: '', thinking: '' };
+ if (ctx === openCtxRef.current) {
+ setStreamingText('');
+ setStreamingThinking('');
+ }
+ } else {
+ refreshContext(ctx);
+ }
+ break;
+ }
case 'profile_switched':
case 'ProfileSwitched': {
const kwantName = kwantsRef.current.find((k) => k.id === event.data?.kwant_id)?.name;
@@ -1261,6 +1289,29 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
};
+ /** Change on a decision chip: record the new pick, show it, then ask the bot to redo it in this chat. */
+ const handleChangeDecision = async (msg: ChatMessage, index: number, picked: string): Promise<string | void> => {
+ haptic('tap');
+ let prompt: string;
+ try {
+ const res = await decisionsApi.change<ChatMessage>(msg.id, index, picked);
+ prompt = res.prompt;
+ const ctx = messageContextId(res.message ?? msg);
+ if (ctx && res.message?.id) {
+ const list = messagesCacheRef.current[ctx];
+ if (list) {
+ const replaced = list.map((x) => (x.id === res.message.id ? res.message : x));
+ messagesCacheRef.current[ctx] = replaced;
+ if (ctx === openCtxRef.current) setMessages(replaced);
+ }
+ }
+ } catch (err) {
+ haptic('warning');
+ return err instanceof Error ? err.message : 'Couldn’t change it.';
+ }
+ if (prompt && !(await handleSendMessage(prompt))) return 'Your choice is saved, but the bot wasn’t told. Ask it in this chat to redo it with your choice.';
+ };
+
const handleResolveApproval = async (
ticketId: string,
decision: 'allow_once' | 'always_allow' | 'deny'
@@ -2362,6 +2413,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}, [loaded, selectedId, isChannel]);
const isCurrentContextStreaming = openCtx in live;
+ const decidingHere = deciding[openCtx] ?? null;
const openTurns = turnsIn(turns, openCtx);
// Turns paused on a question wait for the person; they don't make the bot "busy".
const browserTurns = turnsAwaitingStep(humanSteps);
@@ -2824,6 +2876,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
liveActivity={isCurrentContextStreaming ? activityHere : null}
renderHumanStep={renderHumanStep}
contextKey={openCtx}
+ deciding={decidingHere ? { botName: kwantName(decidingHere.kwantId) ?? chatTitle, consulted: decidingHere.consulted } : null}
+ onChangeDecision={handleChangeDecision}
/>
);
const mainPane = needsSetup ? setupChecklist : showParallel ? parallel : showConnections ? connectionsPage : showLoose ? loose : showAway ? away : !loaded ? (
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index a3ac30bd..50a09c88 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -40,6 +40,8 @@ import { routeReasonText } from '../routeReason';
import { BudgetPausedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';
import { chainBudgetApi, parseBudgetPaused } from '../chainBudget';
import { isSystemNotice, parseInterruption, retryTargets } from '../interruptions';
+import { consultedNames, parseDecisions, parseWorkAhead } from '../decideFirst';
+import { DecidingLine, DecisionChips, WorkAheadBody } from './Proactive';
/** A swipeable chip row whose right fade edge (phones only, see .kw-scroll-row) goes away once
* it is scrolled to the end, or when everything already fits. */
@@ -220,6 +222,10 @@ export interface ChatViewProps {
renderHumanStep?: (msg: ChatMessage, meta: HumanStepMeta, flash: boolean) => React.ReactNode;
/** Changes when another chat opens, so the view jumps to its bottom. */
contextKey?: string;
+ /** Set while a held reply in this chat is being decided ("Team is deciding…"). */
+ deciding?: { botName: string; consulted: string[] } | null;
+ /** Change on a decision chip; resolves to an error message on failure. */
+ onChangeDecision?: (msg: ChatMessage, index: number, picked: string) => Promise<string | void>;
}
export const renderFormattedText = (text: string): React.ReactNode => {
@@ -417,6 +423,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
liveActivity,
renderHumanStep,
contextKey,
+ deciding,
+ onChangeDecision,
}) => {
const narrow = useNarrow();
const [internalIsVmPaneOpen, setInternalIsVmPaneOpen] = useState(false);
@@ -817,6 +825,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
const tokens = isUser ? null : replyTokens(msg.tokens_used, msg.meta);
// Any auto-routed channel, not only #general: the server attaches `routing` wherever it picked the bot.
const routed = isUser ? null : parseRoutingMeta(msg.meta);
+ const decisions = isUser ? [] : parseDecisions(msg.meta);
+ const workAhead = isUser ? null : parseWorkAhead(msg.meta);
const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);
return (
@@ -900,11 +910,16 @@ export const ChatView: React.FC<ChatViewProps> = ({
className={`px-3.5 py-3 sm:p-5 rounded-2xl text-sm leading-relaxed shadow-sm w-full ${
isUser
? 'bg-zinc-800 text-zinc-100 rounded-tr-sm border border-zinc-700/60 max-w-2xl'
- : 'bg-zinc-900/60 text-zinc-200 rounded-tl-sm border border-zinc-800/80'
+ : workAhead
+ ? 'bg-indigo-950/15 text-zinc-200 rounded-tl-sm border border-dashed border-indigo-400/25'
+ : 'bg-zinc-900/60 text-zinc-200 rounded-tl-sm border border-zinc-800/80'
}`}
+ data-work-ahead={workAhead ? '' : undefined}
>
{isUser ? (
<div className="whitespace-pre-wrap break-words">{renderFormattedText(msg.text)}</div>
+ ) : workAhead ? (
+ <WorkAheadBody messageId={msg.id} text={msg.text} />
) : (
<MarkdownRenderer content={msg.text} />
)}
@@ -912,6 +927,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
{files.length > 0 && <FileTiles files={files} align={isUser ? 'end' : 'start'} />}
+ {decisions.length > 0 && (
+ <DecisionChips
+ messageId={msg.id}
+ decisions={decisions}
+ consulted={consultedNames(msg.meta)}
+ onChange={onChangeDecision ? (index, picked) => onChangeDecision(msg, index, picked) : undefined}
+ />
+ )}
+
{!isUser && msg.tool_calls && !savedActivity && <ToolCallsList raw={msg.tool_calls} />}
{/* Copy action */}
@@ -1172,8 +1196,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
<LayaRoutingCard routing={routingState} spaceName={spaceName} />
)}
+ {/* A held reply is being decided: the line stands in for the streamed draft and the consults */}
+ {deciding && <DecidingLine botName={deciding.botName} consulted={deciding.consulted} />}
+
{/* Live Streaming Assistant Message (or its place in the queue, in the same frame) */}
- {isStreaming && routingState?.phase !== 'deciding' && (
+ {isStreaming && !deciding && routingState?.phase !== 'deciding' && (
<div className="flex items-start gap-3.5 w-full max-w-5xl">
<ModernAvatar
role={
diff --git a/frontend/src/components/Proactive.tsx b/frontend/src/components/Proactive.tsx
new file mode 100644
index 00000000..51e23de6
--- /dev/null
+++ b/frontend/src/components/Proactive.tsx
@@ -0,0 +1,169 @@
+import React, { useRef, useState } from 'react';
+import { CheckCircle2, ChevronDown, ChevronRight, Loader2, Moon, Users } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import { MarkdownRenderer } from './MarkdownRenderer';
+import { Decision, changeOptions, consultedLine, decidingDetail, decisionLabel, workAheadSummary } from '../decideFirst';
+
+export interface DecisionChipsProps {
+ messageId: string;
+ decisions: Decision[];
+ /** Teammates asked before deciding (decide-first gate). */
+ consulted?: string[];
+ /** Records the new pick and asks the bot to redo it; resolves to an error message on failure. */
+ onChange?: (index: number, picked: string) => Promise<string | void>;
+}
+
+/** Under a reply: what the team decided on its own, each with Change. */
+export const DecisionChips: React.FC<DecisionChipsProps> = ({ messageId, decisions, consulted = [], onChange }) => {
+ const [open, setOpen] = useState<number | null>(null);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ // Set synchronously, so a double tap can't send two changes.
+ const lock = useRef(false);
+ if (!decisions.length) return null;
+
+ const pick = async (d: Decision, option: string) => {
+ if (!onChange || lock.current) return;
+ lock.current = true;
+ setBusy(option);
+ setError(null);
+ const err = await onChange(d.index, option);
+ lock.current = false;
+ setBusy(null);
+ if (err) setError(err);
+ else setOpen(null);
+ };
+
+ return (
+ <div role="group" aria-label="Decided by the team" data-decisions className="mt-2 w-full max-w-2xl space-y-2">
+ {consulted.length > 0 && (
+ <p className="flex items-center gap-1.5 text-[11px] text-zinc-500">
+ <Users size={12} aria-hidden="true" />
+ {consultedLine(consulted)}
+ </p>
+ )}
+ {decisions.map((d) => {
+ const others = changeOptions(d);
+ const changing = open === d.index;
+ const panelId = `dec-${messageId}-${d.index}`;
+ const changed = d.status === 'changed';
+ return (
+ <div key={d.index} className="rounded-xl border border-zinc-800 bg-zinc-900/40 px-3 py-2">
+ <div className="flex items-start gap-2 min-w-0">
+ <div className="flex flex-1 flex-wrap items-center gap-x-2 gap-y-1.5 min-w-0">
+ {d.question && <span className="text-[11px] text-zinc-400 break-words min-w-0">{d.question}</span>}
+ <span
+ className={`inline-flex items-center gap-1 max-w-full px-2 py-0.5 rounded-full border text-[11px] font-medium ${
+ changed ? 'border-sky-500/40 bg-sky-500/10 text-sky-200' : 'border-emerald-500/35 bg-emerald-500/10 text-emerald-200'
+ }`}
+ >
+ <CheckCircle2 size={12} className="shrink-0" aria-hidden="true" />
+ <span className="break-words min-w-0">{decisionLabel(d)}</span>
+ </span>
+ </div>
+ {others.length > 0 && onChange && (
+ <button
+ type="button"
+ aria-expanded={changing}
+ aria-controls={panelId}
+ onClick={() => {
+ setError(null);
+ setOpen(changing ? null : d.index);
+ }}
+ className="shrink-0 -my-1 px-2.5 py-1.5 min-h-8 rounded-lg text-[11px] font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 border border-zinc-700/60 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ {changing ? 'Keep it' : 'Change'}
+ </button>
+ )}
+ </div>
+ {d.why && <p className="mt-1 text-[11px] text-zinc-500 break-words">Why: {d.why}</p>}
+ {changing && (
+ <div id={panelId} className="mt-2 pt-2 border-t border-zinc-800 space-y-1.5">
+ <p className="text-[11px] text-zinc-400">Pick another one. The bot redoes what depended on it.</p>
+ <div role="group" aria-label={`Other choices for: ${d.question || d.picked}`} className="flex flex-col sm:flex-row sm:flex-wrap gap-1.5">
+ {others.map((o) => (
+ <button
+ key={o}
+ type="button"
+ disabled={busy !== null}
+ onClick={() => pick(d, o)}
+ className="inline-flex items-center justify-center gap-1.5 px-3 py-2 min-h-9 rounded-lg text-xs text-left text-zinc-100 bg-zinc-800 hover:bg-zinc-700 border border-zinc-700/60 disabled:opacity-50 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ {busy === o && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ Use {o}
+ </button>
+ ))}
+ </div>
+ {error && (
+ <p role="alert" className="text-[11px] text-rose-300">
+ {error}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+};
+
+/** In place of the streaming reply while a held reply is being decided. */
+export const DecidingLine: React.FC<{
+ botName: string;
+ consulted: string[];
+}> = ({ botName, consulted }) => (
+ <div className="flex items-start gap-3.5 w-full max-w-5xl" data-deciding>
+ <ModernAvatar role={botName} name={botName} size={34} />
+ <div className="flex flex-col items-start min-w-0 flex-1 max-w-4xl">
+ <div className="flex items-center gap-2 mb-1.5 text-[11px] text-zinc-400 font-medium">
+ <span className="text-zinc-200">{botName}</span>
+ <span className="inline-flex items-center gap-1 text-violet-300 text-[10px]">
+ <span className="w-1.5 h-1.5 rounded-full bg-violet-300 animate-ping motion-reduce:animate-none" aria-hidden="true" />
+ Deciding
+ </span>
+ </div>
+ <div
+ role="status"
+ aria-live="polite"
+ className="px-4 py-3 rounded-2xl rounded-tl-sm bg-violet-950/20 border border-violet-500/20 text-sm text-zinc-200 shadow-sm w-full"
+ >
+ <p className="flex items-center gap-2 font-medium text-violet-100">
+ <Users size={15} className="text-violet-300 shrink-0" aria-hidden="true" />
+ Team is deciding…
+ </p>
+ <p className="mt-0.5 text-xs text-zinc-400">{decidingDetail(botName, consulted)}</p>
+ </div>
+ </div>
+ </div>
+);
+
+/** A "While you were away" message: a subtle label and one line, opening to the whole text. */
+export const WorkAheadBody: React.FC<{ messageId: string; text: string }> = ({ messageId, text }) => {
+ const [open, setOpen] = useState(false);
+ const bodyId = `wa-${messageId}`;
+ return (
+ <div className="w-full">
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-controls={bodyId}
+ onClick={() => setOpen((v) => !v)}
+ className="w-full flex items-start gap-2 text-left rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <Moon size={14} className="mt-0.5 shrink-0 text-indigo-300" aria-hidden="true" />
+ <span className="flex-1 min-w-0">
+ <span className="block text-[11px] font-medium uppercase tracking-wide text-indigo-300/90">While you were away</span>
+ {!open && <span className="block text-sm text-zinc-300 break-words">{workAheadSummary(text)}</span>}
+ </span>
+ <span className="shrink-0 inline-flex items-center gap-0.5 text-[11px] text-zinc-500">
+ {open ? 'Less' : 'More'}
+ {open ? <ChevronDown size={13} aria-hidden="true" /> : <ChevronRight size={13} aria-hidden="true" />}
+ </span>
+ </button>
+ <div id={bodyId} hidden={!open} className="mt-2">
+ {open && <MarkdownRenderer content={text} />}
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/QuestionCard.tsx b/frontend/src/components/QuestionCard.tsx
index 92041861..afbb9255 100644
--- a/frontend/src/components/QuestionCard.tsx
+++ b/frontend/src/components/QuestionCard.tsx
@@ -2,6 +2,7 @@ import React, { useRef, useState } from 'react';
import { ArrowUp, Check, CheckCircle2, Clock, HelpCircle, Loader2, MinusCircle } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { ANSWER_MAX, Question, QuestionMeta, answerTextError, questionView } from '../questions';
+import { whyYouText } from '../decideFirst';
export interface QuestionCardProps {
meta: QuestionMeta;
@@ -34,6 +35,7 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ meta, messageId, kwa
const open = view.status === 'open' && sent === null;
const answer = view.answer ?? sent;
const headingId = `q-${messageId}`;
+ const whyYou = whyYouText(view.why_you);
const submit = async (a: { choice: number } | { text: string }) => {
if (!open || busy !== null) return;
@@ -111,6 +113,8 @@ export const QuestionCard: React.FC<QuestionCardProps> = ({ meta, messageId, kwa
<h3 id={headingId} className="text-sm font-semibold text-zinc-100 whitespace-pre-wrap break-words leading-snug">
{view.question}
</h3>
+ {whyYou && <p className="text-[11px] text-zinc-400 break-words">Only you can answer: {whyYou}</p>}
+ {view.checked && <p className="text-[11px] text-zinc-500 break-words">Already tried: {view.checked}</p>}
</div>
<div role="group" aria-label="Choices" className="px-4 pb-2 flex flex-col sm:flex-row sm:flex-wrap gap-2">
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 09f83562..e0986dd3 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef } from 'react';
-import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff } from 'lucide-react';
+import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff, Sparkles } from 'lucide-react';
import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';
import { budgetError, budgetValue } from '../chainBudget';
import { DailyUsagePanel } from './DailyUsage';
@@ -29,6 +29,41 @@ import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';
import { useEngines } from '../useEngines';
import { LayaStatusRow } from './LayaStatus';
import { AppUpdateAbout, useAppUpdate } from './AppUpdateBanner';
+import { ProactiveSettings, WORK_AHEAD_CAP_MAX, WORK_AHEAD_CAP_MIN, parseProactiveSettings } from '../decideFirst';
+
+/** One labelled switch row, like the others in this dialog. */
+const SwitchRow: React.FC<{ id: string; label: string; hint: string; checked: boolean; onToggle: () => void; children?: React.ReactNode }> = ({
+ id,
+ label,
+ hint,
+ checked,
+ onToggle,
+ children,
+}) => (
+ <div className="flex items-start gap-3 bg-zinc-950/60 p-3 rounded-xl border border-zinc-800">
+ <div className="flex-1 min-w-0">
+ <p id={`${id}-label`} className="text-xs font-medium text-zinc-200">{label}</p>
+ <p id={`${id}-hint`} className="text-[11px] text-zinc-500">{hint}</p>
+ {children}
+ </div>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={checked}
+ aria-labelledby={`${id}-label`}
+ aria-describedby={`${id}-hint`}
+ onClick={() => {
+ playSfx('click');
+ onToggle();
+ }}
+ className="group shrink-0 -m-3 p-3 rounded-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <span className={`relative block w-9 h-5 rounded-full transition-colors ${checked ? 'bg-sky-600' : 'bg-zinc-700'}`}>
+ <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform motion-reduce:transition-none ${checked ? 'translate-x-4' : ''}`} />
+ </span>
+ </button>
+ </div>
+);
interface SettingsData {
anthropic_api_key: string;
@@ -55,6 +90,10 @@ interface SettingsData {
location?: string;
/** Fresh tokens per request before hand-offs pause; 0 = off. Missing on older servers. */
chain_token_budget?: number;
+ /** Proactive bots; missing on older servers. */
+ decide_first?: boolean;
+ work_ahead?: boolean;
+ work_ahead_daily_cap?: number;
}
const LIMIT_FIELDS: { key: TurnLimitKey; label: string; hint: string }[] = [
@@ -89,6 +128,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const [saveError, setSaveError] = useState<string | null>(null);
// null until loaded (or from a server without the setting), and then left out of the save
const [agentTools, setAgentTools] = useState<boolean | null>(null);
+ // Deciding and working ahead on their own; null on a server without these settings
+ const [proactive, setProactive] = useState<ProactiveSettings | null>(null);
// null until loaded, and on a server without these settings
const [place, setPlace] = useState<{ timezone: string; location: string } | null>(null);
const [webhookUrl, setWebhookUrl] = useState('');
@@ -151,6 +192,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
);
setChainBudget(typeof data.chain_token_budget === 'number' ? String(data.chain_token_budget) : null);
setAgentTools(typeof data.agent_tools === 'boolean' ? data.agent_tools : null);
+ setProactive(parseProactiveSettings(data));
setPlace(
typeof data.timezone === 'string'
? { timezone: data.timezone || defaultTimeZone(), location: typeof data.location === 'string' ? data.location : '' }
@@ -219,7 +261,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
openai_api_key: openaiKey,
ollama_url: ollamaUrl,
notify_webhook_url: webhookUrl.trim(),
- notify_on: notifyOnToSave(notifyOn, appUpdates),
+ notify_on: notifyOnToSave(notifyOn, appUpdates, !!proactive),
...(limits
? {
max_turns_per_agent: Number(limits.max_turns_per_agent),
@@ -229,6 +271,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
: {}),
...(chainBudget !== null ? { chain_token_budget: budgetValue(chainBudget) } : {}),
...(agentTools !== null ? { agent_tools: agentTools } : {}),
+ ...(proactive ?? {}),
...(place ? { timezone: place.timezone.trim(), location: place.location.trim() } : {}),
}),
});
@@ -589,6 +632,51 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
</div>
)}
+ {proactive && (
+ <fieldset className="space-y-3 pt-2 border-t border-zinc-800" data-testid="proactive-settings">
+ <legend className="flex items-center gap-2 text-xs font-medium text-zinc-300 pt-3">
+ <Sparkles size={14} className="text-violet-300" aria-hidden="true" />
+ <span>Bots on their own</span>
+ </legend>
+ <SwitchRow
+ id="decide-first"
+ label="Bots decide reversible choices themselves"
+ hint="Instead of asking you to pick, they run their own checks, ask a teammate, choose, and show it with a Change button. They still ask you before sending, paying, deleting or signing in."
+ checked={proactive.decide_first}
+ onToggle={() => setProactive((p) => (p ? { ...p, decide_first: !p.decide_first } : p))}
+ />
+ <SwitchRow
+ id="work-ahead"
+ label="Bots work ahead while I’m away"
+ hint="When a chat has been quiet for 2 hours, its lead finishes open checks and gets the next step ready. You get one “While you were away” message per chat a day at most. They never send, pay or contact anyone."
+ checked={proactive.work_ahead}
+ onToggle={() => setProactive((p) => (p ? { ...p, work_ahead: !p.work_ahead } : p))}
+ >
+ <div className="mt-2 flex items-center gap-2">
+ <label htmlFor="work-ahead-cap" className={`text-[11px] ${proactive.work_ahead ? 'text-zinc-300' : 'text-zinc-500'}`}>
+ At most
+ </label>
+ <select
+ id="work-ahead-cap"
+ value={proactive.work_ahead_daily_cap}
+ disabled={!proactive.work_ahead}
+ onChange={(e) => setProactive((p) => (p ? { ...p, work_ahead_daily_cap: Number(e.target.value) } : p))}
+ className="bg-zinc-950 border border-zinc-800 rounded-lg px-2 py-1.5 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none disabled:opacity-50"
+ >
+ {Array.from({ length: WORK_AHEAD_CAP_MAX - WORK_AHEAD_CAP_MIN + 1 }, (_, i) => i + WORK_AHEAD_CAP_MIN).map((n) => (
+ <option key={n} value={n}>
+ {n}
+ </option>
+ ))}
+ </select>
+ <span className={`text-[11px] ${proactive.work_ahead ? 'text-zinc-300' : 'text-zinc-500'}`}>
+ {proactive.work_ahead_daily_cap === 1 ? 'time' : 'times'} a day in each space
+ </span>
+ </div>
+ </SwitchRow>
+ </fieldset>
+ )}
+
<fieldset className="space-y-3 pt-2 border-t border-zinc-800">
<legend className="flex items-center gap-2 text-xs font-medium text-zinc-300 pt-3">
<Bell size={14} className="text-amber-300" />
@@ -670,7 +758,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
<div className="space-y-1.5" role="group" aria-labelledby="notify-kinds-label">
<p id="notify-kinds-label" className="text-xs font-medium text-zinc-400">Tell me when</p>
- {notifyKindsFor(appUpdates).map((k) => (
+ {notifyKindsFor(appUpdates, !!proactive).map((k) => (
<label key={k.id} className="flex items-center gap-2 text-[11px] text-zinc-300">
<input
type="checkbox"
diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.ts
index 25f16012..9f72477d 100644
--- a/frontend/src/continuity.ts
+++ b/frontend/src/continuity.ts
@@ -113,7 +113,8 @@ export type NotifyKind =
| 'skill_proposed'
| 'question_asked'
| 'human_step'
- | 'app_update';
+ | 'app_update'
+ | 'work_ahead';
export const NOTIFY_KINDS: Array<{ id: NotifyKind; label: string }> = [
{ id: 'turn_finished', label: 'A bot finished replying' },
{ id: 'approval_needed', label: 'A bot needs your approval' },
@@ -128,12 +129,19 @@ export const NOTIFY_KINDS: Array<{ id: NotifyKind; label: string }> = [
/** Only the Mac app sends it (and only its server accepts it), so it is listed there alone. */
export const APP_UPDATE_KIND: { id: NotifyKind; label: string } = { id: 'app_update', label: 'App updates' };
-/** The checkboxes under "Tell me when": App updates only in the Mac app. */
-export const notifyKindsFor = (appUpdates: boolean) => (appUpdates ? [...NOTIFY_KINDS, APP_UPDATE_KIND] : NOTIFY_KINDS);
+/** Sent by servers with the proactive-bots settings (`work_ahead` in GET /api/settings). */
+export const WORK_AHEAD_KIND: { id: NotifyKind; label: string } = { id: 'work_ahead', label: 'A bot worked ahead while you were away' };
-/** What to save: never app_update off the Mac app, whose server would refuse the unknown kind. */
-export const notifyOnToSave = (on: NotifyKind[], appUpdates: boolean) =>
- appUpdates ? on : on.filter((k) => k !== APP_UPDATE_KIND.id);
+/** The checkboxes under "Tell me when": App updates only in the Mac app, work ahead only where the server has it. */
+export const notifyKindsFor = (appUpdates: boolean, workAhead = false) => [
+ ...NOTIFY_KINDS,
+ ...(workAhead ? [WORK_AHEAD_KIND] : []),
+ ...(appUpdates ? [APP_UPDATE_KIND] : []),
+];
+
+/** What to save: never a kind the server doesn't know (it would refuse the whole list). */
+export const notifyOnToSave = (on: NotifyKind[], appUpdates: boolean, workAhead = false) =>
+ on.filter((k) => (k !== APP_UPDATE_KIND.id || appUpdates) && (k !== WORK_AHEAD_KIND.id || workAhead));
/** Kinds also shown as an in-app toast while kwnt is visible (the others only matter in the background). */
export const TOAST_KINDS: NotifyKind[] = ['routine_failed', 'delegation_finished', 'delegation_stalled', 'skill_proposed', 'question_asked', 'human_step'];
@@ -485,7 +493,7 @@ export function shouldShowOsNotification(opts: {
hidden: boolean;
kind: string;
}): boolean {
- return opts.enabled && opts.permission === 'granted' && opts.hidden && NOTIFY_KINDS.some((k) => k.id === opts.kind);
+ return opts.enabled && opts.permission === 'granted' && opts.hidden && (NOTIFY_KINDS.some((k) => k.id === opts.kind) || opts.kind === WORK_AHEAD_KIND.id);
}
/** Whether this browser has OS notifications switched on for kwnt (stored per browser). */
diff --git a/frontend/src/decideFirst.ts b/frontend/src/decideFirst.ts
new file mode 100644
index 00000000..ec6f43eb
--- /dev/null
+++ b/frontend/src/decideFirst.ts
@@ -0,0 +1,192 @@
+// Proactive bots (contract: proactive-bots/contract.md). Bots decide reversible choices themselves
+// and record them on the reply (meta.decisions) so the person can Change one; while a held reply
+// is being decided, the chat shows "Team is deciding…" (SSE decide_updated); work done while the
+// person was away arrives as a message with meta kind "work_ahead".
+import { parseMetaObject } from './questions';
+import { request } from './threads';
+
+export interface Decision {
+ index: number;
+ question: string;
+ options: string[];
+ picked: string;
+ why: string;
+ status: 'decided' | 'changed';
+ changed_to: string | null;
+}
+
+const str = (v: unknown): string => (typeof v === 'string' ? v : '');
+
+/** A reply's decisions, in the order the bot made them; [] for anything else. */
+export function parseDecisions(raw: unknown): Decision[] {
+ const m = parseMetaObject(raw);
+ if (!m || !Array.isArray(m.decisions)) return [];
+ const out: Decision[] = [];
+ m.decisions.forEach((d: unknown, i: number) => {
+ if (!d || typeof d !== 'object') return;
+ const r = d as Record<string, unknown>;
+ const options = Array.isArray(r.options) ? r.options.filter((o): o is string => typeof o === 'string' && o.trim() !== '') : [];
+ const picked = str(r.picked);
+ if (!picked) return;
+ const changedTo = typeof r.changed_to === 'string' && r.changed_to ? r.changed_to : null;
+ out.push({
+ index: typeof r.index === 'number' && Number.isInteger(r.index) ? r.index : i,
+ question: str(r.question),
+ options,
+ picked,
+ why: str(r.why),
+ status: r.status === 'changed' && changedTo ? 'changed' : 'decided',
+ changed_to: changedTo,
+ });
+ });
+ return out;
+}
+
+/** What the chip says: the current choice. */
+export const decisionLabel = (d: Decision): string => (d.status === 'changed' ? `You chose: ${d.changed_to}` : `Decided: ${d.picked}`);
+
+/** The options the person can switch to: every other one. Empty means no Change button. */
+export const changeOptions = (d: Decision): string[] => (d.status === 'changed' ? [] : d.options.filter((o) => o !== d.picked));
+
+/** Teammates the bot asked before deciding, when the reply came from the decide-first gate. */
+export function consultedNames(raw: unknown): string[] {
+ const df = parseMetaObject(raw)?.decide_first;
+ if (!df || typeof df !== 'object') return [];
+ const c = (df as Record<string, unknown>).consulted;
+ return Array.isArray(c) ? c.filter((n): n is string => typeof n === 'string' && n.trim() !== '') : [];
+}
+
+/** "Asked Designer and Writer first." */
+export function consultedLine(names: string[]): string {
+ if (!names.length) return '';
+ const list = names.length === 1 ? names[0] : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
+ return `Asked ${list} first.`;
+}
+
+export interface ChangeResult<M> {
+ message: M;
+ prompt: string;
+}
+
+export const decisionsApi = {
+ /** Records the person's new pick; the client then sends `prompt` to the same chat. */
+ change: <M>(messageId: string, index: number, picked: string) =>
+ request<ChangeResult<M>>('POST', `/api/messages/${encodeURIComponent(messageId)}/decisions/${index}/change`, { picked }),
+};
+
+// ---------------------------------------------------------------------------
+// "Team is deciding…"
+
+export interface Deciding {
+ kwantId: string;
+ heldTurnId: string | null;
+ consulted: string[];
+}
+
+/** Chats where a held reply is being decided, by context id. */
+export type DecidingMap = Readonly<Record<string, Deciding>>;
+
+/** Applies a `decide_updated` event; returns the same map for anything else. */
+export function applyDecideEvent(map: DecidingMap, ev: { type?: string; data?: any }): DecidingMap {
+ if (ev.type !== 'decide_updated' && ev.type !== 'DecideUpdated') return map;
+ const d = ev.data ?? {};
+ const ctx: unknown = d.context_id ?? d.thread_id ?? d.kwant_id;
+ if (typeof ctx !== 'string' || !ctx) return map;
+ if (d.state === 'deciding') {
+ return {
+ ...map,
+ [ctx]: {
+ kwantId: str(d.kwant_id),
+ heldTurnId: typeof d.held_turn_id === 'string' ? d.held_turn_id : null,
+ consulted: Array.isArray(d.consulted) ? d.consulted.filter((n: unknown): n is string => typeof n === 'string') : (map[ctx]?.consulted ?? []),
+ },
+ };
+ }
+ if (!(ctx in map)) return map;
+ const next = { ...map };
+ delete next[ctx];
+ return next;
+}
+
+/** After a (re)connect: chats with a consult or decide turn running (`purpose: "decide"`). */
+export function hydrateDeciding(turns: Array<{ context_id?: string; kwant_id?: string; purpose?: string }> | undefined): DecidingMap {
+ const out: Record<string, Deciding> = {};
+ for (const t of turns ?? []) {
+ if (t?.purpose !== 'decide' || !t.context_id || out[t.context_id]) continue;
+ out[t.context_id] = { kwantId: t.kwant_id ?? '', heldTurnId: null, consulted: [] };
+ }
+ return out;
+}
+
+/** The line under "Team is deciding…". */
+export function decidingDetail(botName: string, consulted: string[]): string {
+ const who = botName || 'The bot';
+ if (!consulted.length) return `${who} is running the checks it listed and making the call, instead of asking you.`;
+ return `${who} is checking with ${consultedLine(consulted).replace(/^Asked /, '').replace(/ first\.$/, '')} and making the call, instead of asking you.`;
+}
+
+// ---------------------------------------------------------------------------
+// "While you were away"
+
+export interface WorkAheadMeta {
+ kind: 'work_ahead';
+ date: string;
+ run_id: string;
+}
+
+export function parseWorkAhead(raw: unknown): WorkAheadMeta | null {
+ const m = parseMetaObject(raw);
+ if (!m || m.kind !== 'work_ahead') return null;
+ return { kind: 'work_ahead', date: str(m.date), run_id: str(m.run_id) };
+}
+
+/** One plain line for the collapsed message: the first sentence-ish line without markdown. */
+export function workAheadSummary(text: string, max = 140): string {
+ const line =
+ text
+ .split('\n')
+ .map((l) => l.replace(/^[#>*\-\s]+/, '').replace(/[*_`]/g, '').trim())
+ .find(Boolean) ?? '';
+ return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;
+}
+
+// ---------------------------------------------------------------------------
+// ask_user cards: why only the person can answer
+
+export type WhyYou = 'irreversible' | 'outside' | 'money' | 'secret_or_signin' | 'taste_no_signal' | 'missing_after_research';
+
+const WHY_YOU: Record<WhyYou, string> = {
+ irreversible: 'It can’t be undone.',
+ outside: 'It sends something or contacts someone.',
+ money: 'It spends money.',
+ secret_or_signin: 'It needs a password or a sign-in.',
+ taste_no_signal: 'It’s a matter of taste and there’s nothing to go on yet.',
+ missing_after_research: 'The bot looked and couldn’t find it.',
+};
+
+export const whyYouText = (v: unknown): string | null => (typeof v === 'string' && v in WHY_YOU ? WHY_YOU[v as WhyYou] : null);
+
+// ---------------------------------------------------------------------------
+// App settings
+
+export const WORK_AHEAD_CAP_MIN = 1;
+export const WORK_AHEAD_CAP_MAX = 10;
+
+export interface ProactiveSettings {
+ decide_first: boolean;
+ work_ahead: boolean;
+ work_ahead_daily_cap: number;
+}
+
+/** The three settings from GET /api/settings; null on a server without them. */
+export function parseProactiveSettings(data: unknown): ProactiveSettings | null {
+ if (!data || typeof data !== 'object') return null;
+ const d = data as Record<string, unknown>;
+ if (typeof d.decide_first !== 'boolean') return null;
+ const cap = typeof d.work_ahead_daily_cap === 'number' && Number.isInteger(d.work_ahead_daily_cap) ? d.work_ahead_daily_cap : 3;
+ return {
+ decide_first: d.decide_first,
+ work_ahead: typeof d.work_ahead === 'boolean' ? d.work_ahead : true,
+ work_ahead_daily_cap: Math.min(WORK_AHEAD_CAP_MAX, Math.max(WORK_AHEAD_CAP_MIN, cap)),
+ };
+}
diff --git a/frontend/src/questions.ts b/frontend/src/questions.ts
index 939e422c..9ee6db8e 100644
--- a/frontend/src/questions.ts
+++ b/frontend/src/questions.ts
@@ -28,6 +28,10 @@ export interface QuestionMeta {
choices: string[];
status: QuestionStatus;
answer: string | null;
+ /** Why only the person can answer (decide-first); null on older cards. */
+ why_you?: string | null;
+ /** What the bot already tried; null on older cards. */
+ checked?: string | null;
}
export const ANSWER_MAX = 2000;
@@ -50,7 +54,16 @@ export function parseQuestionMeta(raw: unknown): QuestionMeta | null {
if (!m || m.kind !== 'ask_user' || typeof m.question_id !== 'string' || typeof m.question !== 'string') return null;
const choices = Array.isArray(m.choices) ? m.choices.filter((c): c is string => typeof c === 'string') : [];
const status: QuestionStatus = m.status === 'answered' || m.status === 'cancelled' ? m.status : 'open';
- return { kind: 'ask_user', question_id: m.question_id, question: m.question, choices, status, answer: typeof m.answer === 'string' ? m.answer : null };
+ return {
+ kind: 'ask_user',
+ question_id: m.question_id,
+ question: m.question,
+ choices,
+ status,
+ answer: typeof m.answer === 'string' ? m.answer : null,
+ why_you: typeof m.why_you === 'string' ? m.why_you : null,
+ checked: typeof m.checked === 'string' && m.checked.trim() ? m.checked.trim() : null,
+ };
}
/** The chat a question lives in: the thread, else the channel, else the agent's direct chat. */
diff --git a/frontend/src/threads.ts b/frontend/src/threads.ts
index b79cba54..0a3f3b38 100644
--- a/frontend/src/threads.ts
+++ b/frontend/src/threads.ts
@@ -29,6 +29,8 @@ export interface ActiveTurn {
thread_id: string | null;
state: 'queued' | 'running';
since?: string;
+ /** "decide": a consult or decide turn of the decide-first gate. */
+ purpose?: string;
}
export interface Thread {
diff --git a/frontend/tests/appUpdate.test.mjs b/frontend/tests/appUpdate.test.mjs
index 9dc3d39b..713af1b0 100644
--- a/frontend/tests/appUpdate.test.mjs
+++ b/frontend/tests/appUpdate.test.mjs
@@ -357,7 +357,7 @@ test('app_update is saved in the Mac app and never sent to a server without it',
test('App settings shows the switch only when the update API is supported', () => {
const s = src('components/SettingsModal.tsx');
assert.match(s, /const appUpdates = useAppUpdate\(\)\.model\.status !== null;/);
- assert.match(s, /notifyKindsFor\(appUpdates\)\.map/);
- assert.match(s, /notify_on: notifyOnToSave\(notifyOn, appUpdates\)/);
+ assert.match(s, /notifyKindsFor\(appUpdates, !!proactive\)\.map/);
+ assert.match(s, /notify_on: notifyOnToSave\(notifyOn, appUpdates, !!proactive\)/);
assert.doesNotMatch(s, /\{NOTIFY_KINDS\.map/);
});
diff --git a/frontend/tests/proactive.test.mjs b/frontend/tests/proactive.test.mjs
new file mode 100644
index 00000000..8362f9d1
--- /dev/null
+++ b/frontend/tests/proactive.test.mjs
@@ -0,0 +1,206 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { loadBundled } from './bundle.mjs';
+
+// The markdown renderer pulls in the UI sounds, which read localStorage when loaded.
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const p = await loadBundled(`export * from './src/decideFirst';`);
+const notify = await loadBundled(`export * from './src/continuity';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { DecisionChips, DecidingLine, WorkAheadBody } from './src/components/Proactive';
+ import { QuestionCard } from './src/components/QuestionCard';
+ const r = (C) => (props) => renderToStaticMarkup(React.createElement(C, props));
+ export const chips = r(DecisionChips);
+ export const deciding = r(DecidingLine);
+ export const workAhead = r(WorkAheadBody);
+ export const question = r(QuestionCard);
+`);
+const src = (path) => readFileSync(new URL(`../src/${path}`, import.meta.url), 'utf8');
+
+// The example from contract.md §1
+const DESIGN = {
+ index: 0,
+ question: 'Which design direction?',
+ options: ['A: Classic', 'B: Wax seal', 'C: Green desk'],
+ picked: 'B: Wax seal',
+ why: 'Matches the wax-seal hero you asked for and stays easy to read.',
+ status: 'decided',
+ changed_to: null,
+};
+const meta = (over = {}) =>
+ JSON.stringify({ decisions: [DESIGN], decide_first: { consulted: ['Designer'], held_turn_id: 't1', kwant_id: 'lead' }, ...over });
+
+test('decisions parse from the contract shape, as a string or an object', () => {
+ const [d] = p.parseDecisions(meta());
+ assert.deepEqual(d, DESIGN);
+ assert.equal(p.parseDecisions(JSON.parse(meta())).length, 1);
+ assert.deepEqual(p.consultedNames(meta()), ['Designer']);
+});
+
+test('junk, other metas and decisions without a pick give nothing', () => {
+ for (const raw of [null, '', 'not json', '{"kind":"ask_user"}', '{"decisions":"x"}', JSON.stringify({ decisions: [{ question: 'Q', options: ['a'] }, 7, null] })])
+ assert.deepEqual(p.parseDecisions(raw), []);
+ assert.deepEqual(p.consultedNames('{"decisions":[]}'), []);
+ // A missing index falls back to the position
+ assert.equal(p.parseDecisions(JSON.stringify({ decisions: [{ ...DESIGN, index: undefined }] }))[0].index, 0);
+});
+
+test('a changed decision shows the person’s pick and offers no second Change', () => {
+ const [d] = p.parseDecisions(meta({ decisions: [{ ...DESIGN, status: 'changed', changed_to: 'A: Classic' }] }));
+ assert.equal(p.decisionLabel(d), 'You chose: A: Classic');
+ assert.deepEqual(p.changeOptions(d), []);
+ // "changed" without changed_to is treated as still decided
+ const [odd] = p.parseDecisions(meta({ decisions: [{ ...DESIGN, status: 'changed' }] }));
+ assert.equal(odd.status, 'decided');
+ assert.equal(p.decisionLabel(DESIGN), 'Decided: B: Wax seal');
+ assert.deepEqual(p.changeOptions(DESIGN), ['A: Classic', 'C: Green desk']);
+});
+
+test('consulted line reads naturally', () => {
+ assert.equal(p.consultedLine([]), '');
+ assert.equal(p.consultedLine(['Designer']), 'Asked Designer first.');
+ assert.equal(p.consultedLine(['Designer', 'Writer']), 'Asked Designer and Writer first.');
+ assert.equal(p.decidingDetail('Mira', ['Designer']), 'Mira is checking with Designer and making the call, instead of asking you.');
+ assert.match(p.decidingDetail('Mira', []), /^Mira is running the checks it listed/);
+});
+
+test('Change posts the new pick to the contract route', async () => {
+ const calls = [];
+ const prev = globalThis.fetch;
+ globalThis.fetch = async (url, init) => {
+ calls.push([init.method, url, JSON.parse(init.body)]);
+ return { ok: true, status: 200, json: async () => ({ message: { id: 'm 1' }, prompt: '@Mira Change of decision' }) };
+ };
+ try {
+ const res = await p.decisionsApi.change('m 1', 0, 'A: Classic');
+ assert.equal(res.prompt, '@Mira Change of decision');
+ assert.deepEqual(calls, [['POST', '/api/messages/m%201/decisions/0/change', { picked: 'A: Classic' }]]);
+ // 409 surfaces the server's words
+ globalThis.fetch = async () => ({ ok: false, status: 409, json: async () => ({ error: 'Already changed.' }) });
+ await assert.rejects(p.decisionsApi.change('m1', 0, 'A: Classic'), /Already changed\./);
+ } finally {
+ globalThis.fetch = prev;
+ }
+});
+
+test('decide_updated: deciding adds the chat, any done removes it', () => {
+ const ev = (data) => ({ type: 'decide_updated', data: { kwant_id: 'lead', context_id: 'ch1', thread_id: null, held_turn_id: 't1', ...data } });
+ let m = p.applyDecideEvent({}, ev({ state: 'deciding', consulted: [] }));
+ assert.deepEqual(m, { ch1: { kwantId: 'lead', heldTurnId: 't1', consulted: [] } });
+ m = p.applyDecideEvent(m, ev({ state: 'deciding', consulted: ['Designer'] }));
+ assert.deepEqual(m.ch1.consulted, ['Designer']);
+ for (const outcome of ['decided', 'posted_original', 'cancelled']) assert.deepEqual(p.applyDecideEvent(m, ev({ state: 'done', outcome })), {});
+ // Unrelated events and a done for a chat not deciding keep the same map
+ assert.equal(p.applyDecideEvent(m, { type: 'turn_started', data: {} }), m);
+ const empty = {};
+ assert.equal(p.applyDecideEvent(empty, ev({ state: 'done' })), empty);
+});
+
+test('after a reload, turns with purpose "decide" bring the line back', () => {
+ const m = p.hydrateDeciding([
+ { turn_id: 'a', kwant_id: 'designer', context_id: 'ch1', purpose: 'decide' },
+ { turn_id: 'b', kwant_id: 'lead', context_id: 'ch1', purpose: 'decide' },
+ { turn_id: 'c', kwant_id: 'writer', context_id: 'ch2' },
+ ]);
+ assert.deepEqual(Object.keys(m), ['ch1']);
+ assert.deepEqual(p.hydrateDeciding(undefined), {});
+});
+
+test('work-ahead meta and its one-line summary', () => {
+ assert.deepEqual(p.parseWorkAhead('{"kind":"work_ahead","date":"2026-10-26","run_id":"r1"}'), { kind: 'work_ahead', date: '2026-10-26', run_id: 'r1' });
+ assert.equal(p.parseWorkAhead('{"kind":"ask_user"}'), null);
+ assert.equal(p.workAheadSummary('\n## While you were away I **ran** the contrast check.\n\n- A passes'), 'While you were away I ran the contrast check.');
+ assert.equal(p.workAheadSummary('x'.repeat(200)).length, 140);
+});
+
+test('settings: parsed only from a server that has them, cap kept in 1–10', () => {
+ assert.equal(p.parseProactiveSettings({ agent_tools: true }), null);
+ assert.deepEqual(p.parseProactiveSettings({ decide_first: false, work_ahead: true, work_ahead_daily_cap: 5 }), {
+ decide_first: false,
+ work_ahead: true,
+ work_ahead_daily_cap: 5,
+ });
+ assert.deepEqual(p.parseProactiveSettings({ decide_first: true }), { decide_first: true, work_ahead: true, work_ahead_daily_cap: 3 });
+ assert.equal(p.parseProactiveSettings({ decide_first: true, work_ahead_daily_cap: 40 }).work_ahead_daily_cap, 10);
+});
+
+test('work_ahead notifications: listed and saved only where the server has the setting', () => {
+ const ids = (a, w) => notify.notifyKindsFor(a, w).map((k) => k.id);
+ assert.ok(!ids(false, false).includes('work_ahead'));
+ assert.ok(ids(false, true).includes('work_ahead'));
+ assert.equal(ids(true, true).at(-1), 'app_update');
+ assert.deepEqual(notify.notifyOnToSave(['turn_finished', 'work_ahead'], false, false), ['turn_finished']);
+ assert.deepEqual(notify.notifyOnToSave(['turn_finished', 'work_ahead'], false, true), ['turn_finished', 'work_ahead']);
+ assert.equal(notify.shouldShowOsNotification({ enabled: true, permission: 'granted', hidden: true, kind: 'work_ahead' }), true);
+});
+
+test('chips: question, pick, why, who was asked, and a Change button', () => {
+ const html = ui.chips({ messageId: 'm1', decisions: [DESIGN], consulted: ['Designer'], onChange: async () => {} });
+ assert.match(html, /aria-label="Decided by the team"/);
+ assert.match(html, /Which design direction\?/);
+ assert.match(html, /Decided: B: Wax seal/);
+ assert.match(html, /Why: Matches the wax-seal hero/);
+ assert.match(html, /Asked Designer first\./);
+ assert.match(html, /aria-expanded="false"[^>]*>Change</);
+ // Without a handler, or once changed, there's nothing to press
+ assert.doesNotMatch(ui.chips({ messageId: 'm1', decisions: [DESIGN] }), />Change</);
+ const changed = ui.chips({ messageId: 'm1', decisions: [{ ...DESIGN, status: 'changed', changed_to: 'A: Classic' }], onChange: async () => {} });
+ assert.match(changed, /You chose: A: Classic/);
+ assert.doesNotMatch(changed, />Change</);
+ assert.equal(ui.chips({ messageId: 'm1', decisions: [] }), '');
+});
+
+test('"Team is deciding…" is a polite status with plain words', () => {
+ const html = ui.deciding({ botName: 'Mira', consulted: ['Designer'] });
+ assert.match(html, /role="status"/);
+ assert.match(html, /aria-live="polite"/);
+ assert.match(html, /Team is deciding…/);
+ assert.match(html, /Mira is checking with Designer/);
+});
+
+test('"While you were away" starts collapsed to one line', () => {
+ const html = ui.workAhead({ messageId: 'm9', text: 'While you were away I ran the contrast check.\n\nNext I expect you’ll want the CSS.' });
+ assert.match(html, /While you were away<\/span>/);
+ assert.match(html, /aria-expanded="false"/);
+ assert.match(html, /aria-controls="wa-m9"/);
+ assert.match(html, /id="wa-m9" hidden=""/);
+ assert.doesNotMatch(html, /Next I expect/);
+});
+
+test('question cards say why only the person can answer, when the bot said', () => {
+ const base = { kind: 'ask_user', question_id: 'q1', question: 'Send the email to Ana?', choices: ['Send', 'Not yet'], status: 'open', answer: null };
+ const props = { messageId: 'm1', kwantName: 'Mira', waiting: true, onAnswer: async () => {}, onDismiss: async () => {} };
+ const html = ui.question({ ...props, meta: { ...base, why_you: 'outside', checked: 'Drafted it and checked the address.' } });
+ assert.match(html, /Only you can answer: It sends something or contacts someone\./);
+ assert.match(html, /Already tried: Drafted it and checked the address\./);
+ const old = ui.question({ ...props, meta: base });
+ assert.doesNotMatch(old, /Only you can answer|Already tried/);
+ assert.equal(p.whyYouText('nonsense'), null);
+});
+
+test('wiring: chat view, app and settings', () => {
+ const chat = src('components/ChatView.tsx');
+ // The line stands in for the streamed draft while deciding
+ assert.match(chat, /\{deciding && <DecidingLine/);
+ assert.match(chat, /\{isStreaming && !deciding && routingState\?\.phase !== 'deciding'/);
+ assert.match(chat, /<DecisionChips/);
+ assert.match(chat, /<WorkAheadBody messageId=\{msg\.id\}/);
+
+ const app = src('App.tsx');
+ assert.match(app, /case 'decide_updated':/);
+ assert.match(app, /setDeciding\(hydrateDeciding\(list\)\)/);
+ // message_added with a known id replaces it (a changed decision)
+ assert.match(app, /if \(list\.some\(\(x\) => x\.id === m\.id\)\) \{\s*const replaced = list\.map/);
+ // Change: record, then send the server's prompt to the same chat
+ assert.match(app, /decisionsApi\.change<ChatMessage>\(msg\.id, index, picked\)/);
+ assert.match(app, /await handleSendMessage\(prompt\)/);
+
+ const settings = src('components/SettingsModal.tsx');
+ assert.match(settings, /Bots decide reversible choices themselves/);
+ assert.match(settings, /Bots work ahead while I’m away/);
+ assert.match(settings, /\.\.\.\(proactive \?\? \{\}\)/);
+});