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
Live activity and human steps in the chat UI
Pixel (kwant bot)b0b6cd60b46e
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex d3fb68fb..a7669bf7 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -8,6 +8,17 @@ import { DelegationCard } from './components/DelegationCard';import { ApprovalsOffBadge } from './components/ApprovalsSetting';import { APPROVALS_CHANGED_EVENT, approvalsOff } from './approvalMode';import { QuestionCard } from './components/QuestionCard';+import { HumanStepCard } from './components/HumanStepCard';+import { LiveActivity, appendThinking, applyActivity, parseStep } from './activity';+import {+ HumanStep,+ HumanStepMeta,+ applyHumanStep,+ humanStepsApi,+ latestOpenStep,+ openStepsByKwant,+ turnsAwaitingStep,+} from './humanSteps';import { McpSuggestionCard } from './components/McpSuggestionCard';import { Suggestion, SuggestionMeta, applySuggestion, suggestionsApi } from './mcpSuggestions';import { ApiError, BotActionMeta, HireMeta, applyBotAction, applyHire, botActionsApi, changesBots, decisionError, hiresApi } from './botActions';@@ -170,6 +181,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const [streamingText, setStreamingText] = useState('');const [streamingThinking, setStreamingThinking] = useState('');const streamsRef = useRef<Record<string, { text: string; thinking: string }>>({});+ // Running turns' live steps by turn id (with the chat they belong to), until the saved reply shows.+ const [activity, setActivity] = useState<Record<string, LiveActivity & { ctx: string }>>({});+ const activityRef = useRef(activity);+ const setActivityMap = (next: Record<string, LiveActivity & { ctx: string }>) => {+ activityRef.current = next;+ setActivity(next);+ };// Chats with a reply in flight -> who is replying. Several can stream at once.const [live, setLive] = useState<Record<string, string>>({});const liveRef = useRef(live);@@ -286,6 +304,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const openSkillsRef = useRef<(kwantId: string) => void>(() => undefined);// Opens the chat of a bot's newest open question; false when it has none.const openQuestionRef = useRef<(kwantId: string) => boolean>(() => false);+ // Opens the chat of a bot's newest open browser step; false when it has none.+ const openHumanStepRef = useRef<(kwantId: string) => boolean>(() => false);const openTargetRef = useRef<(t: { channel_id: string | null; kwant_id: string | null }) => boolean>(() => false);const showNotification = (n: NotifyEvent) => {// Another space's news is the shell's to show, with a way to switch there.@@ -302,7 +322,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({? { label: 'Review', onClick: () => openSkillsRef.current(n.kwant_id) }: n.kind === 'question_asked'? { label: 'Answer', onClick: () => openQuestionRef.current(n.kwant_id) || openTargetRef.current(target) }- : { label: 'Open', onClick: () => openTargetRef.current(target) };+ : n.kind === 'human_step'+ ? { label: 'Open', onClick: () => openHumanStepRef.current(n.kwant_id) || openTargetRef.current(target) }+ : { label: 'Open', onClick: () => openTargetRef.current(target) };setToasts((prev) => [...prev.slice(-2), { id, title: n.title, detail: n.body, action }]);if (n.kind !== 'routine_failed') playSfx('alert');return;@@ -313,6 +335,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({note.onclick = () => {window.focus();if (n.kind === 'skill_proposed') openSkillsRef.current(n.kwant_id);+ else if (n.kind === 'human_step' && openHumanStepRef.current(n.kwant_id)) setIsVmPaneOpen(true);else if (!(n.kind === 'question_asked' && openQuestionRef.current(n.kwant_id))) openTargetRef.current(target);note.close();};@@ -448,6 +471,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({});}, () => undefined);suggestionsApi.list().then((list) => setSuggestions((prev) => list.reduce(applySuggestion, prev)), () => undefined);+ humanStepsApi.listOpen().then((list) => {+ setHumanSteps((prev) => {+ const next: Record<string, HumanStep> = {};+ for (const st of list) next[st.id] = st;+ for (const st of Object.values(prev)) if (st.status !== 'open' && !next[st.id]) next[st.id] = st;+ return next;+ });+ }, () => undefined);try {const { turns: list } = await threadsApi.turns();const map = hydrateTurns(list);@@ -483,6 +514,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const [questions, setQuestions] = useState<Record<string, Question>>({});const questionsRef = useRef(questions);questionsRef.current = questions;+ // Steps bots asked the person to do in the browser: open ones from the server, plus every human_step_updated.+ const [humanSteps, setHumanSteps] = useState<Record<string, HumanStep>>({});+ const humanStepsRef = useRef(humanSteps);+ humanStepsRef.current = humanSteps;// Bots' tool suggestions by id (from the list and mcp_suggestion_updated), and installed// servers that still need the person to sign in.const [suggestions, setSuggestions] = useState<Record<string, Suggestion>>({});@@ -599,8 +634,19 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const completed = new Set<string>();/** After a reply: drop the chat's stream once nothing else runs or waits there. */+ /** Live steps of turns in `ctx` that have finished: their saved reply carries them now. */+ const dropActivity = (ctx: string) => {+ const cur = activityRef.current;+ const running = new Set(turnsIn(turnsRef.current, ctx).map((t) => t.turn_id));+ const gone = Object.keys(cur).filter((id) => cur[id].ctx === ctx && (completed.has(id) || !running.has(id)));+ if (!gone.length) return;+ const next = { ...cur };+ for (const id of gone) delete next[id];+ setActivityMap(next);+ };const settle = (ctx: string | null) => {if (!ctx) return;+ dropActivity(ctx);if (discussionInProgressRef.current && ctx === streamingContextIdRef.current) return;if (turnsIn(turnsRef.current, ctx).length > 0) {streamsRef.current[ctx] = { text: '', thinking: '' };@@ -781,6 +827,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const ctx = streamTarget(event, streamingContextIdRef.current);if (!ctx) break;const buf = (streamsRef.current[ctx] ??= { text: '', thinking: '' });+ if (event.type === 'ThinkingDelta' && typeof event.turn_id === 'string') {+ // Thinking under an open thinking step goes into it; anything else is a status line.+ const cur = activityRef.current[event.turn_id];+ const next = appendThinking(cur, event.turn_id, String(event.data ?? ''));+ if (cur && next) {+ setActivityMap({ ...activityRef.current, [event.turn_id]: { ...next, ctx: cur.ctx } });+ break;+ }+ }if (event.type === 'TextDelta') buf.text += event.data;else buf.thinking = event.data;if (!(ctx in liveRef.current)) markLive(ctx, kwantName(event.kwant_id));@@ -792,6 +847,25 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}break;}+ case 'activity':+ case 'Activity': {+ const step = parseStep(event.data?.step);+ const ctx = streamTarget(event, streamingContextIdRef.current);+ const turnId: string | undefined = typeof event.turn_id === 'string' ? event.turn_id : undefined;+ if (!step || !ctx || !turnId) break;+ const cur = activityRef.current[turnId];+ setActivityMap({ ...activityRef.current, [turnId]: { ...applyActivity(cur, turnId, step), ctx } });+ if (!(ctx in liveRef.current)) markLive(ctx, kwantName(event.kwant_id));+ break;+ }+ case 'human_step_updated':+ case 'HumanStepUpdated': {+ const st: HumanStep | undefined = event.data?.step;+ if (!st?.id) break;+ setHumanSteps((prev) => applyHumanStep(prev, st));+ if (st.status === 'open') playSfx('alert');+ break;+ }case 'routing_started':case 'RoutingStarted': {const ctx = event.data?.context_id;@@ -1276,6 +1350,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({if (q.message_id) setHighlightMessageId(q.message_id);return true;};+ openHumanStepRef.current = (kwantId: string) => {+ const st = latestOpenStep(humanStepsRef.current, kwantId);+ if (!st) return false;+ if (st.thread_id) openThread(st.kwant_id, st.thread_id);+ else openTarget({ channel_id: st.channel_id, kwant_id: st.channel_id ? null : st.kwant_id });+ if (st.message_id) setHighlightMessageId(st.message_id);+ return true;+ };openSkillsRef.current = (kwantId: string) => {const k = kwants.find((x) => x.id === kwantId);if (k) openAgentSettings(k, 'skills');@@ -1427,6 +1509,47 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({);};+ /** Done or Skip on a browser step. A 409 means it was answered elsewhere: show how it ended. */+ const answerHumanStep = async (id: string, which: 'done' | 'decline'): Promise<string | void> => {+ try {+ const { step } = await (which === 'done' ? humanStepsApi.done(id) : humanStepsApi.decline(id));+ setHumanSteps((prev) => applyHumanStep(prev, step));+ } catch (err) {+ try {+ const { step } = await humanStepsApi.get(id);+ setHumanSteps((prev) => applyHumanStep(prev, step));+ if (step.status === 'done') return 'This was already marked done.';+ if (step.status === 'declined') return 'This was already skipped.';+ if (step.status === 'cancelled') return 'This was closed: the reply was stopped.';+ } catch {+ // keep the first error+ }+ return `Couldn't send that: ${errText(err)}`;+ }+ };+ const renderHumanStep = (msg: ChatMessage, meta: HumanStepMeta, flash: boolean) => {+ const st = humanSteps[meta.human_step_id];+ const turnId = st?.turn_id;+ const name = st ? kwantName(st.kwant_id) : undefined;+ return (+ <HumanStepCard+ meta={meta}+ messageId={msg.id}+ kwantName={name ?? (msg.sender_id && msg.sender_id.length <= 20 ? msg.sender_id : chatTitle)}+ kwantId={st?.kwant_id}+ live={st}+ waiting={!!turnId && !!turns[turnId]}+ onOpenBrowser={() => {+ setIsVmPaneOpen(true);+ playSfx('click');+ }}+ onDone={(id) => answerHumanStep(id, 'done')}+ onSkip={(id) => answerHumanStep(id, 'decline')}+ flash={flash}+ />+ );+ };+const handleInstallSuggestion = async (id: string, body: { env?: Record<string, string>; headers?: Record<string, string> }) => {try {const res = await suggestionsApi.install(id, body);@@ -2125,8 +2248,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const isCurrentContextStreaming = openCtx in live;const openTurns = turnsIn(turns, openCtx);// Turns paused on a question wait for the person; they don't make the bot "busy".- const awaitingTurns = turnsAwaitingAnswer(questions);+ const browserTurns = turnsAwaitingStep(humanSteps);+ const awaitingTurns = new Set([...turnsAwaitingAnswer(questions), ...browserTurns]);const awaitingHere = openTurns.some((t) => t.state === 'running' && awaitingTurns.has(t.turn_id)) && !openTurns.some((t) => t.state === 'running' && !awaitingTurns.has(t.turn_id));+ const awaitingBrowserHere = awaitingHere && openTurns.some((t) => t.state === 'running' && browserTurns.has(t.turn_id));+ // The open chat's running turn's live steps (the newest, when several reply at once).+ const activityHere = Object.values(activity).filter((a) => a.ctx === openCtx && turns[a.turnId]).pop() ?? null;+ const needsYouByKwant = openStepsByKwant(humanSteps);const waiting = openTurns.some((t) => t.state === 'running') ? undefined : openTurns.find((t) => t.state === 'queued');const queuedHere: QueuedState | null = waiting? { position: queuePosition(turns, waiting.turn_id), reason: waiting.reason ?? 'agent_busy', speaker: kwantName(waiting.kwant_id) ?? live[openCtx] ?? 'The bot' }@@ -2158,7 +2286,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({<Loader2 size={10} className="shrink-0 animate-spin motion-reduce:animate-none" aria-hidden="true" />)}<span className="truncate">- {elsewhere[0].state === 'queued' ? 'Waiting to work on ' : awaitingTurns.has(elsewhere[0].turn_id) ? 'Asked you a question in ' : 'Working on '}+ {elsewhere[0].state === 'queued' ? 'Waiting to work on ' : browserTurns.has(elsewhere[0].turn_id) ? 'Needs you in the browser in ' : awaitingTurns.has(elsewhere[0].turn_id) ? 'Asked you a question in ' : 'Working on '}{describeContext(elsewhere[0].context_id, elsewhere[0].kwant_id)}</span>{elsewhere.length > 1 && <span className="shrink-0 text-sky-300/80">+{elsewhere.length - 1} more</span>}@@ -2184,7 +2312,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const busyKwants: Record<string, string> = {};for (const t of Object.values(turns)) {if (t.context_id === openCtx || busyKwants[t.kwant_id]) continue;- busyKwants[t.kwant_id] = `${t.state === 'queued' ? 'Waiting to work on' : awaitingTurns.has(t.turn_id) ? 'Asked you a question in' : 'Working on'} ${describeContext(t.context_id, t.kwant_id)}`;+ busyKwants[t.kwant_id] = `${t.state === 'queued' ? 'Waiting to work on' : browserTurns.has(t.turn_id) ? 'Needs you in the browser in' : awaitingTurns.has(t.turn_id) ? 'Asked you a question in' : 'Working on'} ${describeContext(t.context_id, t.kwant_id)}`;}// Delete is off while the bot runs anywhere, the open chat included.@@ -2401,6 +2529,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({isChannel={isChannel}selectedTeamId={selectedTeamId}busyKwants={busyKwants}+ needsYou={needsYouByKwant}onSelectKwant={handleSelectKwant}onSelectChannel={handleSelectChannel}onSelectTeam={handleSelectTeam}@@ -2548,6 +2677,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({renderBotAction={renderBotAction}renderHire={renderHire}awaitingAnswer={awaitingHere}+ awaitingBrowser={awaitingBrowserHere}+ liveActivity={isCurrentContextStreaming ? activityHere : null}+ renderHumanStep={renderHumanStep}contextKey={openCtx}/>);diff --git a/frontend/src/activity.ts b/frontend/src/activity.tsnew file mode 100644index 00000000..7406cfbd--- /dev/null+++ b/frontend/src/activity.ts@@ -0,0 +1,170 @@+// Live activity: what a bot is doing while it works (docs/live-activity.md). Steps arrive as+// scoped `activity` events while the turn runs, thinking text streams as `ThinkingDelta`, and the+// saved reply keeps them in `meta.activity`.+import { parseMetaObject } from './questions';++export type StepKind = 'thinking' | 'tool' | 'approval' | 'human_step' | 'note';+export type StepStatus = 'running' | 'waiting' | 'ok' | 'failed' | 'done' | 'declined' | 'stopped';++export interface ActivityStep {+ id: string;+ kind: StepKind;+ status: StepStatus;+ title: string;+ tool?: string;+ detail?: string;+ /** The thinking step's whole text (set once it ends; live text is in `LiveActivity.thinking`). */+ text?: string;+ ref_id?: string;+ started_at: string;+ ended_at?: string;+ duration_ms?: number;+}++export interface SavedActivity {+ steps: ActivityStep[];+ dropped: number;+}++/** One running turn's steps, as the open chat draws them. */+export interface LiveActivity {+ turnId: string;+ steps: ActivityStep[];+ /** Thinking streamed so far, by step id. */+ thinking: Record<string, string>;+}++const KINDS: StepKind[] = ['thinking', 'tool', 'approval', 'human_step', 'note'];+const STATUSES: StepStatus[] = ['running', 'waiting', 'ok', 'failed', 'done', 'declined', 'stopped'];+const str = (v: unknown) => (typeof v === 'string' && v ? v : undefined);++/** A step from the wire, or null when it isn't one. Unknown kinds draw as notes. */+export function parseStep(raw: unknown): ActivityStep | null {+ if (!raw || typeof raw !== 'object') return null;+ const s = raw as Record<string, unknown>;+ if (typeof s.id !== 'string' || typeof s.title !== 'string') return null;+ const kind = KINDS.includes(s.kind as StepKind) ? (s.kind as StepKind) : 'note';+ const status = STATUSES.includes(s.status as StepStatus) ? (s.status as StepStatus) : 'ok';+ return {+ id: s.id,+ kind,+ status,+ title: s.title,+ tool: str(s.tool),+ detail: str(s.detail),+ text: str(s.text),+ ref_id: str(s.ref_id),+ started_at: typeof s.started_at === 'string' ? s.started_at : '',+ ended_at: str(s.ended_at),+ duration_ms: typeof s.duration_ms === 'number' ? s.duration_ms : undefined,+ };+}++/** `meta.activity` of a saved reply, or null when it has none. */+export function parseActivityMeta(raw: unknown): SavedActivity | null {+ const a = parseMetaObject(raw)?.activity;+ if (!a || typeof a !== 'object' || !Array.isArray((a as { steps?: unknown }).steps)) return null;+ const steps = ((a as { steps: unknown[] }).steps).map(parseStep).filter((s): s is ActivityStep => !!s);+ const dropped = Number((a as { dropped?: unknown }).dropped) || 0;+ return steps.length || dropped ? { steps, dropped } : null;+}++export const isOpenStep = (s: ActivityStep) => s.status === 'running' || s.status === 'waiting';++/** An `activity` event: replaces the step with the same id, else appends it. A new turn starts over. */+export function applyActivity(prev: LiveActivity | undefined, turnId: string, step: ActivityStep): LiveActivity {+ const base = prev && prev.turnId === turnId ? prev : { turnId, steps: [], thinking: {} };+ const i = base.steps.findIndex((s) => s.id === step.id);+ // A settled step doesn't go back to running (an out-of-order event loses).+ if (i >= 0 && !isOpenStep(base.steps[i]) && isOpenStep(step)) return base;+ const steps = i >= 0 ? base.steps.map((s, j) => (j === i ? step : s)) : [...base.steps, step];+ return { ...base, steps };+}++/** The thinking step text is streaming into right now, if any. */+export function runningThinking(live: LiveActivity | undefined, turnId?: string): ActivityStep | null {+ if (!live || (turnId && live.turnId !== turnId)) return null;+ const last = live.steps[live.steps.length - 1];+ return last && last.kind === 'thinking' && last.status === 'running' ? last : null;+}++/**+ * A `ThinkingDelta` chunk. Returns the new state, or null when no thinking step of this turn is+ * open (then the chunk is a status line, like "Cancelled by user", and is shown as before).+ */+export function appendThinking(live: LiveActivity | undefined, turnId: string | undefined, chunk: string): LiveActivity | null {+ const step = runningThinking(live, turnId);+ if (!live || !step) return null;+ return { ...live, thinking: { ...live.thinking, [step.id]: (live.thinking[step.id] ?? '') + chunk } };+}++/** The text to show under a thinking step: the saved text once it ended, else what streamed. */+export const thinkingText = (step: ActivityStep, live?: LiveActivity) => step.text ?? live?.thinking[step.id] ?? '';++const ms = (iso?: string) => {+ const t = iso ? Date.parse(iso) : NaN;+ return Number.isFinite(t) ? t : null;+};++/** From the first step's start to the last end, in ms (null when unknown). */+export function activitySpan(steps: ActivityStep[]): number | null {+ let start: number | null = null;+ let end: number | null = null;+ for (const s of steps) {+ const a = ms(s.started_at);+ const b = ms(s.ended_at) ?? (a !== null && typeof s.duration_ms === 'number' ? a + s.duration_ms : a);+ if (a !== null && (start === null || a < start)) start = a;+ if (b !== null && (end === null || b > end)) end = b;+ }+ return start !== null && end !== null && end >= start ? end - start : null;+}++/** "840 ms", "8.4s", "41s", "2m 05s". */+export function formatDuration(msTotal: number): string {+ if (msTotal < 1000) return `${Math.round(msTotal)} ms`;+ const s = msTotal / 1000;+ if (s < 10) return `${s.toFixed(1)}s`;+ if (s < 60) return `${Math.round(s)}s`;+ const m = Math.floor(s / 60);+ return `${m}m ${String(Math.round(s % 60)).padStart(2, '0')}s`;+}++/** Steps that count in the summary: notes explain a limit and aren't work. */+const counted = (steps: ActivityStep[]) => steps.filter((s) => s.kind !== 'note');++/** "12 steps · 41s", "1 step", plus "· 2 failed" when any failed. */+export function activitySummary(a: SavedActivity): string {+ const n = counted(a.steps).length + a.dropped;+ const parts = [`${n} ${n === 1 ? 'step' : 'steps'}`];+ const span = activitySpan(a.steps);+ if (span !== null && span >= 1000) parts.push(formatDuration(span));+ const failed = a.steps.filter((s) => s.status === 'failed').length;+ if (failed) parts.push(`${failed} failed`);+ return parts.join(' · ');+}++/** What a step's status reads as, for screen readers and the row's label. */+export function statusLabel(s: ActivityStep): string {+ switch (s.status) {+ case 'running':+ return s.kind === 'thinking' ? 'Thinking' : 'Running';+ case 'waiting':+ return 'Waiting for you';+ case 'ok':+ return s.kind === 'approval' ? 'Allowed' : 'Done';+ case 'done':+ return 'Done';+ case 'failed':+ return 'Failed';+ case 'declined':+ return s.kind === 'approval' ? 'Denied' : 'Skipped';+ case 'stopped':+ return 'Stopped';+ }+}++/** The step's title without markdown backticks (titles quote commands like "Running `cargo test`"). */+export const plainTitle = (t: string) => t.replace(/`([^`]*)`/g, '$1');++/** Whether the saved activity has thinking text, so the old reasoning block would repeat it. */+export const hasThinkingText = (a: SavedActivity | null) => !!a?.steps.some((s) => s.kind === 'thinking' && s.text);diff --git a/frontend/src/components/ActivityList.tsx b/frontend/src/components/ActivityList.tsxnew file mode 100644index 00000000..88c89c11--- /dev/null+++ b/frontend/src/components/ActivityList.tsx@@ -0,0 +1,252 @@+import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';+import { Brain, Check, ChevronRight, CircleSlash, Hand, Info, ListTree, Loader2, ShieldQuestion, X } from 'lucide-react';+import {+ ActivityStep,+ LiveActivity,+ SavedActivity,+ activitySpan,+ activitySummary,+ formatDuration,+ isOpenStep,+ plainTitle,+ statusLabel,+ thinkingText,+} from '../activity';++/** "Running `cargo test`" with the quoted part in mono. */+const Title: React.FC<{ text: string }> = ({ text }) => (+ <>+ {text.split(/(`[^`]*`)/g).map((part, i) =>+ part.startsWith('`') && part.endsWith('`') && part.length > 1 ? (+ <code key={i} className="font-mono text-[11px] px-1 py-px rounded bg-zinc-800/80 text-zinc-100 break-all">+ {part.slice(1, -1)}+ </code>+ ) : (+ <React.Fragment key={i}>{part}</React.Fragment>+ ),+ )}+ </>+);++const StatusIcon: React.FC<{ step: ActivityStep }> = ({ step }) => {+ const label = statusLabel(step);+ const icon = (() => {+ switch (step.status) {+ case 'running':+ return step.kind === 'thinking' ? (+ <Brain size={13} className="text-violet-300 animate-pulse motion-reduce:animate-none" />+ ) : (+ <Loader2 size={13} className="text-sky-300 animate-spin motion-reduce:animate-none" />+ );+ case 'waiting':+ return step.kind === 'approval' ? <ShieldQuestion size={13} className="text-amber-300" /> : <Hand size={13} className="text-amber-300" />;+ case 'ok':+ case 'done':+ return step.kind === 'thinking' ? <Brain size={13} className="text-violet-300/80" /> : <Check size={13} className="text-emerald-300" />;+ case 'failed':+ return <X size={13} className="text-rose-300" />;+ case 'declined':+ return <CircleSlash size={13} className="text-zinc-400" />;+ case 'stopped':+ return <CircleSlash size={13} className="text-zinc-400" />;+ }+ })();+ return (+ <span className="mt-px flex-shrink-0 inline-flex" role="img" aria-label={label} title={label}>+ {icon}+ </span>+ );+};++/** Re-renders every second while `on`, for the time a running step has taken so far. */+function useNow(on: boolean): number {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!on) return;+ const t = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(t);+ }, [on]);+ return now;+}++const stepTime = (s: ActivityStep, now: number): string | null => {+ if (typeof s.duration_ms === 'number') return s.kind === 'note' ? null : formatDuration(s.duration_ms);+ if (!isOpenStep(s)) return null;+ const started = Date.parse(s.started_at);+ return Number.isFinite(started) && now - started >= 1000 ? formatDuration(now - started) : null;+};++/** Live thinking text: follows the end while the person hasn't scrolled up. */+const ThinkingBox: React.FC<{ text: string; live: boolean; id: string }> = ({ text, live, id }) => {+ const ref = useRef<HTMLDivElement>(null);+ const stick = useRef(true);+ useLayoutEffect(() => {+ const el = ref.current;+ if (el && live && stick.current) el.scrollTop = el.scrollHeight;+ }, [text, live]);+ return (+ <div+ id={id}+ ref={ref}+ tabIndex={0}+ onScroll={(e) => {+ const el = e.currentTarget;+ stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;+ }}+ className="mt-1 max-h-56 overflow-y-auto rounded-lg bg-zinc-950/80 border border-zinc-800 px-3 py-2 text-xs text-zinc-300 whitespace-pre-wrap break-words leading-relaxed focus-visible:outline focus-visible:outline-2 focus-visible:outline-violet-400"+ aria-label="Thinking"+ >+ {text || <span className="text-zinc-400 italic">Nothing shared yet…</span>}+ </div>+ );+};++const StepRow: React.FC<{ step: ActivityStep; live?: LiveActivity; now: number; listId: string }> = ({ step, live, now, listId }) => {+ const time = stepTime(step, now);+ const running = step.kind === 'thinking' && step.status === 'running';+ const text = step.kind === 'thinking' ? thinkingText(step, live) : '';+ // The running thought is open; finished ones fold until asked.+ const [open, setOpen] = useState(running);+ useEffect(() => {+ if (running) setOpen(true);+ }, [running]);++ if (step.kind === 'note')+ return (+ <li className="flex items-start gap-2 px-3 py-1.5 text-[11px] text-zinc-400">+ <Info size={13} className="mt-px flex-shrink-0 text-zinc-400" aria-hidden="true" />+ <span className="min-w-0 break-words">{step.title}</span>+ </li>+ );++ const waiting = step.status === 'waiting';+ const head = (+ <>+ <StatusIcon step={step} />+ <span className={`min-w-0 flex-1 break-words ${step.status === 'stopped' ? 'text-zinc-400' : waiting ? 'text-amber-100' : 'text-zinc-200'}`}>+ {step.kind === 'thinking' ? (running ? 'Thinking…' : 'Thought') : <Title text={step.title} />}+ </span>+ {time && <span className="flex-shrink-0 font-mono text-[10px] text-zinc-400 tabular-nums">{time}</span>}+ </>+ );++ if (step.kind === 'thinking') {+ const boxId = `${listId}-${step.id}-text`;+ return (+ <li className="px-3 py-1.5 text-[12px]">+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ aria-expanded={open}+ aria-controls={open ? boxId : undefined}+ disabled={!text && !running}+ className="w-full flex items-start gap-2 text-left rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-violet-400 disabled:cursor-default"+ >+ {head}+ {(text || running) && (+ <ChevronRight size={13} className={`mt-px flex-shrink-0 text-zinc-400 transition-transform motion-reduce:transition-none ${open ? 'rotate-90' : ''}`} aria-hidden="true" />+ )}+ </button>+ {open && (text || running) && <ThinkingBox id={boxId} text={text} live={running} />}+ </li>+ );+ }++ return (+ <li className={`px-3 py-1.5 text-[12px] ${waiting ? 'bg-amber-500/[0.06]' : ''}`}>+ {step.detail ? (+ <details className="group">+ <summary className="flex items-start gap-2 cursor-pointer list-none rounded [&::-webkit-details-marker]:hidden focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400">+ {head}+ <ChevronRight size={13} className="mt-px flex-shrink-0 text-zinc-400 transition-transform motion-reduce:transition-none group-open:rotate-90" aria-hidden="true" />+ </summary>+ <pre+ className={`mt-1 ml-5 font-mono text-[11px] whitespace-pre-wrap break-all rounded-md border px-2 py-1.5 max-h-40 overflow-y-auto ${+ step.status === 'failed' ? 'text-rose-200 bg-rose-950/30 border-rose-500/20' : 'text-zinc-300 bg-zinc-950/80 border-zinc-800'+ }`}+ >+ {step.detail}+ </pre>+ </details>+ ) : (+ <div className="flex items-start gap-2">{head}</div>+ )}+ </li>+ );+};++const Steps: React.FC<{ steps: ActivityStep[]; live?: LiveActivity; dropped?: number; id: string }> = ({ steps, live, dropped = 0, id }) => {+ const now = useNow(steps.some(isOpenStep));+ return (+ <ol id={id} aria-label="Steps" className="divide-y divide-zinc-800/60">+ {steps.map((s) => (+ <StepRow key={s.id} step={s} live={live} now={now} listId={id} />+ ))}+ {dropped > 0 && (+ <li className="px-3 py-1.5 text-[11px] text-zinc-400">+ {dropped} more {dropped === 1 ? 'step' : 'steps'} not kept+ </li>+ )}+ </ol>+ );+};++/** While the bot works: every step so far, newest last. */+export const LiveActivityList: React.FC<{ live: LiveActivity; idBase: string }> = ({ live, idBase }) => {+ const { steps } = live;+ if (steps.length === 0) return null;+ const work = steps.filter((s) => s.kind !== 'note').length;+ const current = [...steps].reverse().find(isOpenStep);+ const span = activitySpan(steps);+ return (+ <section aria-label="What the bot is doing" className="mb-2 w-full max-w-2xl rounded-xl border border-zinc-800 bg-zinc-950/50 overflow-hidden">+ <p className="flex items-center gap-1.5 px-3 pt-2 pb-1 text-[10px] font-medium uppercase tracking-wide text-zinc-400">+ <ListTree size={11} className="text-sky-400/80" aria-hidden="true" />+ Working+ <span className="normal-case tracking-normal font-normal">+ · {work} {work === 1 ? 'step' : 'steps'}+ {span !== null && span >= 1000 ? ` · ${formatDuration(span)}` : ''}+ </span>+ </p>+ {/* Only waits are announced; a stream of tool names would be noise. */}+ <p className="sr-only" role="status" aria-live="polite">+ {current?.status === 'waiting' ? plainTitle(current.title) : ''}+ </p>+ <div className="max-h-[22rem] overflow-y-auto">+ <Steps steps={steps} live={live} id={`${idBase}-live`} />+ </div>+ </section>+ );+};++/** On a saved reply: "12 steps · 41s", opening to the list. `children` go under the steps. */+export const SavedActivityList: React.FC<{ activity: SavedActivity; idBase: string; children?: React.ReactNode }> = ({ activity, idBase, children }) => {+ const [open, setOpen] = useState(false);+ const listId = `${idBase}-steps`;+ // The engine's "no thinking shared" note stays in view while it explains a gap.+ const note = activity.steps.some((s) => s.kind === 'thinking') ? undefined : activity.steps.find((s) => s.kind === 'note');+ const failed = activity.steps.some((s) => s.status === 'failed');+ return (+ <div className="mb-2 max-w-full">+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ aria-expanded={open}+ aria-controls={open ? listId : undefined}+ className="max-w-full min-w-0 flex items-center gap-2 px-3 py-1.5 rounded-xl text-xs text-zinc-400 hover:text-zinc-200 bg-zinc-900/80 hover:bg-zinc-900 border border-zinc-800 hover:border-zinc-700/80 transition-colors cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"+ >+ <ListTree size={13} className={failed ? 'text-rose-300' : 'text-sky-400/80'} aria-hidden="true" />+ <span className="truncate min-w-0">{activitySummary(activity)}</span>+ <ChevronRight size={13} className={`flex-shrink-0 text-zinc-400 transition-transform motion-reduce:transition-none ${open ? 'rotate-90' : ''}`} aria-hidden="true" />+ </button>+ {open && (+ <div className="mt-1.5 w-full max-w-2xl rounded-xl border border-zinc-800 bg-zinc-950/50 overflow-hidden">+ <Steps steps={activity.steps} dropped={activity.dropped} id={listId} />+ {children}+ </div>+ )}+ {!open && note && <p className="mt-1 px-1 text-[11px] text-zinc-400 break-words">{note.title}</p>}+ </div>+ );+};+diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 7d81cc05..ccac038b 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -11,6 +11,9 @@ import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThrimport { PinnedInstructions, PinnedItem } from './Instructions';import { DelegationMeta, parseDelegationMeta } from '../threads';import { QuestionMeta, parseQuestionMeta } from '../questions';+import { HumanStepMeta, parseHumanStepMeta } from '../humanSteps';+import { LiveActivity, hasThinkingText, parseActivityMeta } from '../activity';+import { LiveActivityList, SavedActivityList } from './ActivityList';import { SuggestionMeta, parseSuggestionMeta } from '../mcpSuggestions';import { BotActionMeta, HireMeta, parseBotActionMeta, parseHireMeta } from '../botActions';import {@@ -174,6 +177,12 @@ export interface ChatViewProps {canRun?: boolean | null;/** The open chat's turn is paused on a question: it is waiting for the person, not working. */awaitingAnswer?: boolean;+ /** …and the pause is a browser step (sign-in, CAPTCHA) rather than a question. */+ awaitingBrowser?: boolean;+ /** The running reply's steps so far (thinking, tools, waits). */+ liveActivity?: LiveActivity | null;+ /** Draws a bot's browser-step card (message meta kind "human_step"). */+ renderHumanStep?: (msg: ChatMessage, meta: HumanStepMeta, flash: boolean) => React.ReactNode;/** Changes when another chat opens, so the view jumps to its bottom. */contextKey?: string;}@@ -326,6 +335,9 @@ export const ChatView: React.FC<ChatViewProps> = ({onOpenAccounts,canRun = null,awaitingAnswer,+ awaitingBrowser,+ liveActivity,+ renderHumanStep,contextKey,}) => {const [internalIsVmPaneOpen, setInternalIsVmPaneOpen] = useState(false);@@ -679,6 +691,8 @@ export const ChatView: React.FC<ChatViewProps> = ({if (meta && renderDelegation) return <React.Fragment key={msg.id}>{renderDelegation(msg, meta, flashId === msg.id)}</React.Fragment>;const question = msg.meta && renderQuestion ? parseQuestionMeta(msg.meta) : null;if (question && renderQuestion) return <React.Fragment key={msg.id}>{renderQuestion(msg, question, flashId === msg.id)}</React.Fragment>;+ const humanStep = msg.meta && renderHumanStep ? parseHumanStepMeta(msg.meta) : null;+ if (humanStep && renderHumanStep) return <React.Fragment key={msg.id}>{renderHumanStep(msg, humanStep, flashId === msg.id)}</React.Fragment>;const suggestion = msg.meta && renderMcpSuggestion ? parseSuggestionMeta(msg.meta) : null;if (suggestion && renderMcpSuggestion) return <React.Fragment key={msg.id}>{renderMcpSuggestion(msg, suggestion, flashId === msg.id)}</React.Fragment>;const botAction = msg.meta && renderBotAction ? parseBotActionMeta(msg.meta) : null;@@ -706,6 +720,7 @@ export const ChatView: React.FC<ChatViewProps> = ({// A bot's share_file note: the file tiles say it all.const filesOnly = files.length > 0 && isSharedFileMessage(msg.meta);const isThoughtOpen = !!openThoughts[msg.id];+ const savedActivity = !isUser && msg.meta ? parseActivityMeta(msg.meta) : null;const ranOn = isUser ? null : ranOnLabel(msg.meta);const account = isUser ? null : ranOnAccount(msg.meta);// Any auto-routed channel, not only #general: the server attaches `routing` wherever it picked the bot.@@ -748,8 +763,19 @@ export const ChatView: React.FC<ChatViewProps> = ({</p>)}- {/* Collapsible Reasoning Disclosure */}- {msg.reasoning_content && (+ {/* What the reply did: "12 steps · 41s", opening to the steps (tool calls go inside) */}+ {savedActivity && (+ <SavedActivityList activity={savedActivity} idBase={`act-${msg.id}`}>+ {msg.tool_calls && (+ <div className="border-t border-zinc-800/60 p-2">+ <ToolCallsList raw={msg.tool_calls} />+ </div>+ )}+ </SavedActivityList>+ )}++ {/* Collapsible Reasoning Disclosure (the steps above already hold the thinking when they have it) */}+ {msg.reasoning_content && !hasThinkingText(savedActivity) && (<div className="mb-2 max-w-full"><buttontype="button"@@ -789,7 +815,7 @@ export const ChatView: React.FC<ChatViewProps> = ({)}{files.length > 0 && <FileTiles files={files} align={isUser ? 'end' : 'start'} />}- {!isUser && msg.tool_calls && <ToolCallsList raw={msg.tool_calls} />}+ {!isUser && msg.tool_calls && !savedActivity && <ToolCallsList raw={msg.tool_calls} />}{/* Copy action */}{!isUser && !filesOnly && (@@ -1074,7 +1100,7 @@ export const ChatView: React.FC<ChatViewProps> = ({) : awaitingAnswer ? (<span className="inline-flex items-center gap-1 text-amber-300 text-[10px]"><span className="w-1.5 h-1.5 rounded-full bg-amber-300" aria-hidden="true" />- Waiting for your answer+ {awaitingBrowser ? 'Waiting for you in the browser' : 'Waiting for your answer'}</span>) : (<span className="inline-flex items-center gap-1 text-sky-400 text-[10px]">@@ -1084,8 +1110,10 @@ export const ChatView: React.FC<ChatViewProps> = ({)}</div>+ {liveActivity && <LiveActivityList live={liveActivity} idBase={`live-${liveActivity.turnId}`} />}+{streamingThinking && (- <div className="mb-2 p-2.5 rounded-xl bg-violet-950/20 border border-violet-500/20 text-xs font-mono text-violet-300/90 flex items-center gap-2 animate-pulse max-w-full">+ <div className="mb-2 p-2.5 rounded-xl bg-violet-950/20 border border-violet-500/20 text-xs font-mono text-violet-300/90 flex items-center gap-2 animate-pulse motion-reduce:animate-none max-w-full"><Sparkles size={13} className="text-violet-400 flex-shrink-0" /><span className="truncate">{streamingThinking}</span></div>@@ -1103,7 +1131,9 @@ export const ChatView: React.FC<ChatViewProps> = ({<MarkdownRenderer content={stripDiscussionMarkers(streamingText)} isStreaming={true} />) : awaitingAnswer ? (<p className="text-zinc-400" role="status">- Paused on the question above. Answer it there; this reply carries on from it.+ {awaitingBrowser+ ? 'Paused on the browser step above. Do it in the browser panel and press Done; this reply carries on from it.'+ : 'Paused on the question above. Answer it there; this reply carries on from it.'}</p>) : (<span className="inline-flex gap-1 py-1.5" aria-label="Waiting for the first words">diff --git a/frontend/src/components/HumanStepCard.tsx b/frontend/src/components/HumanStepCard.tsxnew file mode 100644index 00000000..b192c878--- /dev/null+++ b/frontend/src/components/HumanStepCard.tsx@@ -0,0 +1,146 @@+import React, { useState } from 'react';+import { CheckCircle2, Clock, Globe, Hand, Loader2, MinusCircle, MonitorPlay } from 'lucide-react';+import { ModernAvatar } from './ModernAvatar';+import { HumanStep, HumanStepMeta, KIND_TEXT, domainOf, humanStepView } from '../humanSteps';++export interface HumanStepCardProps {+ meta: HumanStepMeta;+ messageId: string;+ kwantName: string;+ kwantId?: string;+ /** Live record from `human_step_updated`, when known; wins over `meta`. */+ live?: HumanStep | null;+ /** A turn is paused on this step right now (else Done starts a new reply). */+ waiting: boolean;+ /** Shows the bot's browser panel. */+ onOpenBrowser?: (sandboxTarget: string | null) => void;+ /** Resolve to an error message on failure. */+ onDone: (id: string) => Promise<string | void>;+ onSkip: (id: string) => Promise<string | void>;+ flash?: boolean;+}++/**+ * A bot asks the person to do one step in its browser: sign in, solve a CAPTCHA or enter a code.+ * Only the site's domain is shown. Done and Skip answer it; a closed card keeps the outcome.+ */+export const HumanStepCard: React.FC<HumanStepCardProps> = ({ meta, messageId, kwantName, kwantId, live, waiting, onOpenBrowser, onDone, onSkip, flash }) => {+ const view = humanStepView(meta, live);+ const [busy, setBusy] = useState<'done' | 'skip' | null>(null);+ const [error, setError] = useState<string | null>(null);+ // Shown right away; the server's human_step_updated confirms it.+ const [sent, setSent] = useState<'done' | 'declined' | null>(null);++ const status = sent && view.status === 'open' ? sent : view.status;+ const open = status === 'open';+ const text = KIND_TEXT[view.step_kind];+ const domain = domainOf(view.url);+ const headingId = `hs-${messageId}`;++ const answer = async (which: 'done' | 'skip') => {+ if (!open || busy) return;+ setBusy(which);+ setError(null);+ const err = await (which === 'done' ? onDone : onSkip)(meta.human_step_id);+ setBusy(null);+ if (err) setError(err);+ else setSent(which === 'done' ? 'done' : 'declined');+ };++ const line =+ status === 'done' ? (+ <span className="inline-flex items-center gap-1.5 text-emerald-300">+ <CheckCircle2 size={13} aria-hidden="true" /> Done. {kwantName} is carrying on{view.status === 'open' ? '…' : '.'}+ </span>+ ) : status === 'declined' ? (+ <span className="inline-flex items-center gap-1.5 text-zinc-400">+ <MinusCircle size={13} aria-hidden="true" /> Skipped. {kwantName} continues without it.+ </span>+ ) : status === 'cancelled' ? (+ <span className="inline-flex items-center gap-1.5 text-zinc-400">+ <MinusCircle size={13} aria-hidden="true" /> Closed: the reply was stopped.+ </span>+ ) : waiting ? (+ <span className="inline-flex items-center gap-1.5 text-amber-300">+ <Clock size={13} aria-hidden="true" /> {kwantName} is paused and waiting for you.+ </span>+ ) : (+ <span className="inline-flex items-center gap-1.5 text-zinc-400">+ <Clock size={13} aria-hidden="true" /> {kwantName} stopped waiting. Press Done any time and it picks up in a new reply.+ </span>+ );++ const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-amber-400';++ return (+ <section+ data-message-id={messageId}+ aria-labelledby={headingId}+ className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${flash ? 'kw-flash' : ''}`}+ >+ <ModernAvatar role={kwantName} name={kwantName} size={34} kwantId={kwantId} />+ <div className={`flex-1 min-w-0 max-w-2xl rounded-2xl rounded-tl-sm border bg-zinc-900/60 shadow-sm ${open ? 'border-amber-500/40' : 'border-zinc-800'}`}>+ <div className="px-4 pt-3 pb-2 space-y-1">+ <span className="flex items-center gap-1.5 text-[11px] font-medium text-zinc-400">+ <Hand size={12} className="text-amber-300" aria-hidden="true" />+ <span className="text-zinc-200">{kwantName}</span> needs you in the browser+ {view.source === 'auto' && <span className="text-zinc-400">· spotted automatically</span>}+ </span>+ <h3 id={headingId} className="text-sm font-semibold text-zinc-100">+ {text.heading}+ </h3>+ {view.reason && <p className="text-sm text-zinc-300 whitespace-pre-wrap break-words leading-snug">{view.reason}</p>}+ {domain && (+ <p className="inline-flex items-center gap-1.5 text-xs text-zinc-400">+ <Globe size={12} aria-hidden="true" />+ <span className="font-mono text-zinc-200">{domain}</span>+ </p>+ )}+ </div>++ {open && (+ <div className="px-4 pb-2 flex flex-col sm:flex-row sm:flex-wrap gap-2">+ {onOpenBrowser && (+ <button+ type="button"+ onClick={() => onOpenBrowser(view.sandbox_target)}+ className={`inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3 py-1.5 rounded-xl text-sm border bg-zinc-800/80 border-zinc-700 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600 ${focusRing}`}+ >+ <MonitorPlay size={14} aria-hidden="true" /> Open browser+ </button>+ )}+ <button+ type="button"+ onClick={() => answer('done')}+ disabled={busy !== null}+ className={`inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3 py-1.5 rounded-xl text-sm font-semibold bg-amber-400 text-zinc-950 hover:bg-amber-300 disabled:opacity-60 ${focusRing}`}+ >+ {busy === 'done' ? <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <CheckCircle2 size={14} aria-hidden="true" />}+ {text.done}+ </button>+ <button+ type="button"+ onClick={() => answer('skip')}+ disabled={busy !== null}+ className={`inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[34px] px-3 py-1.5 rounded-xl text-sm text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 disabled:opacity-60 ${focusRing}`}+ >+ {busy === 'skip' ? 'Skipping…' : 'Skip'}+ </button>+ </div>+ )}++ <div className="px-4 pb-3 pt-0.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px]">+ <p role="status" aria-live="polite" className="min-w-0">+ {line}+ </p>+ {open && <p className="basis-full text-zinc-400">Do it in the browser panel, then press Done. What you type into fields there isn’t passed to {kwantName}.</p>}+ {error && (+ <span role="alert" className="basis-full text-rose-300">+ {error}+ </span>+ )}+ </div>+ </div>+ </section>+ );+};diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 7a5d0a9c..2c21bca6 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -1,5 +1,5 @@import React, { useCallback, useEffect, useState } from 'react';-import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock, ShieldOff, ListChecks, Split } from 'lucide-react';+import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock, ShieldOff, ListChecks, Split, Hand } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { playSfx } from '../audio/chiptune';import { badgeText } from '../away';@@ -78,6 +78,8 @@ export interface SidebarProps {selectedTeamId?: string | null;/** Bots busy outside the open chat -> "Working on …", shown under their name. */busyKwants?: Record<string, string>;+ /** Open browser steps per bot ("Needs you" pill). */+ needsYou?: Record<string, number>;onSelectKwant: (kwant: Kwant) => void;onSelectChannel: (channel: Channel) => void;onSelectTeam: (team: Team) => void;@@ -135,6 +137,7 @@ export const Sidebar: React.FC<SidebarProps> = ({isChannel,selectedTeamId,busyKwants = {},+ needsYou = {},onSelectKwant,onSelectChannel,onSelectTeam,@@ -452,6 +455,11 @@ export const Sidebar: React.FC<SidebarProps> = ({{k.name}{busyKwants[k.id] && <span className="sr-only"> ({busyKwants[k.id]})</span>}</span>+ {needsYou[k.id] > 0 && (+ <span className="shrink-0 inline-flex text-amber-300" role="img" aria-label="Needs you in the browser" title="Needs you in the browser">+ <Hand size={11} />+ </span>+ )}{busyKwants[k.id] && (<span className="w-1.5 h-1.5 shrink-0 rounded-full bg-sky-400 animate-pulse motion-reduce:animate-none" aria-hidden="true" />)}@@ -615,6 +623,15 @@ export const Sidebar: React.FC<SidebarProps> = ({<div className="flex-1 min-w-0"><div className="flex items-center justify-between gap-1"><span className="text-xs font-semibold text-zinc-200 truncate">{k.name}</span>+ {needsYou[k.id] > 0 && (+ <span+ className="shrink-0 inline-flex items-center gap-1 px-1.5 py-px rounded-full text-[10px] font-medium bg-amber-400/15 text-amber-200 border border-amber-400/30"+ title={`${k.name} needs you in the browser`}+ >+ <Hand size={10} aria-hidden="true" />+ Needs you{needsYou[k.id] > 1 ? ` · ${needsYou[k.id]}` : ''}+ </span>+ )}{approvalsOff(k) && <ApprovalsOffBadge compact title={`${k.name} runs commands, file writes and tools without asking.`} />}{onEditKwant && (<buttondiff --git a/frontend/src/continuity.ts b/frontend/src/continuity.tsindex 76f8770a..dd9fe694 100644--- a/frontend/src/continuity.ts+++ b/frontend/src/continuity.ts@@ -99,7 +99,8 @@ export type NotifyKind =| 'delegation_finished'| 'delegation_stalled'| 'skill_proposed'- | 'question_asked';+ | 'question_asked'+ | 'human_step';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' },@@ -108,10 +109,11 @@ export const NOTIFY_KINDS: Array<{ id: NotifyKind; label: string }> = [{ id: 'delegation_stalled', label: 'A delegated task is taking long' },{ id: 'skill_proposed', label: 'A bot proposed a skill to review' },{ id: 'question_asked', label: 'A bot has a question for you' },+ { id: 'human_step', label: 'A bot needs you in the browser' },];/** 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'];+export const TOAST_KINDS: NotifyKind[] = ['routine_failed', 'delegation_finished', 'delegation_stalled', 'skill_proposed', 'question_asked', 'human_step'];export interface NotifyEvent {kind: NotifyKind;diff --git a/frontend/src/humanSteps.ts b/frontend/src/humanSteps.tsnew file mode 100644index 00000000..d4dbb8ae--- /dev/null+++ b/frontend/src/humanSteps.ts@@ -0,0 +1,124 @@+// Human steps: a bot asks the person to do one thing in its browser (sign in, a CAPTCHA, a code),+// then waits for Done or Skip (docs/live-activity.md, part 2).+import { parseMetaObject } from './questions';+import { request } from './threads';++export type HumanStepKind = 'sign_in' | 'captcha' | 'two_factor' | 'other';+export type HumanStepStatus = 'open' | 'done' | 'declined' | 'cancelled';++export interface HumanStep {+ id: string;+ kwant_id: string;+ channel_id: string | null;+ direct_kwant_id: string | null;+ thread_id: string | null;+ turn_id: string | null;+ kind: HumanStepKind;+ reason: string;+ url: string | null;+ sandbox_target: string | null;+ source: 'bot' | 'auto';+ status: HumanStepStatus;+ message_id: string | null;+ created_at: string;+ closed_at: string | null;+}++/** `meta` of the card message. */+export interface HumanStepMeta {+ kind: 'human_step';+ human_step_id: string;+ step_kind: HumanStepKind;+ reason: string;+ url: string | null;+ sandbox_target: string | null;+ source: 'bot' | 'auto';+ status: HumanStepStatus;+}++const STEP_KINDS: HumanStepKind[] = ['sign_in', 'captcha', 'two_factor', 'other'];+const STATUSES: HumanStepStatus[] = ['open', 'done', 'declined', 'cancelled'];+const kindOf = (v: unknown): HumanStepKind => (STEP_KINDS.includes(v as HumanStepKind) ? (v as HumanStepKind) : 'other');+const statusOf = (v: unknown): HumanStepStatus => (STATUSES.includes(v as HumanStepStatus) ? (v as HumanStepStatus) : 'open');++export function parseHumanStepMeta(raw: unknown): HumanStepMeta | null {+ const m = parseMetaObject(raw);+ if (!m || m.kind !== 'human_step' || typeof m.human_step_id !== 'string') return null;+ return {+ kind: 'human_step',+ human_step_id: m.human_step_id,+ step_kind: kindOf(m.step_kind),+ reason: typeof m.reason === 'string' ? m.reason : '',+ url: typeof m.url === 'string' && m.url ? m.url : null,+ sandbox_target: typeof m.sandbox_target === 'string' && m.sandbox_target ? m.sandbox_target : null,+ source: m.source === 'auto' ? 'auto' : 'bot',+ status: statusOf(m.status),+ };+}++/** Card state: the live record from `human_step_updated` wins over the (possibly stale) meta. */+export function humanStepView(meta: HumanStepMeta, live?: HumanStep | null): HumanStepMeta {+ if (!live || live.id !== meta.human_step_id) return meta;+ return { ...meta, status: live.status, url: live.url ?? meta.url, sandbox_target: live.sandbox_target ?? meta.sandbox_target };+}++/** Keeps the latest known record per step; a closed step never reopens. */+export function applyHumanStep(map: Record<string, HumanStep>, s: HumanStep): Record<string, HumanStep> {+ const prev = map[s.id];+ if (prev && prev.status === s.status) return map;+ if (prev && prev.status !== 'open' && s.status === 'open') return map;+ return { ...map, [s.id]: s };+}++/** The chat a step lives in: the thread, else the channel, else the bot's direct chat. */+export const humanStepContextId = (s: Pick<HumanStep, 'thread_id' | 'channel_id' | 'direct_kwant_id'>) =>+ s.thread_id || s.channel_id || s.direct_kwant_id || null;++/** Open steps per bot, for the sidebar badge. */+export function openStepsByKwant(map: Record<string, HumanStep>): Record<string, number> {+ const out: Record<string, number> = {};+ for (const s of Object.values(map)) if (s.status === 'open') out[s.kwant_id] = (out[s.kwant_id] ?? 0) + 1;+ return out;+}++/** The newest open step a bot raised, e.g. to open from a notification. */+export function latestOpenStep(map: Record<string, HumanStep>, kwantId: string): HumanStep | null {+ let best: HumanStep | null = null;+ for (const s of Object.values(map)) if (s.kwant_id === kwantId && s.status === 'open' && (!best || s.created_at > best.created_at)) best = s;+ return best;+}++/** Turn ids paused on a step (waiting for the person, not working). */+export function turnsAwaitingStep(map: Record<string, HumanStep>): Set<string> {+ const out = new Set<string>();+ for (const s of Object.values(map)) if (s.status === 'open' && s.turn_id) out.add(s.turn_id);+ return out;+}++/** Heading and the Done button's words for each kind. */+export const KIND_TEXT: Record<HumanStepKind, { heading: string; done: string }> = {+ sign_in: { heading: 'Sign in needed', done: 'Done, I’m signed in' },+ captcha: { heading: 'Human check needed', done: 'Done, I solved it' },+ two_factor: { heading: 'Sign-in code needed', done: 'Done, I entered the code' },+ other: { heading: 'Your help is needed', done: 'Done' },+};++/** Only the host of a step's address ("github.com"), so the card never shows paths. */+export function domainOf(url: string | null | undefined): string | null {+ if (!url) return null;+ try {+ const host = new URL(url).hostname.replace(/^www\./, '');+ return host || null;+ } catch {+ return null;+ }+}++const enc = encodeURIComponent;++export const humanStepsApi = {+ listOpen: () => request<HumanStep[]>('GET', '/api/human-steps?status=open'),+ get: (id: string) => request<{ step: HumanStep; waiting: boolean }>('GET', `/api/human-steps/${enc(id)}`),+ done: (id: string) => request<{ step: HumanStep; resumed: 'turn' | 'new_turn' }>('POST', `/api/human-steps/${enc(id)}/done`),+ decline: (id: string) => request<{ step: HumanStep; resumed: 'turn' | 'new_turn' }>('POST', `/api/human-steps/${enc(id)}/decline`),+};diff --git a/frontend/tests/activity.test.mjs b/frontend/tests/activity.test.mjsnew file mode 100644index 00000000..3d6eed93--- /dev/null+++ b/frontend/tests/activity.test.mjs@@ -0,0 +1,100 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++const a = await loadBundled(`export * from './src/activity';`);+const ui = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { LiveActivityList, SavedActivityList } from './src/components/ActivityList';+ export const live = (props) => renderToStaticMarkup(React.createElement(LiveActivityList, props));+ export const saved = (props) => renderToStaticMarkup(React.createElement(SavedActivityList, props));+`);++const step = (over = {}) => ({ id: 's1', kind: 'tool', status: 'running', title: 'Running `cargo test`', started_at: '2026-10-22T10:00:00Z', ...over });++test('steps parse; unknown kinds draw as notes; junk is dropped', () => {+ assert.equal(a.parseStep(step()).kind, 'tool');+ assert.equal(a.parseStep(step({ kind: 'mystery', status: 'odd' })).kind, 'note');+ assert.equal(a.parseStep(step({ status: 'odd' })).status, 'ok');+ assert.equal(a.parseStep({ id: 1, title: 'x' }), null);+ assert.equal(a.parseStep(null), null);+});++test('meta.activity parses from a string or object', () => {+ const meta = { activity: { steps: [step({ status: 'ok' }), { bad: true }], dropped: 3 } };+ const got = a.parseActivityMeta(JSON.stringify(meta));+ assert.equal(got.steps.length, 1);+ assert.equal(got.dropped, 3);+ assert.equal(a.parseActivityMeta({ kind: 'ask_user' }), null);+ assert.equal(a.parseActivityMeta({ activity: { steps: [] } }), null);+ assert.equal(a.parseActivityMeta('nope'), null);+});++test('applyActivity replaces by id, appends new ones, never reopens a settled step, resets per turn', () => {+ let l = a.applyActivity(undefined, 't1', step());+ l = a.applyActivity(l, 't1', step({ id: 's2', title: 'Reading' }));+ assert.equal(l.steps.length, 2);+ l = a.applyActivity(l, 't1', step({ status: 'ok', duration_ms: 1200 }));+ assert.equal(l.steps[0].status, 'ok');+ assert.equal(a.applyActivity(l, 't1', step()).steps[0].status, 'ok', 'late running event loses');+ assert.equal(a.applyActivity(l, 't2', step({ id: 'x' })).steps.length, 1);+});++test('thinking chunks go to the running thinking step only', () => {+ let l = a.applyActivity(undefined, 't1', step({ id: 'th', kind: 'thinking', title: 'Thinking' }));+ l = a.appendThinking(l, 't1', 'First, ');+ l = a.appendThinking(l, 't1', 'check the tests.');+ assert.equal(l.thinking.th, 'First, check the tests.');+ assert.equal(a.appendThinking(l, 't2', 'x'), null, 'other turn');+ const done = a.applyActivity(l, 't1', step({ id: 'th', kind: 'thinking', status: 'done', text: 'Saved text' }));+ assert.equal(a.appendThinking(done, 't1', '⏹️ Cancelled by user'), null, 'a status line is not thinking');+ assert.equal(a.thinkingText(done.steps[0], done), 'Saved text');+ assert.equal(a.thinkingText(l.steps[0], l), 'First, check the tests.');+});++test('durations and the summary line', () => {+ assert.equal(a.formatDuration(840), '840 ms');+ assert.equal(a.formatDuration(8400), '8.4s');+ assert.equal(a.formatDuration(41000), '41s');+ assert.equal(a.formatDuration(125000), '2m 05s');+ const steps = [+ step({ id: 'a', status: 'ok', started_at: '2026-10-22T10:00:00Z', ended_at: '2026-10-22T10:00:10Z' }),+ step({ id: 'b', status: 'failed', started_at: '2026-10-22T10:00:10Z', ended_at: '2026-10-22T10:00:41Z' }),+ step({ id: 'n', kind: 'note', status: 'ok', title: 'This engine doesn’t share its thinking.' }),+ ];+ assert.equal(a.activitySummary({ steps, dropped: 10 }), '12 steps · 41s · 1 failed');+ assert.equal(a.activitySummary({ steps: [steps[0]], dropped: 0 }), '1 step · 10s');+ assert.equal(a.plainTitle('Running `ls`'), 'Running ls');+ assert.equal(a.statusLabel(step({ kind: 'approval', status: 'declined' })), 'Denied');+});++test('live list: steps, mono command, waits announced, reduced motion', () => {+ const l = {+ turnId: 't1',+ thinking: { th: 'Looking at the failing test' },+ steps: [+ step({ id: 'th', kind: 'thinking', title: 'Thinking' }),+ step({ id: 'ap', kind: 'approval', status: 'waiting', title: 'Approve `rm -rf build`' }),+ ],+ };+ const html = ui.live({ live: l, idBase: 'x' });+ assert.match(html, /Thinking…/);+ assert.match(html, /Looking at the failing test/, 'running thought is open, not cut to one line');+ assert.match(html, /<code[^>]*>rm -rf build<\/code>/);+ assert.match(html, /role="status"[^>]*>Approve rm -rf build</);+ assert.match(html, /motion-reduce:animate-none/);+ assert.match(html, /aria-label="Waiting for you"/);+ assert.equal(ui.live({ live: { turnId: 't', steps: [], thinking: {} }, idBase: 'x' }), '');+});++test('saved list starts collapsed to the summary; the engine note stays visible', () => {+ const activity = { steps: [step({ status: 'ok', duration_ms: 900 }), step({ id: 'n', kind: 'note', status: 'ok', title: 'This engine doesn’t share its thinking.' })], dropped: 0 };+ const html = ui.saved({ activity, idBase: 'm1' });+ assert.match(html, /aria-expanded="false"/);+ assert.match(html, /1 step/);+ assert.match(html, /doesn’t share its thinking/);+ assert.doesNotMatch(html, /cargo test/, 'steps hidden until opened');+ assert.equal(a.hasThinkingText(activity), false);+ assert.equal(a.hasThinkingText({ steps: [step({ kind: 'thinking', status: 'done', text: 'hm' })], dropped: 0 }), true);+});diff --git a/frontend/tests/humanSteps.test.mjs b/frontend/tests/humanSteps.test.mjsnew file mode 100644index 00000000..7fef0870--- /dev/null+++ b/frontend/tests/humanSteps.test.mjs@@ -0,0 +1,79 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++const h = await loadBundled(`export * from './src/humanSteps';`);+const ui = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { HumanStepCard } from './src/components/HumanStepCard';+ export const render = (props) => renderToStaticMarkup(React.createElement(HumanStepCard, props));+`);++const meta = (over = {}) => ({+ kind: 'human_step', human_step_id: 'hs1', step_kind: 'sign_in', reason: 'Log in to GitHub so I can open the PR.',+ url: 'https://www.github.com/login?return_to=/secret/path', sandbox_target: 'vm', source: 'bot', status: 'open', ...over,+});+const rec = (over = {}) => ({+ id: 'hs1', kwant_id: 'pixel', channel_id: null, direct_kwant_id: 'pixel', thread_id: null, turn_id: 't1', kind: 'sign_in',+ reason: 'r', url: null, sandbox_target: null, source: 'bot', status: 'open', message_id: 'm1', created_at: '2026-10-22T10:00:00Z', closed_at: null, ...over,+});+const props = (over = {}) => ({ meta: h.parseHumanStepMeta(meta()), messageId: 'm1', kwantName: 'Pixel', waiting: true, onOpenBrowser: () => {}, onDone: async () => {}, onSkip: async () => {}, ...over });++test('meta parses, defaults odd values, ignores other kinds', () => {+ assert.equal(h.parseHumanStepMeta(JSON.stringify(meta())).step_kind, 'sign_in');+ assert.equal(h.parseHumanStepMeta(meta({ step_kind: 'weird', status: 'x' })).step_kind, 'other');+ assert.equal(h.parseHumanStepMeta(meta({ status: 'x' })).status, 'open');+ assert.equal(h.parseHumanStepMeta({ kind: 'ask_user' }), null);+ assert.equal(h.parseHumanStepMeta('nope'), null);+});++test('only the domain of the address is shown', () => {+ assert.equal(h.domainOf('https://www.github.com/login?x=1'), 'github.com');+ assert.equal(h.domainOf('not a url'), null);+ assert.equal(h.domainOf(null), null);+});++test('records: newest state, closed never reopens; badges and waits', () => {+ let map = h.applyHumanStep({}, rec());+ map = h.applyHumanStep(map, rec({ id: 'hs2', kwant_id: 'pixel', turn_id: 't2', created_at: '2026-10-22T11:00:00Z' }));+ assert.deepEqual(h.openStepsByKwant(map), { pixel: 2 });+ assert.equal(h.latestOpenStep(map, 'pixel').id, 'hs2');+ assert.deepEqual([...h.turnsAwaitingStep(map)].sort(), ['t1', 't2']);+ map = h.applyHumanStep(map, rec({ status: 'done' }));+ assert.equal(h.applyHumanStep(map, rec()).hs1.status, 'done');+ assert.deepEqual(h.openStepsByKwant(map), { pixel: 1 });+ assert.equal(h.latestOpenStep(map, 'other'), null);+ assert.equal(h.humanStepView(h.parseHumanStepMeta(meta()), rec({ status: 'declined' })).status, 'declined');+});++test('the Done label fits the kind', () => {+ assert.equal(h.KIND_TEXT.sign_in.done, 'Done, I’m signed in');+ assert.equal(h.KIND_TEXT.captcha.done, 'Done, I solved it');+ for (const [kind, t] of Object.entries(h.KIND_TEXT)) {+ const html = ui.render(props({ meta: h.parseHumanStepMeta(meta({ step_kind: kind })) }));+ assert.ok(html.includes(t.heading), kind);+ assert.ok(html.includes(t.done.replace('’', ''')) || html.includes(t.done), kind);+ }+});++test('open card: reason, domain only, three buttons, waiting line', () => {+ const html = ui.render(props());+ assert.match(html, /Pixel<\/span> needs you in the browser/);+ assert.match(html, /Log in to GitHub/);+ assert.match(html, />github\.com</);+ assert.doesNotMatch(html, /secret\/path|return_to/);+ assert.match(html, /Open browser/);+ assert.match(html, />Skip</);+ assert.match(html, /is paused and waiting for you/);+ assert.equal((html.match(/<button/g) || []).length, 3);+});++test('closed and stale cards', () => {+ assert.doesNotMatch(ui.render(props({ live: rec({ status: 'done' }) })), /<button/);+ assert.match(ui.render(props({ live: rec({ status: 'done' }) })), /Done\. Pixel is carrying on/);+ assert.match(ui.render(props({ live: rec({ status: 'declined' }) })), /Skipped/);+ assert.match(ui.render(props({ live: rec({ status: 'cancelled' }) })), /reply was stopped/);+ assert.match(ui.render(props({ waiting: false })), /stopped waiting/);+ assert.match(ui.render(props({ meta: h.parseHumanStepMeta(meta({ source: 'auto' })) })), /spotted automatically/);+});