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.

Isolated agents UI: Run Claude inside the VM, chips, notice cards (#450)

Oleksandr Ivanchenko474ef900da70
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 5780efb4..07743322 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -344,6 +344,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setSettingsFocusRow('spend-stop');
openAppSettings();
};
+ // Isolation notices: App settings at the Computer card, "Run Claude inside the VM" focused.
+ const openComputerSettings = () => {
+ setSettingsFocusRow('claude-isolation');
+ openAppSettings();
+ };
const openConnections = () => openSpaceSettings('connections');
const openClaudeSignIn = () => {
setClaudeSignInFocus(Date.now());
@@ -824,7 +829,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [isNewTeamOpen, setIsNewTeamOpen] = useState(false);
const [isNewChannelOpen, setIsNewChannelOpen] = useState(false);
const [editingTeam, setEditingTeam] = useState<Team | null>(null);
- const [editingTeamFocusWs, setEditingTeamFocusWs] = useState(false);
+ const [editingTeamFocusWs, setEditingTeamFocusWs] = useState<boolean | 'folder'>(false);
useEffect(() => {
if (!editingTeam) setEditingTeamFocusWs(false);
}, [editingTeam]);
@@ -3093,7 +3098,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
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' }
+ ? { position: queuePosition(turns, waiting.turn_id), reason: waiting.reason ?? 'agent_busy', slots: waiting.slots, speaker: kwantName(waiting.kwant_id) ?? live[openCtx] ?? 'The bot' }
: null;
// The bot's conversations, the open thread's controls, and "working on…" elsewhere.
@@ -3748,6 +3753,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
welcome={getStartedCard && messages.length === 0 ? getStartedCard : undefined}
onOpenAccounts={openSettings}
onOpenUsage={openUsageSettings}
+ onOpenComputerSettings={openComputerSettings}
+ onChangeTeamFolder={(teamId) => {
+ const t = teams.find((x) => x.id === teamId);
+ if (!t) return;
+ setEditingTeamFocusWs('folder');
+ setEditingTeam(t);
+ }}
+ onEditBot={(name) => {
+ const k = kwants.find((x) => x.name === name) ?? kwants.find((x) => x.name.toLowerCase() === name.toLowerCase());
+ if (k) openAgentSettings(k, 'profile');
+ }}
canRun={canRun}
titleExtra={
workingBadge || skillsBadge || approvalsBadge ? (
diff --git a/frontend/src/claudeVm.ts b/frontend/src/claudeVm.ts
new file mode 100644
index 00000000..5634a543
--- /dev/null
+++ b/frontend/src/claudeVm.ts
@@ -0,0 +1,257 @@
+// "Run Claude inside the VM" (agents-in-vm, design/ui.md + design/ui-check-446.md): the switch
+// under the VM card, the "Right now" chips and the status line under them.
+// Contract: GET/PUT /api/settings/computer adds `isolate_claude`, `isolate_claude_toggle` and
+// `agents` (src/server/computer.rs, src/sandbox/agent_vm/mod.rs).
+
+export type AgentEngine = 'claude' | 'codex' | 'grok';
+export const AGENT_ENGINES: AgentEngine[] = ['claude', 'codex', 'grok'];
+export const ENGINE_NAMES: Record<AgentEngine, string> = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
+
+export type AgentRunState = 'off' | 'isolated' | 'not_isolated' | 'preparing' | 'unavailable';
+
+export interface AgentVmState {
+ state: AgentRunState;
+ reason: string | null;
+ /** People's words from the server, e.g. why the setup failed. */
+ detail: string | null;
+ /** Only while preparing, and only if the server measures it (0.7.7 doesn't). */
+ progress: { done_bytes: number; total_bytes: number } | null;
+}
+
+export interface ClaudeVm {
+ /** The saved switch, kept in both modes. */
+ on: boolean;
+ /** Can the switch be turned ON right now. */
+ toggle: { available: boolean; reason: string | null };
+ agents: Partial<Record<AgentEngine, AgentVmState>>;
+}
+
+export const SETTING_NAME = 'Run Claude inside the VM';
+
+const STATES: AgentRunState[] = ['off', 'isolated', 'not_isolated', 'preparing', 'unavailable'];
+const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v : null);
+
+function parseAgent(v: unknown): AgentVmState | null {
+ if (!v || typeof v !== 'object') return null;
+ const a = v as Record<string, any>;
+ if (!STATES.includes(a.state)) return null;
+ const p = a.progress;
+ const progress =
+ p && typeof p === 'object' && Number.isFinite(p.done_bytes) && Number.isFinite(p.total_bytes) && p.total_bytes > 0
+ ? { done_bytes: Math.max(0, Math.min(p.done_bytes, p.total_bytes)), total_bytes: p.total_bytes }
+ : null;
+ return { state: a.state, reason: str(a.reason), detail: str(a.detail), progress };
+}
+
+/** The switch's fields from the computer view, or null on a server without them (no row then). */
+export function parseClaudeVm(d: Record<string, any>): ClaudeVm | null {
+ if (typeof d.isolate_claude !== 'boolean') return null;
+ const t = d.isolate_claude_toggle && typeof d.isolate_claude_toggle === 'object' ? d.isolate_claude_toggle : {};
+ const agents: ClaudeVm['agents'] = {};
+ for (const e of AGENT_ENGINES) {
+ const a = parseAgent(d.agents?.[e]);
+ if (a) agents[e] = a;
+ }
+ return { on: d.isolate_claude, toggle: { available: t.available === true, reason: str(t.reason) }, agents };
+}
+
+/** Hosts where the switch never works in this release: the hint is replaced by this line. */
+export const PLATFORM_HINTS: Record<string, string> = {
+ mac_later: 'Coming to Mac later. For now, Claude runs on this computer in both modes.',
+ not_supported_yet: 'Only on Linux for now. Claude runs on this computer in both modes.',
+};
+
+export const ISOLATION_HINT =
+ 'Claude sees only the task folder. Its own tools, web search included, can’t go online, so it browses with kwant’s browser. Your Claude sign-in or key stays on this computer; kwant adds it on the way out.';
+
+/** Whether this host could run Claude in the VM (Linux), whatever Docker is doing. */
+export const hostSupportsIsolation = (vm: ClaudeVm | null | undefined) => !!vm && !(vm.toggle.reason && vm.toggle.reason in PLATFORM_HINTS);
+
+// ---- chips ----
+
+export type ChipTone = 'isolated' | 'neutral' | 'preparing' | 'stopped';
+
+export interface Chip {
+ engine: AgentEngine;
+ name: string;
+ tone: ChipTone;
+ /** The state after the "·". */
+ label: string;
+ /** What a screen reader hears, e.g. "Claude: isolated". */
+ spoken: string;
+ title: string | null;
+ /** Preparing with no measured progress: a spinner instead of the download icon. */
+ indeterminate?: boolean;
+}
+
+const pct = (p: AgentVmState['progress']) => (p ? Math.floor((p.done_bytes / p.total_bytes) * 100) : null);
+
+export function chipFor(engine: AgentEngine, a: AgentVmState | undefined): Chip {
+ const name = ENGINE_NAMES[engine];
+ const chip = (tone: ChipTone, label: string, title: string | null = null, extra: Partial<Chip> = {}): Chip => ({
+ engine,
+ name,
+ tone,
+ label,
+ spoken: `${name}: ${label.toLowerCase()}`,
+ title,
+ ...extra,
+ });
+ const later = `${name} still runs on this computer, with its own file and shell tools. Moving it inside the VM comes later.`;
+ if (engine !== 'claude') return chip('neutral', 'Not isolated yet', later);
+ if (!a) return chip('neutral', 'Not isolated');
+ switch (a.state) {
+ case 'isolated':
+ return chip('isolated', 'Isolated', 'Claude runs inside the VM, in a container of its own with no network.');
+ case 'preparing': {
+ const n = pct(a.progress);
+ return n === null
+ ? chip('preparing', 'Getting ready', 'Getting the VM ready for Claude.', { indeterminate: true })
+ : chip('preparing', `Getting ready · ${n}%`, 'Getting the VM ready for Claude.');
+ }
+ case 'unavailable':
+ return chip('stopped', 'Stopped', "Claude can't reply until this is fixed. Nothing runs on this computer instead.");
+ case 'not_isolated':
+ return chip('neutral', a.reason === 'not_supported_yet' ? 'Not isolated yet' : 'Not isolated', a.detail);
+ default:
+ return chip('neutral', 'Not isolated', a.detail);
+ }
+}
+
+export const chipsFor = (vm: ClaudeVm): Chip[] => AGENT_ENGINES.map((e) => chipFor(e, vm.agents[e]));
+
+// ---- the row ----
+
+export type RowStatus =
+ | { kind: 'preparing'; progress: AgentVmState['progress'] }
+ | { kind: 'stopped'; text: string; action: 'check' | 'retry' | null }
+ | { kind: 'quiet'; text: string }
+ | null;
+
+export interface RowModel {
+ checked: boolean;
+ /** Can't be turned on now. Never set while it's on: the person can always turn it off (fix 9). */
+ disabled: boolean;
+ /** Replaces the hint on a Mac or Windows host. */
+ hint: string;
+ status: RowStatus;
+}
+
+const sentence = (s: string) => s.trim().replace(/[.\s]+$/, '');
+
+/** The amber line for `unavailable`, by reason (states D, E, E2). */
+export function stoppedLine(a: AgentVmState): Extract<RowStatus, { kind: 'stopped' }> {
+ switch (a.reason) {
+ case 'docker_unavailable':
+ return {
+ kind: 'stopped',
+ text: 'Docker isn’t running, so Claude can’t reply. Start Docker, or turn this off to run Claude on this computer.',
+ action: 'check',
+ };
+ case 'download_failed':
+ return {
+ kind: 'stopped',
+ text: `The setup stopped: ${sentence(a.detail ?? 'the setup failed (kwant’s log has the details)')}. Claude can’t reply until it finishes.`,
+ action: 'retry',
+ };
+ case 'download_needed':
+ return { kind: 'stopped', text: 'Claude’s VM isn’t set up yet, so Claude can’t reply. Try again to start the one-time setup.', action: 'retry' };
+ case 'relay_down':
+ return { kind: 'stopped', text: 'kwant couldn’t connect Claude to your sign-in. Restart kwant; if it keeps happening, turn this off.', action: null };
+ case 'sign_in_expired':
+ return { kind: 'stopped', text: 'Your Claude sign-in has expired, so Claude can’t reply. Sign in again in Settings › This space › Accounts.', action: null };
+ default: {
+ const why = a.detail ? sentence(a.detail) : a.reason ? `code ${a.reason}` : null;
+ return {
+ kind: 'stopped',
+ text: `Claude can’t reply right now${why ? ` (${why})` : ''}. Check again, or turn this off to run Claude on this computer.`,
+ action: 'check',
+ };
+ }
+ }
+}
+
+/** Everything the row shows, from the saved setting (or the one being saved) and the live state. */
+export function rowModel(vm: ClaudeVm, pending: boolean | null = null): RowModel {
+ const checked = pending ?? vm.on;
+ const platform = vm.toggle.reason ? PLATFORM_HINTS[vm.toggle.reason] : undefined;
+ // Fix 9: the toggle's `available` ignores the saved setting, so a switch that is on stays usable.
+ const disabled = !vm.on && !vm.toggle.available;
+ const hint = platform ?? ISOLATION_HINT;
+ let status: RowStatus = null;
+ const claude = vm.agents.claude;
+ if (platform) status = null;
+ else if (!vm.on) status = disabled && vm.toggle.reason === 'docker_unavailable' ? { kind: 'quiet', text: 'Start Docker to turn this on.' } : null;
+ else if (claude?.state === 'preparing') status = { kind: 'preparing', progress: claude.progress };
+ else if (claude?.state === 'unavailable') status = stoppedLine(claude);
+ return { checked, disabled, hint, status };
+}
+
+/** How often to re-read the setting: every second while preparing, every 10 s while stopped. */
+export function pollInterval(vm: ClaudeVm | null | undefined): number | null {
+ const states = vm ? Object.values(vm.agents).map((a) => a?.state) : [];
+ if (states.includes('preparing')) return 1000;
+ if (states.includes('unavailable')) return 10_000;
+ return null;
+}
+
+/** The progress block's copy. Without measured progress (0.7.7) it's indeterminate (fix 6). */
+export function preparingCopy(progress: AgentVmState['progress']) {
+ if (!progress)
+ return {
+ line1: 'Getting the VM ready for Claude. This one-time setup downloads about 860 MB and takes a few minutes.',
+ line2: 'Claude can’t reply until it’s done. Turning this off lets Claude reply on this computer meanwhile; the setup keeps going.',
+ figure: null,
+ };
+ const mb = (b: number) => Math.round(b / 1_000_000);
+ return {
+ line1: 'Getting the VM ready for Claude. This one-time download takes a few minutes.',
+ line2: 'Claude can’t reply until it’s done.',
+ figure: `${mb(progress.done_bytes)} of ${mb(progress.total_bytes)} MB`,
+ };
+}
+
+/** One sentence for the live region: only at the start, the end and on a failure, never per tick. */
+export function announcement(prev: AgentVmState | undefined, next: AgentVmState | undefined): string | null {
+ if (!next || prev?.state === next.state) return null;
+ if (next.state === 'preparing') return 'Getting the VM ready for Claude.';
+ if (next.state === 'isolated' && prev) return 'Claude now runs inside the VM.';
+ if (next.state === 'unavailable' && prev) return `Claude stopped. ${stoppedLine(next).text}`;
+ return null;
+}
+
+// ---- saving ----
+
+/** The PUT's 400 codes in people's words; older servers send the bare code as `error` (fix 5). */
+export const PUT_ERRORS: Record<string, string> = {
+ mac_later: PLATFORM_HINTS.mac_later,
+ not_supported_yet: PLATFORM_HINTS.not_supported_yet,
+ docker_unavailable: 'Start Docker to turn this on.',
+};
+
+export function putErrorText(status: number, data: unknown): string {
+ const d = data && typeof data === 'object' ? (data as Record<string, unknown>) : {};
+ const error = str(d.error);
+ const code = str(d.code);
+ // The server's readable `error` first (#446 final: same words as ours); a code alone (older
+ // servers sent the code as `error`) reads in our words; never a bare code.
+ if (error && !/^[a-z_]+$/.test(error)) return error;
+ if (code && PUT_ERRORS[code]) return PUT_ERRORS[code];
+ if (error && PUT_ERRORS[error]) return PUT_ERRORS[error];
+ return `Couldn’t change this (HTTP ${status}).`;
+}
+
+/** Lin's #446 contract: a reply waiting for a free spot inside the VM. */
+export const queuedVmText = (slots?: number): string =>
+ `Waiting for a free spot in the VM.${slots ? ` ${slots === 1 ? '1 reply runs' : `${slots} replies run`} at once there.` : ''} This one starts as soon as one finishes.`;
+
+/**
+ * The open chat's "in line" sentence. Calm on purpose: a reply can wait about five minutes behind
+ * two replies held on approval cards (qa-446 P-5b), so no timeout, no warning tone, no spinner.
+ */
+export const queuedText = (reason: 'agent_busy' | 'server_busy' | 'vm_busy', slots?: number): string =>
+ reason === 'vm_busy'
+ ? queuedVmText(slots)
+ : reason === 'server_busy'
+ ? 'The server is running as many turns as it allows right now; this one starts as soon as a slot frees up.'
+ : 'Waiting for this bot’s other replies to finish.';
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 6d815e87..d0223304 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -1,4 +1,5 @@
import React, { Fragment, useState, useRef, useEffect, useLayoutEffect, useMemo } from 'react';
+import { queuedText } from '../claudeVm';
import type { SwitchEntry } from '../watchLive';
import { emptyTrialReplyLine, trialCardsAfter, trialOf } from '../showOnce';
import { parsePick } from '../engines';
@@ -62,6 +63,8 @@ import { chainBudgetApi, parseBudgetPaused, parseHandoffCapped } from '../chainB
import { parseSpendStopped } from '../spendStop';
import { SpendStoppedNotice } from './SpendStop';
import { isSystemNotice, parseInterruption, retryTargets } from '../interruptions';
+import { parseIsolationFailed, parseRequestLimit } from '../isolationNotice';
+import { IsolationNotice, RequestLimitNotice } from './IsolationNotice';
import { IDEA_MAX, isIdeaCommand } from '../ideas';
import { ideaBlockedLine, ideaLength } from '../ideaShell';
import { JarIcon } from './JarIcon';
@@ -109,7 +112,9 @@ export interface SendOptions {
/** The open chat's turn is waiting for a free slot. */
export interface QueuedState {
position: number | null;
- reason: 'agent_busy' | 'server_busy';
+ reason: 'agent_busy' | 'server_busy' | 'vm_busy';
+ /** vm_busy only: how many replies run inside the VM at once. */
+ slots?: number;
speaker: string;
}
@@ -277,6 +282,12 @@ export interface ChatViewProps {
onOpenAccounts?: () => void;
/** Opens Settings › All spaces › Usage at the daily spending stop. */
onOpenUsage?: () => void;
+ /** Opens App settings at the Computer card, "Run Claude inside the VM" focused (isolation notices). */
+ onOpenComputerSettings?: () => void;
+ /** Opens Manage Team with its folder input focused (isolation notices 6 and 7). */
+ onChangeTeamFolder?: (teamId: string) => void;
+ /** Opens the named bot's Edit modal on Profile, where its AI is picked (notice 7). */
+ onEditBot?: (botName: string) => void;
/** Whether anything can run a bot in this space now (null while unknown). */
canRun?: boolean | null;
/** The open chat's turn is paused on a question: it is waiting for the person, not working. */
@@ -479,6 +490,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
onSendToOtherBot,
onOpenAccounts,
onOpenUsage,
+ onOpenComputerSettings,
+ onChangeTeamFolder,
+ onEditBot,
canRun = null,
awaitingAnswer,
awaitingBrowser,
@@ -1122,6 +1136,38 @@ export const ChatView: React.FC<ChatViewProps> = ({
flash={flashId === msg.id}
/>
);
+ const isolation = parseIsolationFailed(msg);
+ if (isolation)
+ return (
+ <IsolationNotice
+ key={msg.id}
+ messageId={msg.id}
+ meta={isolation}
+ text={msg.text}
+ retry={canRun === false ? null : retries.get(msg.id)}
+ onRetry={retrySend}
+ onOpenComputerSettings={onOpenComputerSettings}
+ onOpenAccounts={onOpenAccounts}
+ onChangeTeamFolder={onChangeTeamFolder}
+ onEditBot={onEditBot}
+ flash={flashId === msg.id}
+ />
+ );
+ const requestLimit = parseRequestLimit(msg);
+ if (requestLimit)
+ return (
+ <RequestLimitNotice
+ key={msg.id}
+ messageId={msg.id}
+ meta={requestLimit}
+ canContinue={canRun !== false && retries.has(msg.id)}
+ onSend={async (text) => {
+ stickRef.current = true;
+ if ((await onSendMessage(text, [])) === false) throw new Error('not sent');
+ }}
+ flash={flashId === msg.id}
+ />
+ );
const meta = msg.meta && renderDelegation ? parseDelegationMeta(msg.meta) : null;
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;
@@ -1718,9 +1764,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
: streamingSpeakerName || title}
</span>
{queued ? (
- <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" />
- Queued
+ <span className="inline-flex items-center gap-1 text-zinc-400 text-[10px]">
+ <span className="w-1.5 h-1.5 rounded-full bg-zinc-500" aria-hidden="true" />
+ In line
</span>
) : (awaitingAnswer || bubble === 'approval') && !phone ? (
<span className="inline-flex items-center gap-1 text-amber-300 text-[10px]">
@@ -1751,10 +1797,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
<div className="p-4 sm:p-5 min-h-[3.5rem] rounded-2xl rounded-tl-sm bg-zinc-900/60 text-zinc-200 border border-zinc-800/80 text-sm leading-relaxed shadow-sm w-full">
{queued ? (
<p className="text-zinc-300" role="status">
- {queued.position ? <strong className="text-amber-200">#{queued.position} in line.</strong> : <strong className="text-amber-200">In line.</strong>}{' '}
- {queued.reason === 'server_busy'
- ? 'The server is running as many turns as it allows right now; this one starts as soon as a slot frees up.'
- : `${queued.speaker} is busy with other work; this starts as soon as one of those finishes.`}
+ {queued.position ? <strong className="font-medium text-zinc-100">#{queued.position} in line.</strong> : <strong className="font-medium text-zinc-100">In line.</strong>}{' '}
+ {queuedText(queued.reason, queued.slots)}
</p>
) : streamingText ? (
<MarkdownRenderer content={hideStreamingDecisions(stripDiscussionMarkers(streamingText))} isStreaming={true} />
diff --git a/frontend/src/components/ClaudeIsolationRow.tsx b/frontend/src/components/ClaudeIsolationRow.tsx
new file mode 100644
index 00000000..347eda56
--- /dev/null
+++ b/frontend/src/components/ClaudeIsolationRow.tsx
@@ -0,0 +1,217 @@
+import React, { useEffect, useRef, useState } from 'react';
+import { AlertTriangle, Download, Loader2, RefreshCw, RotateCcw, Shield, ShieldCheck } from 'lucide-react';
+import { AgentVmState, Chip, ChipTone, announcement, chipsFor, preparingCopy, rowModel } from '../claudeVm';
+import { ComputerModeApi, ComputerModeError } from './ComputerModeSwitch';
+
+const TONE: Record<ChipTone, string> = {
+ isolated: 'border-teal-300/30 bg-teal-300/[.08] text-ok',
+ neutral: 'border-zinc-800 bg-zinc-950/60 text-zinc-400',
+ preparing: 'border-sky-500/35 bg-sky-500/10 text-sky-300',
+ stopped: 'border-amber-500/35 bg-amber-500/10 text-warn',
+};
+
+const ChipIcon: React.FC<{ chip: Chip }> = ({ chip }) => {
+ if (chip.tone === 'isolated') return <ShieldCheck size={12} aria-hidden="true" />;
+ if (chip.tone === 'stopped') return <AlertTriangle size={12} aria-hidden="true" />;
+ if (chip.tone === 'preparing')
+ return chip.indeterminate ? (
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : (
+ <Download size={12} aria-hidden="true" />
+ );
+ return null;
+};
+
+/** One "Right now" chip: where an AI runs at this moment (never the setting itself). */
+export const AgentChip: React.FC<{ chip: Chip }> = ({ chip }) => (
+ <li
+ data-agent-chip={chip.engine}
+ data-tone={chip.tone}
+ title={chip.title ?? undefined}
+ className={`inline-flex items-center gap-[5px] h-6 px-2 rounded-md border text-[11px] whitespace-nowrap transition-opacity duration-150 motion-reduce:transition-none ${TONE[chip.tone]}`}
+ >
+ <ChipIcon chip={chip} />
+ <span className="sr-only">{chip.spoken}</span>
+ <span aria-hidden="true" className="font-medium text-zinc-200">
+ {chip.name}
+ </span>
+ <span aria-hidden="true" className="text-zinc-600">
+ ·
+ </span>
+ <span aria-hidden="true">{chip.label}</span>
+ </li>
+);
+
+const PreparingBlock: React.FC<{ progress: AgentVmState['progress'] }> = ({ progress }) => {
+ const copy = preparingCopy(progress);
+ return (
+ <div data-claude-iso-status="preparing" className="mt-2.5 ml-[23px] text-[11px] leading-[1.45]">
+ <div className="flex items-baseline gap-3">
+ <p className="flex-1 text-zinc-300">{copy.line1}</p>
+ {copy.figure && <span className="shrink-0 tabular-nums text-zinc-400">{copy.figure}</span>}
+ </div>
+ {progress ? (
+ <div
+ role="progressbar"
+ aria-label="Getting the VM ready for Claude"
+ aria-valuemin={0}
+ aria-valuemax={progress.total_bytes}
+ aria-valuenow={progress.done_bytes}
+ aria-valuetext={copy.figure ?? undefined}
+ className="mt-1.5 h-1 rounded-full bg-zinc-800 overflow-hidden"
+ >
+ <div
+ className="h-full w-full origin-left bg-sky-500 transition-transform duration-200 ease-linear motion-reduce:transition-none"
+ style={{ transform: `scaleX(${progress.done_bytes / progress.total_bytes})` }}
+ />
+ </div>
+ ) : null}
+ <p className="mt-1.5 text-zinc-500">{copy.line2}</p>
+ </div>
+ );
+};
+
+/**
+ * "Run Claude inside the VM" (design/ui.md): one switch under the VM card, the "Right now" chips
+ * and, when something needs the person, one status line. VM mode only; nothing until loaded.
+ */
+export const ClaudeIsolationRow: React.FC<{ api: ComputerModeApi }> = ({ api }) => {
+ const settings = api.state.settings;
+ const vm = settings?.claudeVm ?? null;
+ const claude = vm?.agents.claude;
+
+ // The live region speaks at the start, the end and on a failure; never per progress tick.
+ const prev = useRef<AgentVmState | undefined>(claude);
+ const [said, setSaid] = useState('');
+ useEffect(() => {
+ const text = announcement(prev.current, claude);
+ prev.current = claude;
+ if (text) setSaid(text);
+ }, [claude?.state, claude?.reason]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const [checking, setChecking] = useState(false);
+ if (!settings || !vm || settings.mode !== 'vm') return null;
+
+ const pending = api.isoPending ?? null;
+ const model = rowModel(vm, pending);
+ const busy = pending !== null;
+ const chips = chipsFor(vm);
+ const describedBy = ['claude-iso-hint', model.status ? 'claude-iso-status' : null].filter(Boolean).join(' ');
+ const toggle = () => {
+ if (model.disabled || busy) return;
+ api.setIsolateClaude?.(!vm.on);
+ };
+ const check = async () => {
+ if (checking) return;
+ setChecking(true);
+ try {
+ await api.refresh?.();
+ } finally {
+ setChecking(false);
+ }
+ };
+ const status = model.status;
+
+ return (
+ <div data-claude-iso className="p-3 rounded-xl border border-zinc-800 bg-zinc-950/60">
+ <div className="flex items-start gap-3">
+ <div className="flex-1 min-w-0">
+ <p id="claude-iso-label" className={`flex items-center gap-2 text-xs font-medium ${model.disabled ? 'text-zinc-500' : 'text-zinc-200'}`}>
+ <Shield size={15} className={model.disabled ? 'text-zinc-600' : 'text-sky-400'} aria-hidden="true" />
+ Run Claude inside the VM
+ </p>
+ <p id="claude-iso-hint" className="mt-1 pl-[23px] text-[11px] leading-[1.45] text-zinc-500">
+ {model.hint}
+ </p>
+ </div>
+ <button
+ type="button"
+ role="switch"
+ data-switch="claude-isolation"
+ aria-checked={model.checked}
+ aria-labelledby="claude-iso-label"
+ aria-describedby={describedBy}
+ aria-disabled={model.disabled || undefined}
+ aria-busy={busy || undefined}
+ onClick={toggle}
+ className={`group shrink-0 -m-3 p-3 rounded-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 ${
+ model.disabled ? 'cursor-not-allowed' : busy ? 'cursor-progress' : ''
+ }`}
+ >
+ <span
+ className={`relative block w-9 h-5 rounded-full transition-colors motion-reduce:transition-none ${
+ model.disabled ? (model.checked ? 'bg-sky-600/35' : 'bg-zinc-800') : model.checked ? 'bg-sky-600' : 'bg-zinc-700'
+ }`}
+ >
+ <span
+ className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full transition-transform duration-150 motion-reduce:transition-none ${
+ model.disabled ? 'bg-zinc-600' : 'bg-white'
+ } ${model.checked ? 'translate-x-4' : ''}`}
+ />
+ </span>
+ {busy && <span className="sr-only">(saving)</span>}
+ </button>
+ </div>
+
+ <div className={`mt-2.5 pl-[23px] flex flex-wrap items-center gap-1.5 ${busy ? 'opacity-60' : ''}`}>
+ <span className="basis-full sm:basis-auto text-[11px] text-zinc-500" aria-hidden="true">
+ Right now
+ </span>
+ <ul aria-label="Where each AI runs right now" className="contents">
+ {chips.map((c) => (
+ <AgentChip key={c.engine} chip={c} />
+ ))}
+ </ul>
+ </div>
+ <span className="sr-only" aria-live="polite" data-claude-iso-live>
+ {said}
+ </span>
+
+ {status?.kind === 'preparing' && (
+ <div id="claude-iso-status" role="status">
+ <PreparingBlock progress={status.progress} />
+ </div>
+ )}
+ {status?.kind === 'quiet' && (
+ <p id="claude-iso-status" data-claude-iso-status="quiet" className="mt-2.5 ml-[23px] text-[11px] text-zinc-500">
+ {status.text}
+ </p>
+ )}
+ {status?.kind === 'stopped' && (
+ <div
+ data-claude-iso-status="stopped"
+ className="mt-2.5 ml-[23px] flex flex-col sm:flex-row sm:items-center gap-2 px-2.5 py-2 rounded-lg border border-amber-500/30 bg-amber-950/20"
+ >
+ <p id="claude-iso-status" className="flex items-start gap-1.5 flex-1 min-w-0 text-[11px] leading-[1.45] text-amber-200">
+ <AlertTriangle size={13} className="mt-px shrink-0 text-amber-400" aria-hidden="true" />
+ <span className="min-w-0 [overflow-wrap:anywhere]">{status.text}</span>
+ </p>
+ {status.action && (
+ <button
+ type="button"
+ data-claude-iso-action={status.action}
+ onClick={status.action === 'check' ? check : () => api.setIsolateClaude?.(true)}
+ disabled={checking || busy}
+ aria-busy={checking || busy || undefined}
+ className="shrink-0 ml-[19px] sm:ml-0 inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[32px] px-3 rounded-lg text-[11px] font-medium border text-amber-100 bg-amber-500/15 border-amber-500/40 hover:bg-amber-500/25 disabled:opacity-70 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400"
+ >
+ {checking || (busy && status.action === 'retry') ? (
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : status.action === 'check' ? (
+ <RefreshCw size={12} aria-hidden="true" />
+ ) : (
+ <RotateCcw size={12} aria-hidden="true" />
+ )}
+ {status.action === 'check' ? 'Check again' : 'Try again'}
+ </button>
+ )}
+ </div>
+ )}
+ {api.isoError && api.isoError !== model.hint && !(status?.kind === 'quiet' && status.text === api.isoError) && (
+ <div className="mt-2.5 ml-[23px]">
+ <ComputerModeError error={api.isoError} onDismiss={api.dismissIsoError} />
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/ComputerModeSwitch.tsx b/frontend/src/components/ComputerModeSwitch.tsx
index 8ba28399..34b315e2 100644
--- a/frontend/src/components/ComputerModeSwitch.tsx
+++ b/frontend/src/components/ComputerModeSwitch.tsx
@@ -13,12 +13,14 @@ import {
modeLabel,
otherMode,
saveComputerMode,
+ saveIsolateClaude,
saveLocalWindow,
showsLocalWindow,
shownMode,
switchReducer,
unavailableReason,
} from '../computerMode';
+import { pollInterval } from '../claudeVm';
export interface ComputerModeApi {
state: SwitchState;
@@ -29,6 +31,14 @@ export interface ComputerModeApi {
setWindow: (visible: boolean) => void;
/** True while a window switch restarts Chrome. */
windowPending: boolean;
+ /** "Run Claude inside the VM": saves at once; on failure the switch goes back and `isoError` says why. */
+ setIsolateClaude?: (on: boolean) => void;
+ /** The value being saved, shown until the server answers. */
+ isoPending?: boolean | null;
+ isoError?: string | null;
+ dismissIsoError?: () => void;
+ /** Reads the setting again ("Check again"). */
+ refresh?: () => Promise<void>;
}
/** Loads the setting while `enabled`, and follows switches made elsewhere in this tab. */
@@ -94,8 +104,44 @@ export function useComputerMode(enabled: boolean): ComputerModeApi {
return () => window.clearInterval(timer);
}, [windowOpen]);
+ const refresh = useCallback(async () => {
+ const s = await fetchComputerSettings().catch(() => null);
+ if (s) dispatch({ type: 'loaded', settings: s });
+ }, []);
+
+ const [isoPending, setIsoPending] = useState<boolean | null>(null);
+ const [isoError, setIsoError] = useState<string | null>(null);
+ const isoLock = useRef(false);
+ const setIsolateClaude = useCallback((on: boolean) => {
+ if (isoLock.current || !stateRef.current.settings?.claudeVm) return;
+ isoLock.current = true;
+ playSfx('click');
+ setIsoPending(on);
+ setIsoError(null);
+ saveIsolateClaude(on).then((r) => {
+ isoLock.current = false;
+ setIsoPending(null);
+ if (r.ok) {
+ dispatch({ type: 'saved', settings: r.settings });
+ window.dispatchEvent(new CustomEvent(COMPUTER_MODE_EVENT, { detail: r.settings }));
+ } else {
+ setIsoError(r.error);
+ }
+ });
+ }, []);
+ const dismissIsoError = useCallback(() => setIsoError(null), []);
+
+ // Every second while Claude's VM gets ready, every 10 s while it's stopped, so the chip clears
+ // after someone starts Docker even if they never press Check again.
+ const every = enabled ? pollInterval(state.settings?.claudeVm) : null;
+ useEffect(() => {
+ if (!every) return;
+ const timer = window.setInterval(() => void refresh(), every);
+ return () => window.clearInterval(timer);
+ }, [every, refresh]);
+
const dismissError = useCallback(() => dispatch({ type: 'dismiss' }), []);
- return { state, select, dismissError, setWindow, windowPending };
+ return { state, select, dismissError, setWindow, windowPending, setIsolateClaude, isoPending, isoError, dismissIsoError, refresh };
}
const ICONS: Record<ComputerMode, typeof Laptop> = { local: Laptop, vm: Box };
diff --git a/frontend/src/components/IsolationNotice.tsx b/frontend/src/components/IsolationNotice.tsx
new file mode 100644
index 00000000..e9082961
--- /dev/null
+++ b/frontend/src/components/IsolationNotice.tsx
@@ -0,0 +1,231 @@
+import React, { useRef, useState } from 'react';
+import { Check, FolderOpen, KeyRound, Loader2, Monitor, PauseCircle, Pencil, Play, RotateCcw, ShieldAlert } from 'lucide-react';
+import { RetryState, RetryTarget, runRetryOnce } from '../interruptions';
+import {
+ CONTINUE_TEXT,
+ IsolationFailedMeta,
+ NoticeAction,
+ RequestLimitMeta,
+ SAFETY,
+ SafetyKind,
+ isolationCard,
+ requestLimitText,
+} from '../isolationNotice';
+
+const BOX = 'w-full max-w-5xl rounded-xl border border-amber-500/30 bg-amber-950/20 px-3.5 py-2.5 sm:px-4';
+const BTN =
+ 'shrink-0 inline-flex items-center justify-center gap-1.5 min-h-[44px] sm:min-h-[36px] px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors cursor-pointer disabled:cursor-default disabled:opacity-70 focus-visible:outline focus-visible:outline-2';
+const PRIMARY = `${BTN} text-amber-100 bg-amber-500/15 border-amber-500/40 hover:bg-amber-500/25 disabled:hover:bg-amber-500/15 focus-visible:outline-amber-400`;
+const SECONDARY = `${BTN} text-zinc-200 border-zinc-700 hover:bg-zinc-800/70 focus-visible:outline-sky-500`;
+
+const SafetyLine: React.FC<{ kind: SafetyKind }> = ({ kind }) => {
+ if (!kind) return null;
+ const [a, name, b] = SAFETY[kind];
+ return (
+ <p data-isolation-safety={kind} className="mt-1.5 text-xs leading-[1.5] text-zinc-400">
+ {a}
+ {name && <span className="font-medium text-zinc-300">{name}</span>}
+ {b}
+ </p>
+ );
+};
+
+export interface IsolationNoticeProps {
+ messageId: string;
+ meta: IsolationFailedMeta;
+ /** The saved text: for a code with no row, the server's own words come from here. */
+ text?: string | null;
+ /** Only on the newest notice the person hasn't written past (`retryTargets`). */
+ retry?: RetryTarget | null;
+ onRetry?: (target: RetryTarget) => void | Promise<unknown>;
+ onOpenComputerSettings?: () => void;
+ onOpenAccounts?: () => void;
+ onChangeTeamFolder?: (teamId: string) => void;
+ onEditBot?: (botName: string) => void;
+ flash?: boolean;
+}
+
+/** Isolation stopped a reply (fail closed): why, what's safe, and the one or two ways on. */
+export const IsolationNotice: React.FC<IsolationNoticeProps> = ({
+ messageId,
+ meta,
+ text,
+ retry,
+ onRetry,
+ onOpenComputerSettings,
+ onOpenAccounts,
+ onChangeTeamFolder,
+ onEditBot,
+ flash,
+}) => {
+ const card = isolationCard(meta, text);
+ const [state, setState] = useState<RetryState>('idle');
+ const lock = useRef<RetryState>('idle');
+ const headingId = `iso-${messageId}`;
+ const reasonId = `iso-r-${messageId}`;
+
+ const button = (a: NoticeAction, primary: boolean) => {
+ const cls = primary ? PRIMARY : SECONDARY;
+ switch (a) {
+ case 'retry':
+ if (!retry || !onRetry) return null;
+ return (
+ <button
+ key={a}
+ type="button"
+ data-isolation-action="retry"
+ onClick={() => void runRetryOnce(lock, retry, onRetry, setState)}
+ disabled={state !== 'idle'}
+ aria-describedby={headingId}
+ className={cls}
+ >
+ {state === 'sending' ? (
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : state === 'sent' ? (
+ <Check size={13} aria-hidden="true" />
+ ) : (
+ <RotateCcw size={13} aria-hidden="true" />
+ )}
+ <span>{state === 'sending' ? 'Sending…' : state === 'sent' ? 'Sent again' : 'Retry'}</span>
+ </button>
+ );
+ case 'computer':
+ if (!onOpenComputerSettings) return null;
+ return (
+ <button key={a} type="button" data-isolation-action="computer" onClick={onOpenComputerSettings} className={cls}>
+ <Monitor size={13} aria-hidden="true" />
+ <span>Computer settings</span>
+ </button>
+ );
+ case 'accounts':
+ if (!onOpenAccounts) return null;
+ return (
+ <button key={a} type="button" data-isolation-action="accounts" onClick={onOpenAccounts} className={cls}>
+ <KeyRound size={13} aria-hidden="true" />
+ <span>Accounts</span>
+ </button>
+ );
+ case 'change_folder':
+ if (!onChangeTeamFolder || !meta.teamId) return null;
+ return (
+ <button key={a} type="button" data-isolation-action="change_folder" onClick={() => onChangeTeamFolder(meta.teamId!)} className={cls}>
+ <FolderOpen size={13} aria-hidden="true" />
+ <span>Change folder</span>
+ </button>
+ );
+ case 'edit_bot':
+ if (!onEditBot) return null;
+ return (
+ <button key={a} type="button" data-isolation-action="edit_bot" onClick={() => onEditBot(meta.botName)} className={cls}>
+ <Pencil size={13} aria-hidden="true" />
+ <span>Edit {meta.botName}</span>
+ </button>
+ );
+ }
+ };
+
+ // The first button that can show is primary, so Retry leads when there's no Change folder.
+ let primaryTaken = false;
+ const buttons = card.actions
+ .map((a) => {
+ const canShow =
+ a === 'retry'
+ ? !!retry && !!onRetry
+ : a === 'computer'
+ ? !!onOpenComputerSettings
+ : a === 'accounts'
+ ? !!onOpenAccounts
+ : a === 'change_folder'
+ ? !!onChangeTeamFolder && !!meta.teamId
+ : !!onEditBot;
+ if (!canShow) return null;
+ const el = button(a, !primaryTaken);
+ primaryTaken = true;
+ return el;
+ })
+ .filter(Boolean);
+
+ return (
+ <section
+ data-message-id={messageId}
+ data-isolation-notice={card.row}
+ aria-labelledby={headingId}
+ aria-describedby={reasonId}
+ className={`${BOX} ${flash ? 'kw-flash' : ''}`}
+ >
+ <div className="flex items-start gap-2">
+ <ShieldAlert size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p id={headingId} className="text-sm font-semibold text-amber-100 break-words">
+ {card.first}
+ </p>
+ <p id={reasonId} className="mt-0.5 text-sm leading-[1.5] text-amber-200 break-words">
+ {card.reason.map((s, i) =>
+ s.folder ? (
+ <span key={i} data-isolation-folder className="font-mono text-[13px] text-amber-100 [overflow-wrap:anywhere]">
+ {s.text}
+ </span>
+ ) : (
+ <React.Fragment key={i}>{s.text}</React.Fragment>
+ ),
+ )}
+ </p>
+ <SafetyLine kind={card.safety} />
+ {buttons.length > 0 && <div className="mt-2.5 flex flex-wrap gap-2">{buttons}</div>}
+ </div>
+ </div>
+ </section>
+ );
+};
+
+export interface RequestLimitNoticeProps {
+ messageId: string;
+ meta: RequestLimitMeta;
+ /** Only on the newest notice the person hasn't written past; without it there's no Continue. */
+ canContinue?: boolean;
+ onSend?: (text: string) => void | Promise<unknown>;
+ flash?: boolean;
+}
+
+/** Notice 5: a reply paused at its request limit; Continue starts a new reply with a fresh limit. */
+export const RequestLimitNotice: React.FC<RequestLimitNoticeProps> = ({ messageId, meta, canContinue, onSend, flash }) => {
+ const copy = requestLimitText(meta);
+ const [state, setState] = useState<RetryState>('idle');
+ const lock = useRef<RetryState>('idle');
+ const headingId = `limit-${messageId}`;
+ const show = !!canContinue && !!onSend;
+ return (
+ <section data-message-id={messageId} data-request-limit aria-labelledby={headingId} className={`${BOX} ${flash ? 'kw-flash' : ''}`}>
+ <div className="flex items-start gap-2">
+ <PauseCircle size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p id={headingId} className="text-sm font-semibold text-amber-100 break-words">
+ {copy.first}
+ </p>
+ <p className="mt-0.5 text-sm leading-[1.5] text-amber-200 break-words">{copy.body}</p>
+ {show && (
+ <div className="mt-2.5 flex flex-wrap gap-2">
+ <button
+ type="button"
+ data-request-limit-action="continue"
+ onClick={() => void runRetryOnce(lock, { text: CONTINUE_TEXT, attachments: [] }, (t) => onSend!(t.text), setState)}
+ disabled={state !== 'idle'}
+ aria-describedby={headingId}
+ className={PRIMARY}
+ >
+ {state === 'sending' ? (
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : state === 'sent' ? (
+ <Check size={13} aria-hidden="true" />
+ ) : (
+ <Play size={13} aria-hidden="true" />
+ )}
+ <span>{state === 'sending' ? 'Sending…' : state === 'sent' ? 'Sent' : 'Continue'}</span>
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ </section>
+ );
+};
diff --git a/frontend/src/components/ManageTeamModal.tsx b/frontend/src/components/ManageTeamModal.tsx
index 81cfce42..19f420a1 100644
--- a/frontend/src/components/ManageTeamModal.tsx
+++ b/frontend/src/components/ManageTeamModal.tsx
@@ -29,8 +29,10 @@ interface ManageTeamModalProps {
}
) => Promise<void>;
onDeleteTeam: (id: string) => Promise<void>;
- /** A8 ("Pick a repo"): open with the Team Workspace group in view and its input focused. */
- focusWorkspace?: boolean;
+ /** A8 ("Pick a repo"): open with the Team Workspace group in view and its input focused.
+ * 'folder' (an isolation notice's Change folder): the same, but a team with no workspace yet
+ * lands on Local Path, not Git Repo. */
+ focusWorkspace?: boolean | 'folder';
}
/**
@@ -145,7 +147,7 @@ export const ManageTeamModal: React.FC<ManageTeamModalProps> = ({
setRepoUrl(team.repo_url);
} else {
// A8: no workspace yet, so "Pick a repo" lands on Git Repo.
- setWorkspaceType(focusWorkspace ? 'repo' : 'default');
+ setWorkspaceType(focusWorkspace === 'folder' ? 'local' : focusWorkspace ? 'repo' : 'default');
setWorkspacePath('');
setRepoUrl('');
}
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 317ea556..c836b502 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -32,6 +32,7 @@ import { useAuth } from './AuthGate';
import { SignedInDevices } from './DeviceSignIn';
import { signedInDevicesVisible } from '../deviceSignIn';
import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';
+import { ClaudeIsolationRow } from './ClaudeIsolationRow';
import { LayaStatusRow } from './LayaStatus';
import { AppUpdateAbout, useAppUpdate } from './AppUpdateBanner';
import { WhatsNewAbout } from './WhatsNewSheet';
@@ -472,13 +473,16 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
useEffect(() => {
if (!isOpen || !focusRow || !settings) return;
const raf = requestAnimationFrame(() => {
- const el = document.querySelector<HTMLElement>(`[data-switch="${focusRow}"]`);
+ // The Claude switch shows only in VM mode; otherwise land on the Computer card it lives in.
+ const el =
+ document.querySelector<HTMLElement>(`[data-switch="${focusRow}"]`) ??
+ (focusRow === 'claude-isolation' ? document.querySelector<HTMLElement>('[data-computer-card]') : null);
if (!el) return;
el.scrollIntoView({ block: 'center', behavior: 'auto' });
el.focus({ preventScroll: true });
});
return () => cancelAnimationFrame(raf);
- }, [isOpen, focusRow, settings]);
+ }, [isOpen, focusRow, settings, computer.state.settings]);
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
@@ -669,7 +673,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
<StarAskSettingsLink />
{computer.state.settings && (
- <div className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3">
+ <div data-computer-card tabIndex={-1} className="bg-zinc-950/60 p-4 rounded-xl border border-zinc-800 space-y-3 focus:outline-none">
<div>
<p id="computer-mode-label" className="flex items-center gap-2 text-xs font-medium text-zinc-300">
<Monitor size={15} className="text-sky-400" aria-hidden="true" />
@@ -678,6 +682,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
<p className="mt-1 text-[11px] text-zinc-500">Switches right away, no need to save.</p>
</div>
<ComputerModeControl api={computer} />
+ <ClaudeIsolationRow api={computer} />
</div>
)}
diff --git a/frontend/src/computerMode.ts b/frontend/src/computerMode.ts
index 37540464..9ff5e965 100644
--- a/frontend/src/computerMode.ts
+++ b/frontend/src/computerMode.ts
@@ -1,5 +1,6 @@
// "Local computer" vs "VM": which computer kwant's browser and shell use.
// Contract: GET/PUT /api/settings/computer (docs/browser-service.md)
+import { ClaudeVm, hostSupportsIsolation, parseClaudeVm, putErrorText } from './claudeVm';
export type ComputerMode = 'local' | 'vm';
@@ -18,6 +19,8 @@ export interface ComputerSettings {
window: LocalWindow;
/** What vm mode runs in containers, as the server reports it ("browser", "kwnt_shell", later "cli_agents"). */
isolates: string[];
+ /** "Run Claude inside the VM"; null on servers without it. */
+ claudeVm: ClaudeVm | null;
}
/** What vm mode isolated before the server said so: never the CLI agents. */
@@ -26,7 +29,15 @@ export const DEFAULT_VM_ISOLATES = ['browser', 'kwnt_shell'];
const ISOLATED_PARTS: Record<string, string> = { browser: 'browser', kwnt_shell: 'built-in shell' };
/** VM copy built from what it really isolates, so it can't promise more than the server does. */
-export function vmCopy(isolates: string[]): { label: string; hint: string; note: string | null } {
+export function vmCopy(isolates: string[], claudeOn = false): { label: string; hint: string; note: string | null } {
+ // The setting, not the old umbrella flag, says whether Claude moved (ui.md decision 5)
+ if (claudeOn && isolates.includes('kwnt_shell')) {
+ return {
+ label: 'VM (browser, shell and Claude isolated)',
+ hint: 'The browser, built-in shell and Claude run in Docker containers, away from your files.',
+ note: 'Codex and Grok still run on this computer, with their own file and shell tools. They won’t run in a folder Claude used inside the VM.',
+ };
+ }
if (isolates.includes('cli_agents')) {
return { label: 'VM (isolated)', hint: 'Runs bots in Docker containers, away from your files.', note: null };
}
@@ -60,9 +71,21 @@ export const COMPUTER_MODES: ModeCopy[] = [
{ id: 'vm', short: 'VM', ...vmCopy(DEFAULT_VM_ISOLATES) },
];
+/** Said under the VM card in Local mode, on hosts where the switch would work, while it's off (state H). */
+export const PICK_VM_FOR_CLAUDE = 'Pick VM to run Claude inside it too.';
+
/** Both options, with the VM copy taken from what this server says it isolates. */
-export const computerModes = (s: ComputerSettings | null | undefined): ModeCopy[] =>
- s ? COMPUTER_MODES.map((m) => (m.id === 'vm' ? { ...m, ...vmCopy(s.isolates) } : m)) : COMPUTER_MODES;
+export const computerModes = (s: ComputerSettings | null | undefined): ModeCopy[] => {
+ if (!s) return COMPUTER_MODES;
+ return COMPUTER_MODES.map((m) => {
+ if (m.id !== 'vm') return m;
+ const copy = vmCopy(s.isolates, !!s.claudeVm?.on);
+ if (s.mode === 'local' && s.claudeVm && !s.claudeVm.on && hostSupportsIsolation(s.claudeVm) && s.isolates.includes('kwnt_shell')) {
+ copy.note = copy.note ? `${copy.note} ${PICK_VM_FOR_CLAUDE}` : PICK_VM_FOR_CLAUDE;
+ }
+ return { ...m, ...copy };
+ });
+};
export const LOCAL_BROWSER_NOTE = "Your bots' Chrome is open as a window on your computer.";
@@ -105,6 +128,7 @@ export function parseComputerSettings(data: unknown): ComputerSettings | null {
},
// Older servers don't send it; they isolated the same things.
isolates: Array.isArray(d.isolates) ? d.isolates.filter((x: unknown): x is string => typeof x === 'string') : DEFAULT_VM_ISOLATES,
+ claudeVm: parseClaudeVm(d),
};
}
@@ -187,3 +211,21 @@ export const saveComputerMode = (mode: ComputerMode) => putSettings('/api/settin
/** Opens the bots' Chrome as a window (`true`) or puts it back in the app (`false`). */
export const saveLocalWindow = (visible: boolean) =>
putSettings('/api/settings/computer/window', { visible }, visible ? 'Could not open the window' : 'Could not bring the browser back');
+
+/** Turns "Run Claude inside the VM" on or off. A 400's code is put in people's words (fix 5). */
+export async function saveIsolateClaude(on: boolean): Promise<SaveResult> {
+ let res: Response;
+ try {
+ res = await fetch('/api/settings/computer', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ isolate_claude: on }),
+ });
+ } catch {
+ return { ok: false, error: 'Could not reach the server.' };
+ }
+ const data = await res.json().catch(() => null);
+ if (!res.ok) return { ok: false, error: putErrorText(res.status, data) };
+ const settings = parseComputerSettings(data);
+ return settings ? { ok: true, settings } : { ok: false, error: 'The server sent an unexpected answer.' };
+}
diff --git a/frontend/src/interruptions.ts b/frontend/src/interruptions.ts
index b31d3f2a..df39bbb9 100644
--- a/frontend/src/interruptions.ts
+++ b/frontend/src/interruptions.ts
@@ -4,6 +4,7 @@
import type { ChatMessage } from './components/ChatView';
import { AttachmentRef, parseAttachments } from './attachments';
import { parseMetaObject } from './questions';
+import { isIsolationNotice } from './isolationNotice';
export interface Interruption {
kind: 'restart' | 'stall';
@@ -58,7 +59,8 @@ export function retryTargets(messages: ChatMessage[]): Map<string, RetryTarget>
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
if (msg.sender_role === 'user') return out;
- if (!parseInterruption(msg)) continue;
+ // Isolation refusals and the request limit end a reply too (agents-in-vm notices 1–7).
+ if (!parseInterruption(msg) && !isIsolationNotice(msg)) continue;
for (let j = i - 1; j >= 0; j--) {
const prev = messages[j];
if (prev.sender_role !== 'user') continue;
diff --git a/frontend/src/isolationNotice.ts b/frontend/src/isolationNotice.ts
new file mode 100644
index 00000000..9ff8526b
--- /dev/null
+++ b/frontend/src/isolationNotice.ts
@@ -0,0 +1,290 @@
+// Chat notices when "Run Claude inside the VM" stopped a reply (`turn_isolation_failed`) or a
+// reply hit its request limit (`turn_request_limit`). Copy: design/ui.md "Chat notices" and
+// "Copy for Ada's decisions 2", plus design/ui-check-446.md fix 4 (a row for every code).
+// Server: src/sandbox/agent_vm/notice.rs (`IsolationFailed::to_meta`, `start_text`) and
+// src/drivers/cli.rs (`isolation_notice`, `isolated_end`).
+import type { ChatMessage } from './components/ChatView';
+import { SETTING_NAME } from './claudeVm';
+import { parseMetaObject } from './questions';
+
+export type FolderFrom = 'team' | 'space' | 'goal' | 'bot';
+
+export interface IsolationFailedMeta {
+ kind: 'turn_isolation_failed';
+ botName: string;
+ engine: string;
+ reason: string;
+ phase: 'start' | 'mid_turn';
+ progressPct: number | null;
+ code: string | null;
+ folder: string | null;
+ folderFrom: FolderFrom | null;
+ teamId: string | null;
+ teamName: string | null;
+ unsafeKind: string | null;
+ /** People's words from the server for this refusal, if it sends them (`detail` or `message`). */
+ detail: string | null;
+}
+
+export interface RequestLimitMeta {
+ kind: 'turn_request_limit';
+ botName: string;
+ limit: number | null;
+}
+
+const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : null);
+const FROMS: FolderFrom[] = ['team', 'space', 'goal', 'bot'];
+
+export function parseIsolationFailed(msg: ChatMessage): IsolationFailedMeta | null {
+ if (msg.sender_role !== 'kwant' && msg.sender_role !== 'system') return null;
+ const m = parseMetaObject(msg.meta);
+ if (m?.kind !== 'turn_isolation_failed') return null;
+ const from = str(m.folder_from);
+ const pct = typeof m.progress_pct === 'number' && Number.isFinite(m.progress_pct) ? Math.max(0, Math.min(100, Math.floor(m.progress_pct))) : null;
+ return {
+ kind: 'turn_isolation_failed',
+ botName: str(m.kwant_name) ?? (msg.sender_id && msg.sender_id.length <= 40 ? msg.sender_id : 'The bot'),
+ engine: str(m.engine) ?? 'claude',
+ reason: str(m.reason) ?? str(m.code) ?? 'unknown',
+ phase: m.phase === 'mid_turn' ? 'mid_turn' : 'start',
+ progressPct: pct,
+ code: str(m.code),
+ folder: str(m.folder),
+ folderFrom: from && (FROMS as string[]).includes(from) ? (from as FolderFrom) : null,
+ teamId: str(m.team_id),
+ teamName: str(m.team_name),
+ unsafeKind: str(m.unsafe_kind),
+ detail: str(m.detail) ?? str(m.message),
+ };
+}
+
+export function parseRequestLimit(msg: ChatMessage): RequestLimitMeta | null {
+ if (msg.sender_role !== 'kwant' && msg.sender_role !== 'system') return null;
+ const m = parseMetaObject(msg.meta);
+ if (m?.kind !== 'turn_request_limit') return null;
+ const limit = typeof m.limit === 'number' && m.limit > 0 ? Math.floor(m.limit) : null;
+ return { kind: 'turn_request_limit', botName: str(m.kwant_name) ?? (msg.sender_id || 'The bot'), limit };
+}
+
+/** The frontend doesn't know $HOME: `/home/<you>` and `/Users/<you>` read as `~`. */
+export const shortPath = (p: string) => p.replace(/^\/(?:Users|home)\/[^/]+(?=\/|$)/, '~');
+
+const ENGINE = (e: string) => (e === 'codex' ? 'Codex' : e === 'grok' ? 'Grok' : e === 'claude' ? 'Claude' : e);
+
+// ---- the card's model ----
+
+/** A run of reason text; `folder` runs are drawn in mono, `team` runs as "@Team". */
+export type Seg = { text: string; folder?: boolean };
+
+export type NoticeAction = 'retry' | 'computer' | 'accounts' | 'change_folder' | 'edit_bot';
+
+/** Which safety line, if any. `standard` names the setting; the others are notice 6/7 and fix 4 lines. */
+export type SafetyKind = 'standard' | 'nothing_ran' | 'unsafe' | 'unsafe_shared' | 'folder_used' | null;
+
+export interface IsolationCard {
+ /** Stable key for tests and `data-isolation-row`. */
+ row: string;
+ first: string;
+ reason: Seg[];
+ safety: SafetyKind;
+ /** In order: the first one is primary. */
+ actions: NoticeAction[];
+}
+
+/** The safety lines, split so the setting's name can be bold. */
+export const SAFETY: Record<Exclude<SafetyKind, null>, [string, string, string] | [string]> = {
+ standard: ['While ', SETTING_NAME, ' is on, Claude never runs outside it, so nothing ran on this computer. To run Claude here instead, turn that off in Computer settings.'],
+ nothing_ran: ['Nothing ran.'],
+ unsafe: ['Nothing ran. Turning off ', SETTING_NAME, ' would also work, but then Claude could read this whole folder from this computer.'],
+ unsafe_shared: ['Nothing ran. Turning off ', SETTING_NAME, ' would also work, but then Claude runs on this computer again.'],
+ folder_used: ['Nothing ran. Turning off ', SETTING_NAME, ' doesn’t change this, because the folder may already hold those settings.'],
+};
+
+const t = (text: string): Seg => ({ text });
+
+/** Notice 6, sentence 1, by `unsafe_kind`. */
+function unsafeSentence(kind: string | null, folder: string | null): Seg[] {
+ const f = folder ? shortPath(folder) : null;
+ const withPath = (lead: string | null, rest: string): Seg[] => (f ? [{ text: f, folder: true }, t(rest)] : [t(`${lead ?? 'This folder'}${rest}`)]);
+ switch (kind) {
+ case 'home':
+ return withPath('This folder', ' is your home folder. Inside the VM, Claude would see all your files and sign-ins.');
+ case 'contains_home':
+ case 'root':
+ return withPath('This folder', ' holds your home folder. Inside the VM, Claude would see all your files and sign-ins.');
+ case 'sign_ins':
+ return withPath('This folder', ' holds sign-ins, like your SSH keys or Claude, Codex or Grok sign-in, so kwant won’t share it with the VM.');
+ case 'kwant_data':
+ return withPath('This folder', ' holds kwant’s own data, including your sign-ins, so kwant won’t share it with the VM.');
+ case 'docker':
+ return withPath('This folder', ' holds Docker’s control socket, which would let Claude out of the VM.');
+ case 'shared_folder':
+ return [t('This is the folder teams share when they don’t have their own. If Claude used it inside the VM, Codex and Grok bots in every team would be kept out of it.')];
+ default:
+ return [t('This folder holds your home folder or sign-ins, so kwant won’t share it with the VM.')];
+ }
+}
+
+const canChangeFolder = (m: IsolationFailedMeta) => m.folderFrom === 'team' && !!m.teamId;
+const team = (m: IsolationFailedMeta) => (m.teamName ? `@${m.teamName}` : null);
+
+function unsafeFolderCard(m: IsolationFailedMeta): IsolationCard {
+ const shared = m.unsafeKind === 'shared_folder';
+ const s1 = unsafeSentence(m.unsafeKind, shared ? null : m.folder);
+ let s2: string;
+ if (shared) s2 = team(m) ? `Give ${team(m)} its own folder, then Retry.` : 'Give this team its own folder, then Retry.';
+ else if (m.folderFrom === 'team') s2 = team(m) ? `Pick a project folder for ${team(m)} instead, then Retry.` : 'Pick a project folder for this team instead, then Retry.';
+ else if (m.folderFrom === 'goal') s2 = 'Pick a project folder for this goal instead, then Retry.';
+ else s2 = 'Pick a project folder instead, then Retry.';
+ // The shared folder is a team's when it has none of its own, so Change folder fits whenever the team is known.
+ const change = canChangeFolder(m) || (shared && !!m.teamId);
+ return {
+ row: shared ? 'unsafe_folder:shared_folder' : `unsafe_folder:${m.unsafeKind ?? 'unknown'}`,
+ first: `${m.botName} didn’t reply: Claude can’t use this folder inside the VM.`,
+ reason: [...s1, t(` ${s2}`)],
+ safety: shared ? 'unsafe_shared' : 'unsafe',
+ actions: change ? ['change_folder', 'retry'] : ['retry'],
+ };
+}
+
+function folderUsedCard(m: IsolationFailedMeta): IsolationCard {
+ const E = ENGINE(m.engine);
+ const bot = m.botName;
+ const f: Seg = m.folder ? { text: shortPath(m.folder), folder: true } : t('this folder');
+ let reason: Seg[];
+ let row: string;
+ if (m.folderFrom === 'bot') {
+ row = 'folder_used_by_isolated_bot:bot';
+ reason = [t(`${bot} used this folder as Claude inside the VM, and it could have left settings there that ${E} would load on this computer. Switch ${bot} back to Claude to keep working here.`)];
+ } else if (m.folderFrom === 'team') {
+ row = 'folder_used_by_isolated_bot:team';
+ const other = team(m) ? `pick another folder for ${team(m)}` : 'pick another folder';
+ reason = [t('A bot inside the VM could have left settings in '), f, t(` that ${E} would load on this computer, so kwant keeps ${E} out of it for now. Switch ${bot} to Claude, or ${other}, then Retry.`)];
+ } else {
+ row = 'folder_used_by_isolated_bot:other';
+ reason = [t('A bot inside the VM could have left settings in '), f, t(` that ${E} would load on this computer, so kwant keeps ${E} out of it for now. Switch ${bot} to Claude, then Retry.`)];
+ }
+ const second: NoticeAction[] = canChangeFolder(m) ? ['change_folder'] : ['retry'];
+ return {
+ row,
+ first: `${bot} didn’t reply: ${E} won’t run in a folder Claude used inside the VM.`,
+ reason,
+ safety: 'folder_used',
+ actions: ['edit_bot', ...second],
+ };
+}
+
+const GENERIC_FIRST = (bot: string) => `${bot} didn’t reply: Claude couldn’t start inside the VM.`;
+
+/**
+ * The reason for a code with no row of its own. The server's own words win (a `detail` in the
+ * meta, or what its saved text says beyond the template); "Something went wrong ({code})" only
+ * when there's nothing else.
+ */
+export function unknownReason(m: IsolationFailedMeta, savedText: string | null | undefined): string {
+ const code = m.code ?? m.reason;
+ const tail = `Retry, or turn off ${SETTING_NAME} to run Claude on this computer.`;
+ const own = m.detail ?? serverReason(savedText, m.botName);
+ if (own) return `${own.replace(/[.\s]+$/, '')}. ${tail}`;
+ return `Something went wrong (${code}). ${tail}`;
+}
+
+/**
+ * The human part of a saved notice text: without its first sentence ("{Bot} didn't reply: …"),
+ * the safety sentence and the generic "Something went wrong (code). Retry, or turn off…" template.
+ * Null when only the template is left.
+ */
+export function serverReason(text: string | null | undefined, bot: string): string | null {
+ if (!text) return null;
+ let s = text.replace(/[‘’]/g, "'").trim();
+ const lead = `${bot.replace(/[‘’]/g, "'")} didn't reply:`;
+ if (s.startsWith(lead)) {
+ const end = s.indexOf('.', lead.length);
+ s = end >= 0 ? s.slice(end + 1) : '';
+ }
+ s = s
+ .replace(/While Run Claude inside the VM is on, Claude never runs outside it, so nothing ran on this computer\.(?: To run Claude here instead, turn that off in Computer settings\.)?/g, '')
+ .replace(/Something went wrong \([^)]*\)\.?/g, '')
+ .replace(/Retry, or turn off Run Claude inside the VM to run Claude on this computer\.?/g, '')
+ .replace(/\s+/g, ' ')
+ .trim();
+ return s ? s.replace(/'/g, '’') : null;
+}
+
+/** Everything a `turn_isolation_failed` card shows, by reason (one row per code the server sends). */
+export function isolationCard(m: IsolationFailedMeta, savedText?: string | null): IsolationCard {
+ const bot = m.botName;
+ const couldnt = GENERIC_FIRST(bot);
+ const notReady = `${bot} didn’t reply: Claude’s VM isn’t ready yet.`;
+ const std = (row: string, first: string, reason: string, actions: NoticeAction[] = ['retry', 'computer'], safety: SafetyKind = 'standard'): IsolationCard => ({
+ row,
+ first,
+ reason: [t(reason)],
+ safety,
+ actions,
+ });
+
+ if (m.reason === 'unsafe_folder') return unsafeFolderCard(m);
+ if (m.reason === 'folder_used_by_isolated_bot') return folderUsedCard(m);
+ if (m.phase === 'mid_turn')
+ return std(
+ 'mid_turn',
+ `${bot}’s reply stopped partway: Claude lost its connection inside the VM.`,
+ 'What it changed before that is in the task folder, and Undo still works. Retry to start the reply again.',
+ );
+
+ switch (m.reason) {
+ case 'docker_unavailable':
+ return std('docker_unavailable', couldnt, 'Docker isn’t running on this computer. Start Docker, then Retry.');
+ case 'preparing':
+ // progress_pct is always null in 0.7.7 (ui-check §4), so the no-% wording unless it's sent.
+ return std(
+ 'preparing',
+ notReady,
+ m.progressPct !== null ? `The one-time setup is at ${m.progressPct}%. Retry when it’s done.` : 'The one-time setup is still running. Retry when it’s done.',
+ );
+ case 'download_failed':
+ case 'download_needed':
+ return std(m.reason, notReady, 'The one-time setup didn’t finish. Try it again in Computer settings, then Retry.');
+ case 'relay_down':
+ return std('relay_down', couldnt, 'kwant couldn’t connect Claude to your sign-in. Restart kwant, then Retry.');
+ case 'sign_in_expired':
+ return std('sign_in_expired', `${bot} didn’t reply: your Claude sign-in has expired.`, 'Sign in again in Settings › This space › Accounts, then Retry.', ['retry', 'accounts'], null);
+ case 'no_credential':
+ return std('no_credential', `${bot} didn’t reply: there’s no Claude sign-in for it on this computer.`, 'Sign in to Claude in Settings › This space › Accounts, then Retry.', ['retry', 'accounts'], null);
+ case 'host_is_root':
+ return std('host_is_root', couldnt, 'kwant is running as root, so Claude can’t run inside the VM as you. Start kwant as your normal user, then Retry.');
+ case 'folder_name_unsupported':
+ return std(
+ 'folder_name_unsupported',
+ `${bot} didn’t reply: Claude can’t use this folder inside the VM.`,
+ 'The folder’s name has characters kwant can’t pass to the VM, like a line break. Rename the folder, then Retry.',
+ ['retry'],
+ 'nothing_ran',
+ );
+ case 'folder_record_failed':
+ return std('folder_record_failed', couldnt, 'kwant couldn’t note that this folder is used inside the VM, so it didn’t start Claude. Retry; if it keeps happening, restart kwant.');
+ case 'container_failed':
+ return std('container_failed', couldnt, 'The VM couldn’t start Claude. Retry; if it keeps happening, restart Docker.');
+ case 'unsupported_os':
+ case 'not_supported_yet':
+ case 'mac_later':
+ return std(m.reason, couldnt, `Isolation is only on Linux for now. Turn off ${SETTING_NAME} to run Claude on this computer.`, ['computer']);
+ default:
+ return std('unknown', couldnt, unknownReason(m, savedText));
+ }
+}
+
+/** Notice 5: the request limit. */
+export function requestLimitText(m: RequestLimitMeta) {
+ return {
+ first: m.limit ? `${m.botName} paused after ${m.limit} requests to Claude in this reply.` : `${m.botName} paused: this reply reached its limit of requests to Claude.`,
+ body: 'That’s the most one reply can make, so a bot stuck in a loop can’t keep using up your Claude plan. Its work so far is kept.',
+ };
+}
+
+/** What Continue sends, as a visible message from the person (ui.md notice 5). */
+export const CONTINUE_TEXT = 'Continue where you left off.';
+
+/** A notice that ends a reply and offers Retry or Continue (for `retryTargets`). */
+export const isIsolationNotice = (msg: ChatMessage) => !!parseIsolationFailed(msg) || !!parseRequestLimit(msg);
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 0c2d80e9..e763b7ff 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -1251,7 +1251,10 @@ export function restoreErrorText(e: unknown): string {
case 'unknown_force_path':
return 'A file you picked isn’t in the preview any more. Look at the new preview.';
case 'checkpoint_failed':
- return 'The safety checkpoint couldn’t be taken, so nothing was restored.';
+ // #446: the same code when the task's folder is missing, moved or a symlink now.
+ return /missing, moved or a symlink/.test(e.message)
+ ? 'Couldn’t restore: the task’s folder was moved or replaced. Nothing was changed.'
+ : 'The safety checkpoint couldn’t be taken, so nothing was restored.';
case 'not_held':
return 'It isn’t on hold any more, maybe Run was pressed in another tab.';
default:
diff --git a/frontend/src/threads.ts b/frontend/src/threads.ts
index a6ea158a..1673b272 100644
--- a/frontend/src/threads.ts
+++ b/frontend/src/threads.ts
@@ -82,10 +82,17 @@ export const shouldRenderDelta = (
// ---------------------------------------------------------------------------
// Turns: running and queued, from turn_queued / turn_started / turn_ended and GET /api/turns
+/** Why a reply waits: its bot is busy, the server is full, or every VM spot is taken (#446). */
+export type QueueReason = 'agent_busy' | 'server_busy' | 'vm_busy';
+
+const queueReason = (r: unknown): QueueReason => (r === 'server_busy' || r === 'vm_busy' ? r : 'agent_busy');
+
export interface TrackedTurn extends ActiveTurn {
/** Order seen; the queue is FIFO. */
seq: number;
- reason?: 'agent_busy' | 'server_busy';
+ reason?: QueueReason;
+ /** vm_busy only: how many replies run inside the VM at once. */
+ slots?: number;
/** Position reported by the server when it queued; only ever goes down. */
reported?: number;
}
@@ -151,7 +158,8 @@ export function applyTurnEvent(turns: TurnMap, ev: { type?: string; data?: any }
thread_id: d.thread_id ?? null,
state: 'queued',
seq: turns[id]?.seq ?? ++seqCounter,
- reason: d.reason === 'server_busy' ? 'server_busy' : 'agent_busy',
+ reason: queueReason(d.reason),
+ slots: d.reason === 'vm_busy' && typeof d.slots === 'number' && d.slots > 0 ? d.slots : undefined,
reported: typeof d.position === 'number' ? d.position : undefined,
since: new Date().toISOString(),
},
@@ -193,7 +201,7 @@ export function queuePosition(turns: TurnMap, turnId: string): number | null {
let ahead = 0;
for (const o of Object.values(turns)) {
if (o.state !== 'queued' || o.seq >= t.seq) continue;
- if (t.reason === 'server_busy' || o.kwant_id === t.kwant_id) ahead++;
+ if (t.reason === 'vm_busy' ? o.reason === 'vm_busy' : t.reason === 'server_busy' || o.kwant_id === t.kwant_id) ahead++;
}
const computed = ahead + 1;
return t.reported ? Math.min(t.reported, computed) : computed;
diff --git a/frontend/tests/claudeVm.test.mjs b/frontend/tests/claudeVm.test.mjs
new file mode 100644
index 00000000..d4940778
--- /dev/null
+++ b/frontend/tests/claudeVm.test.mjs
@@ -0,0 +1,236 @@
+// "Run Claude inside the VM": the setting under the VM card, its chips and status line
+// (design/ui.md states A–H, design/ui-check-446.md fixes 1, 5–9).
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+
+const m = await loadBundled(`
+ export * from './src/claudeVm';
+ export { parseComputerSettings, vmCopy, computerModes, saveIsolateClaude } from './src/computerMode';
+ export { ClaudeIsolationRow } from './src/components/ClaudeIsolationRow';
+ export { initialSwitchState } from './src/computerMode';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { createElement } from 'react';
+`);
+
+const NA = (reason = 'not_supported_yet') => ({ state: 'not_isolated', reason, detail: null, progress: null });
+// Shaped like src/server/computer.rs view().
+const view = ({ on = false, available = true, reason = null, claude = { state: on ? 'isolated' : 'off', reason: null, detail: null, progress: null }, mode = 'vm' } = {}) => ({
+ mode,
+ available: { local: true, vm: true },
+ reasons: { local: null, vm: null },
+ isolates: ['browser', 'kwnt_shell'],
+ isolate_claude: on,
+ isolate_claude_toggle: { available, reason },
+ agents: { claude, codex: NA(), grok: NA() },
+});
+const vmOf = (v) => m.parseClaudeVm(v);
+const api = (raw, extra = {}) => ({
+ state: { ...m.initialSwitchState, settings: m.parseComputerSettings(raw) },
+ select: () => {},
+ dismissError: () => {},
+ setWindow: () => {},
+ windowPending: false,
+ setIsolateClaude: () => {},
+ refresh: async () => {},
+ isoPending: null,
+ isoError: null,
+ ...extra,
+});
+const render = (raw, extra) => m.renderToStaticMarkup(m.createElement(m.ClaudeIsolationRow, { api: api(raw, extra) }));
+
+test('parseClaudeVm reads the contract; an older server has no row', () => {
+ const vm = vmOf(view({ on: true }));
+ assert.equal(vm.on, true);
+ assert.deepEqual(vm.toggle, { available: true, reason: null });
+ assert.equal(vm.agents.claude.state, 'isolated');
+ assert.equal(vm.agents.codex.reason, 'not_supported_yet');
+ assert.equal(m.parseClaudeVm({ mode: 'vm' }), null);
+ assert.equal(m.parseComputerSettings({ ...view(), isolate_claude: undefined }).claudeVm, null);
+ // progress is clamped and needs a positive total
+ const p = vmOf(view({ on: true, claude: { state: 'preparing', progress: { done_bytes: 900, total_bytes: 860 } } }));
+ assert.deepEqual(p.agents.claude.progress, { done_bytes: 860, total_bytes: 860 });
+ assert.equal(vmOf(view({ on: true, claude: { state: 'preparing', progress: { done_bytes: 1, total_bytes: 0 } } })).agents.claude.progress, null);
+});
+
+test('A: off by default on Linux — enabled switch, the hint, all three chips neutral', () => {
+ const r = m.rowModel(vmOf(view()));
+ assert.deepEqual([r.checked, r.disabled, r.status], [false, false, null]);
+ assert.equal(r.hint, m.ISOLATION_HINT);
+ const html = render(view());
+ assert.match(html, /role="switch"/);
+ assert.match(html, /aria-checked="false"/);
+ assert.doesNotMatch(html, /aria-disabled/);
+ assert.match(html, /web search included/);
+ assert.match(html, /aria-label="Where each AI runs right now"/);
+ assert.match(html, /Claude: not isolated/);
+ assert.match(html, /Codex: not isolated yet/);
+ assert.match(html, /Grok: not isolated yet/);
+});
+
+test('Mac: disabled with its reason, no status line', () => {
+ const raw = view({ available: false, reason: 'mac_later', claude: { state: 'off', reason: 'mac_later' } });
+ const r = m.rowModel(vmOf(raw));
+ assert.deepEqual([r.checked, r.disabled, r.status], [false, true, null]);
+ assert.equal(r.hint, 'Coming to Mac later. For now, Claude runs on this computer in both modes.');
+ const html = render(raw);
+ assert.match(html, /aria-disabled="true"/);
+ assert.match(html, /Coming to Mac later/);
+});
+
+test('Windows gets its own line (fix 8)', () => {
+ const raw = view({ available: false, reason: 'not_supported_yet', claude: { state: 'off', reason: 'not_supported_yet' } });
+ assert.equal(m.rowModel(vmOf(raw)).hint, 'Only on Linux for now. Claude runs on this computer in both modes.');
+ assert.match(render(raw), /Only on Linux for now/);
+});
+
+test('Docker down, switch off: disabled, quiet "Start Docker to turn this on."', () => {
+ const raw = view({ available: false, reason: 'docker_unavailable', claude: { state: 'off' } });
+ const r = m.rowModel(vmOf(raw));
+ assert.equal(r.disabled, true);
+ assert.deepEqual(r.status, { kind: 'quiet', text: 'Start Docker to turn this on.' });
+ assert.match(render(raw), /data-claude-iso-status="quiet"/);
+});
+
+test('Docker down, switch on: stays usable (fix 9), Stopped chip, Check again', () => {
+ const raw = view({ on: true, available: false, reason: 'docker_unavailable', claude: { state: 'unavailable', reason: 'docker_unavailable' } });
+ const r = m.rowModel(vmOf(raw));
+ assert.deepEqual([r.checked, r.disabled], [true, false]);
+ assert.equal(r.status.action, 'check');
+ assert.match(r.status.text, /^Docker isn’t running, so Claude can’t reply\./);
+ const html = render(raw);
+ assert.doesNotMatch(html, /aria-disabled/);
+ assert.match(html, /data-tone="stopped"/);
+ assert.match(html, /Claude: stopped/);
+ assert.match(html, /data-claude-iso-action="check"/);
+ assert.match(html, />Check again</);
+});
+
+test('B: getting ready without progress — spinner chip, no bar, two lines (fix 6)', () => {
+ const raw = view({ on: true, claude: { state: 'preparing', progress: null } });
+ const vm = vmOf(raw);
+ const chip = m.chipFor('claude', vm.agents.claude);
+ assert.deepEqual([chip.tone, chip.label, chip.indeterminate], ['preparing', 'Getting ready', true]);
+ const html = render(raw);
+ assert.match(html, /role="status"/);
+ assert.doesNotMatch(html, /role="progressbar"/);
+ assert.match(html, /downloads about 860 MB and takes a few minutes/);
+ assert.match(html, /Turning this off lets Claude reply on this computer meanwhile; the setup keeps going\./);
+ assert.match(html, /animate-spin/);
+ assert.equal(m.pollInterval(vm), 1000);
+});
+
+test('B with measured progress: percent chip and a bar', () => {
+ const raw = view({ on: true, claude: { state: 'preparing', progress: { done_bytes: 430_000_000, total_bytes: 860_000_000 } } });
+ assert.equal(m.chipFor('claude', vmOf(raw).agents.claude).label, 'Getting ready · 50%');
+ const html = render(raw);
+ assert.match(html, /role="progressbar"/);
+ assert.match(html, /430 of 860 MB/);
+ assert.match(html, /scaleX\(0\.5\)/);
+});
+
+test('C: isolated — teal chip, no status line, no polling', () => {
+ const raw = view({ on: true });
+ const vm = vmOf(raw);
+ assert.equal(m.rowModel(vm).status, null);
+ assert.equal(m.pollInterval(vm), null);
+ const html = render(raw);
+ assert.match(html, /aria-checked="true"/);
+ assert.match(html, /data-tone="isolated"/);
+ assert.match(html, /Claude: isolated/);
+});
+
+test('E: download failed — the server detail and Try again (fix 7)', () => {
+ const raw = view({ on: true, claude: { state: 'unavailable', reason: 'download_failed', detail: 'the image pull timed out.' } });
+ const r = m.rowModel(vmOf(raw));
+ assert.equal(r.status.text, 'The setup stopped: the image pull timed out. Claude can’t reply until it finishes.');
+ assert.equal(r.status.action, 'retry');
+ assert.match(render(raw), />Try again</);
+ assert.equal(m.pollInterval(vmOf(raw)), 10_000);
+});
+
+test('download needed, relay down, sign-in expired and an unknown reason each get a line', () => {
+ const line = (reason, detail = null) => m.stoppedLine({ state: 'unavailable', reason, detail, progress: null });
+ assert.equal(line('download_needed').action, 'retry');
+ assert.match(line('relay_down').text, /couldn’t connect Claude to your sign-in/);
+ assert.equal(line('relay_down').action, null);
+ assert.match(line('sign_in_expired').text, /sign-in has expired/);
+ assert.match(line('weird_code').text, /\(code weird_code\)/);
+ assert.match(line('weird_code', 'The disk is full.').text, /\(The disk is full\)/);
+});
+
+test('Local mode or API-key bot: neutral chip with the server detail as its title', () => {
+ const detail = 'Bots using an API key run inside kwant; their tools already use the VM.';
+ const chip = m.chipFor('claude', { state: 'not_isolated', reason: null, detail, progress: null });
+ assert.deepEqual([chip.tone, chip.label, chip.title], ['neutral', 'Not isolated', detail]);
+});
+
+test('the row shows only in VM mode', () => {
+ assert.equal(render(view({ mode: 'local' })), '');
+});
+
+test('saving: the switch shows the pending value and is busy; errors show', () => {
+ const html = render(view(), { isoPending: true, isoError: 'Start Docker to turn this on.' });
+ assert.match(html, /aria-checked="true"/);
+ assert.match(html, /aria-busy="true"/);
+ assert.match(html, /Start Docker to turn this on\./);
+});
+
+test('PUT errors read in people’s words, never as a raw code (fix 5)', () => {
+ assert.equal(m.putErrorText(400, { error: 'mac_later' }), m.PLATFORM_HINTS.mac_later);
+ assert.equal(m.putErrorText(400, { error: 'x', code: 'docker_unavailable' }), 'Start Docker to turn this on.');
+ assert.equal(m.putErrorText(400, { error: 'Docker is not running.', code: 'docker_unavailable' }), 'Docker is not running.', 'the server’s readable error wins');
+ assert.equal(m.putErrorText(400, { error: 'Coming to Mac later. For now, Claude runs on this computer in both modes.', code: 'mac_later' }), m.PLATFORM_HINTS.mac_later);
+ assert.equal(m.putErrorText(400, { error: 'Something human.' }), 'Something human.');
+ assert.equal(m.putErrorText(500, { error: 'boom_code' }), 'Couldn’t change this (HTTP 500).');
+});
+
+test('saveIsolateClaude PUTs the flag and maps a 400', async () => {
+ const orig = globalThis.fetch;
+ try {
+ let body;
+ globalThis.fetch = async (_u, init) => {
+ body = init.body;
+ return new Response(JSON.stringify(view({ on: true, claude: { state: 'preparing' } })), { status: 200 });
+ };
+ const r = await m.saveIsolateClaude(true);
+ assert.deepEqual(JSON.parse(body), { isolate_claude: true });
+ assert.equal(r.ok, true);
+ assert.equal(r.settings.claudeVm.agents.claude.state, 'preparing');
+ globalThis.fetch = async () => new Response(JSON.stringify({ error: 'mac_later' }), { status: 400 });
+ assert.deepEqual(await m.saveIsolateClaude(true), { ok: false, error: m.PLATFORM_HINTS.mac_later });
+ } finally {
+ globalThis.fetch = orig;
+ }
+});
+
+test('the live region speaks at the start, the end and a failure only', () => {
+ const s = (state, reason = null) => ({ state, reason, detail: null, progress: null });
+ assert.equal(m.announcement(s('off'), s('preparing')), 'Getting the VM ready for Claude.');
+ assert.equal(m.announcement(s('preparing'), s('preparing')), null);
+ assert.equal(m.announcement(s('preparing'), s('isolated')), 'Claude now runs inside the VM.');
+ assert.match(m.announcement(s('isolated'), s('unavailable', 'docker_unavailable')), /^Claude stopped\. Docker isn’t running/);
+ assert.equal(m.announcement(undefined, s('isolated')), null);
+});
+
+test('VM card copy: setting on names Claude and warns about Codex and Grok', () => {
+ const on = m.vmCopy(['browser', 'kwnt_shell'], true);
+ assert.equal(on.label, 'VM (browser, shell and Claude isolated)');
+ assert.match(on.note, /They won’t run in a folder Claude used inside the VM\./);
+ assert.equal(m.vmCopy(['browser', 'kwnt_shell'], false).label, 'VM (browser and built-in shell isolated)');
+});
+
+test('queued for a VM spot: Lin’s wording, with or without slots', () => {
+ assert.equal(m.queuedVmText(2), 'Waiting for a free spot in the VM. 2 replies run at once there. This one starts as soon as one finishes.');
+ assert.equal(m.queuedVmText(1), 'Waiting for a free spot in the VM. 1 reply runs at once there. This one starts as soon as one finishes.');
+ assert.equal(m.queuedVmText(), 'Waiting for a free spot in the VM. This one starts as soon as one finishes.');
+});
+
+test('the in-line sentence reads as calm waiting (qa-446: up to ~5 min behind approval cards)', () => {
+ assert.equal(m.queuedText('agent_busy'), 'Waiting for this bot’s other replies to finish.');
+ assert.equal(m.queuedText('vm_busy', 2), m.queuedVmText(2));
+ assert.match(m.queuedText('server_busy'), /starts as soon as a slot frees up/);
+ for (const r of ['agent_busy', 'server_busy', 'vm_busy']) assert.doesNotMatch(m.queuedText(r, 2), /timeout|timed out|error|stuck|minutes/i);
+});
diff --git a/frontend/tests/computerMode.test.mjs b/frontend/tests/computerMode.test.mjs
index 4c7c06b3..d25fac04 100644
--- a/frontend/tests/computerMode.test.mjs
+++ b/frontend/tests/computerMode.test.mjs
@@ -18,6 +18,7 @@ const settings = (mode, local = true, vm = true, reasons = {}, window = {}, isol
reasons: { local: null, vm: null, ...reasons },
window: { visible: false, available: false, reason: null, ...window },
isolates,
+ claudeVm: null,
});
const api = (state, extra = {}) => ({ state, select: () => {}, dismissError: () => {}, setWindow: () => {}, windowPending: false, ...extra });
const render = (C, state) => m.renderToStaticMarkup(m.createElement(C, { api: api(state) }));
diff --git a/frontend/tests/isolationNotice.test.mjs b/frontend/tests/isolationNotice.test.mjs
new file mode 100644
index 00000000..e6695db9
--- /dev/null
+++ b/frontend/tests/isolationNotice.test.mjs
@@ -0,0 +1,214 @@
+// Chat notices for "Run Claude inside the VM": every refusal code gets a row (design/ui.md
+// notices 1–7, design/ui-check-446.md fix 4), the unknown code shows the server's own words,
+// and the request limit gets Continue.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+
+const m = await loadBundled(`
+ export * from './src/isolationNotice';
+ export { retryTargets } from './src/interruptions';
+ export { IsolationNotice, RequestLimitNotice } from './src/components/IsolationNotice';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { createElement } from 'react';
+`);
+
+// Shaped like IsolationFailed::to_meta (src/sandbox/agent_vm/notice.rs).
+const notice = (id, reason, extra = {}, text = 'saved text') => ({
+ id,
+ sender_role: 'kwant',
+ sender_id: 'Ada',
+ text,
+ meta: JSON.stringify({ kind: 'turn_isolation_failed', kwant_name: 'Ada', engine: 'claude', reason, phase: 'start', progress_pct: null, code: null, ...extra }),
+});
+const limitNote = (id, limit = 200) => ({
+ id,
+ sender_role: 'kwant',
+ sender_id: 'Ada',
+ text: `Ada paused after ${limit} requests to Claude in this reply.`,
+ meta: JSON.stringify({ kind: 'turn_request_limit', kwant_name: 'Ada', engine: 'claude', limit }),
+});
+const user = (id, text) => ({ id, sender_role: 'user', sender_id: 'me', text, meta: null });
+const card = (reason, extra, text) => m.isolationCard(m.parseIsolationFailed(notice('n', reason, extra, text)), text);
+const all = { onRetry: () => {}, onOpenComputerSettings: () => {}, onOpenAccounts: () => {}, onChangeTeamFolder: () => {}, onEditBot: () => {} };
+const render = (msg, props = {}) =>
+ m.renderToStaticMarkup(
+ m.createElement(m.IsolationNotice, { messageId: msg.id, meta: m.parseIsolationFailed(msg), text: msg.text, retry: { text: 'go', attachments: [] }, ...all, ...props }),
+ );
+const plain = (c) => c.reason.map((s) => s.text).join('');
+
+test('parses the meta and ignores other messages', () => {
+ const p = m.parseIsolationFailed(notice('n', 'unsafe_folder', { folder: '/home/oleks', folder_from: 'team', team_id: 't1', team_name: 'Checkout', unsafe_kind: 'home' }));
+ assert.equal(p.botName, 'Ada');
+ assert.equal(p.folderFrom, 'team');
+ assert.equal(p.unsafeKind, 'home');
+ assert.equal(m.parseIsolationFailed(user('u', 'hi')), null);
+ assert.equal(m.parseIsolationFailed({ ...notice('n', 'x'), meta: JSON.stringify({ kind: 'turn_stalled' }) }), null);
+ assert.equal(m.parseRequestLimit(limitNote('l')).limit, 200);
+});
+
+// The table: every code the server sends, with first line, reason, safety and buttons.
+const ROWS = [
+ ['docker_unavailable', /couldn’t start inside the VM\.$/, /^Docker isn’t running on this computer\. Start Docker, then Retry\.$/, 'standard', ['retry', 'computer']],
+ ['preparing', /VM isn’t ready yet\.$/, /^The one-time setup is still running\. Retry when it’s done\.$/, 'standard', ['retry', 'computer']],
+ ['download_failed', /VM isn’t ready yet\.$/, /^The one-time setup didn’t finish\. Try it again in Computer settings, then Retry\.$/, 'standard', ['retry', 'computer']],
+ ['download_needed', /VM isn’t ready yet\.$/, /^The one-time setup didn’t finish\./, 'standard', ['retry', 'computer']],
+ ['relay_down', /couldn’t start inside the VM\.$/, /^kwant couldn’t connect Claude to your sign-in\. Restart kwant, then Retry\.$/, 'standard', ['retry', 'computer']],
+ ['sign_in_expired', /your Claude sign-in has expired\.$/, /^Sign in again in Settings › This space › Accounts, then Retry\.$/, null, ['retry', 'accounts']],
+ ['no_credential', /there’s no Claude sign-in for it on this computer\.$/, /^Sign in to Claude in Settings › This space › Accounts, then Retry\.$/, null, ['retry', 'accounts']],
+ ['host_is_root', /couldn’t start inside the VM\.$/, /^kwant is running as root, so Claude can’t run inside the VM as you\./, 'standard', ['retry', 'computer']],
+ ['folder_name_unsupported', /Claude can’t use this folder inside the VM\.$/, /^The folder’s name has characters kwant can’t pass to the VM, like a line break\. Rename the folder, then Retry\.$/, 'nothing_ran', ['retry']],
+ ['folder_record_failed', /couldn’t start inside the VM\.$/, /^kwant couldn’t note that this folder is used inside the VM, so it didn’t start Claude\./, 'standard', ['retry', 'computer']],
+ ['container_failed', /couldn’t start inside the VM\.$/, /^The VM couldn’t start Claude\. Retry; if it keeps happening, restart Docker\.$/, 'standard', ['retry', 'computer']],
+ ['unsupported_os', /couldn’t start inside the VM\.$/, /^Isolation is only on Linux for now\. Turn off Run Claude inside the VM to run Claude on this computer\.$/, 'standard', ['computer']],
+];
+
+for (const [reason, first, why, safety, actions] of ROWS) {
+ test(`row: ${reason}`, () => {
+ const c = card(reason);
+ assert.equal(c.row, reason);
+ assert.match(c.first, /^Ada /);
+ assert.match(c.first, first);
+ assert.match(plain(c), why);
+ assert.equal(c.safety, safety);
+ assert.deepEqual(c.actions, actions);
+ assert.doesNotMatch(plain(c), /Something went wrong/);
+ const html = render(notice('n1', reason));
+ assert.match(html, new RegExp(`data-isolation-notice="${reason}"`));
+ for (const a of actions) assert.match(html, new RegExp(`data-isolation-action="${a}"`));
+ if (safety) assert.match(html, new RegExp(`data-isolation-safety="${safety}"`));
+ else assert.doesNotMatch(html, /data-isolation-safety/);
+ });
+}
+
+test('preparing uses the percent when the server sends it', () => {
+ assert.match(plain(card('preparing', { progress_pct: 42 })), /at 42%/);
+});
+
+test('the standard safety line bolds the setting name', () => {
+ const html = render(notice('n', 'docker_unavailable'));
+ assert.match(html, /While <span class="font-medium text-zinc-300">Run Claude inside the VM<\/span> is on/);
+});
+
+test('mid-turn (notice 3): any reason, its own first line', () => {
+ const c = card('container_failed', { phase: 'mid_turn' });
+ assert.equal(c.row, 'mid_turn');
+ assert.equal(c.first, 'Ada’s reply stopped partway: Claude lost its connection inside the VM.');
+ assert.match(plain(c), /Undo still works/);
+ assert.equal(c.safety, 'standard');
+});
+
+test('unknown code: the server’s own words win over "Something went wrong"', () => {
+ // A detail in the meta
+ assert.match(plain(card('new_code', { detail: 'The VM ran out of disk.' })), /^The VM ran out of disk\. Retry, or turn off Run Claude inside the VM/);
+ // Human text the server saved beyond its template
+ const saved = "Ada didn't reply: Claude couldn't start inside the VM. The image is from a newer kwant. While Run Claude inside the VM is on, Claude never runs outside it, so nothing ran on this computer.";
+ assert.match(plain(card('new_code', {}, saved)), /^The image is from a newer kwant\. Retry/);
+ // Only the template: the code, as a last resort
+ const tpl = "Ada didn't reply: Claude couldn't start inside the VM. Something went wrong (new_code). Retry, or turn off Run Claude inside the VM to run Claude on this computer. While Run Claude inside the VM is on, Claude never runs outside it, so nothing ran on this computer.";
+ assert.equal(m.serverReason(tpl, 'Ada'), null);
+ assert.match(plain(card('new_code', {}, tpl)), /^Something went wrong \(new_code\)\./);
+ assert.equal(card('new_code').row, 'unknown');
+ assert.deepEqual(card('new_code').actions, ['retry', 'computer']);
+});
+
+test('notice 6: unsafe folder, by kind, with ~ and Change folder for a team', () => {
+ const c = card('unsafe_folder', { folder: '/home/oleks', folder_from: 'team', team_id: 't1', team_name: 'Checkout', unsafe_kind: 'home' });
+ assert.equal(c.first, 'Ada didn’t reply: Claude can’t use this folder inside the VM.');
+ assert.equal(plain(c), '~ is your home folder. Inside the VM, Claude would see all your files and sign-ins. Pick a project folder for @Checkout instead, then Retry.');
+ assert.equal(c.reason[0].folder, true);
+ assert.equal(c.safety, 'unsafe');
+ assert.deepEqual(c.actions, ['change_folder', 'retry']);
+ assert.equal((plain(c).match(/Pick a project folder/g) || []).length, 1);
+ assert.doesNotMatch(plain(c), /the computer/);
+
+ const kinds = {
+ contains_home: /holds your home folder/,
+ root: /holds your home folder/,
+ sign_ins: /holds sign-ins, like your SSH keys/,
+ kwant_data: /holds kwant’s own data/,
+ docker: /Docker’s control socket/,
+ mystery: /^This folder holds your home folder or sign-ins/,
+ };
+ for (const [k, re] of Object.entries(kinds)) {
+ const x = card('unsafe_folder', { folder: '/srv/x', folder_from: 'bot', unsafe_kind: k });
+ assert.match(plain(x), re, k);
+ assert.match(plain(x), /Pick a project folder instead, then Retry\.$/);
+ assert.deepEqual(x.actions, ['retry'], `${k}: no Change folder for a bot folder`);
+ }
+ assert.match(plain(card('unsafe_folder', { folder: '/x', folder_from: 'goal', unsafe_kind: 'home' })), /for this goal instead/);
+ // No folder at all: still reads, no path
+ assert.match(plain(card('unsafe_folder', { unsafe_kind: 'home' })), /^This folder is your home folder/);
+ const html = render(notice('n', 'unsafe_folder', { folder: '/Users/oleks/code', folder_from: 'team', team_id: 't1', team_name: 'Checkout', unsafe_kind: 'sign_ins' }));
+ assert.match(html, /data-isolation-folder[^>]*>~\/code</);
+ assert.match(html, /data-isolation-action="change_folder"[\s\S]*data-isolation-action="retry"/);
+});
+
+test('notice 6b: the shared folder has no path and asks for the team’s own folder', () => {
+ const c = card('unsafe_folder', { folder: '/var/lib/kwant/workspace', folder_from: 'team', team_id: 't1', team_name: 'Checkout', unsafe_kind: 'shared_folder' });
+ assert.equal(c.row, 'unsafe_folder:shared_folder');
+ assert.doesNotMatch(plain(c), /\/var\/lib/);
+ assert.match(plain(c), /Give @Checkout its own folder, then Retry\.$/);
+ assert.equal(c.safety, 'unsafe_shared');
+ assert.deepEqual(c.actions, ['change_folder', 'retry']);
+ assert.match(plain(card('unsafe_folder', { unsafe_kind: 'shared_folder' })), /Give this team its own folder, then Retry\.$/);
+});
+
+test('notice 7: Codex or Grok in a folder Claude used', () => {
+ const team = card('folder_used_by_isolated_bot', { engine: 'codex', folder: '/home/oleks/shop', folder_from: 'team', team_id: 't1', team_name: 'Checkout' });
+ assert.equal(team.first, 'Ada didn’t reply: Codex won’t run in a folder Claude used inside the VM.');
+ assert.match(plain(team), /left settings in ~\/shop that Codex would load/);
+ assert.match(plain(team), /Switch Ada to Claude, or pick another folder for @Checkout, then Retry\.$/);
+ assert.deepEqual(team.actions, ['edit_bot', 'change_folder']);
+ assert.equal(team.safety, 'folder_used');
+
+ const bot = card('folder_used_by_isolated_bot', { engine: 'grok', folder: '/x', folder_from: 'bot' });
+ assert.match(plain(bot), /^Ada used this folder as Claude inside the VM.*Grok would load.*Switch Ada back to Claude to keep working here\.$/);
+ assert.deepEqual(bot.actions, ['edit_bot', 'retry']);
+
+ const other = card('folder_used_by_isolated_bot', { engine: 'codex', folder_from: 'goal' });
+ assert.match(plain(other), /Switch Ada to Claude, then Retry\.$/);
+ const html = render(notice('n', 'folder_used_by_isolated_bot', { engine: 'codex', folder_from: 'bot' }));
+ assert.match(html, /Edit Ada/);
+});
+
+test('buttons: Retry only on the newest notice; the first shown button is primary', () => {
+ const noRetry = render(notice('n', 'docker_unavailable'), { retry: null });
+ assert.doesNotMatch(noRetry, /data-isolation-action="retry"/);
+ assert.match(noRetry, /data-isolation-action="computer"[^>]*class="[^"]*bg-amber-500\/15/);
+ const both = render(notice('n', 'docker_unavailable'));
+ assert.match(both, /data-isolation-action="retry"[^>]*class="[^"]*bg-amber-500\/15/);
+ assert.match(both, /data-isolation-action="computer"[^>]*class="[^"]*border-zinc-700/);
+});
+
+test('retryTargets counts isolation and limit notices', () => {
+ const t = m.retryTargets([user('u1', 'build it'), notice('n1', 'docker_unavailable')]);
+ assert.equal(t.get('n1').text, 'build it');
+ assert.equal(m.retryTargets([user('u1', 'a'), notice('n1', 'preparing'), user('u2', 'b')]).size, 0);
+ assert.equal(m.retryTargets([user('u1', 'a'), limitNote('l1')]).has('l1'), true);
+ // Only the newest one
+ const two = m.retryTargets([user('u1', 'a'), notice('n1', 'preparing'), notice('n2', 'docker_unavailable')]);
+ assert.deepEqual([...two.keys()], ['n2']);
+});
+
+test('notice 5: the request limit, with Continue only when allowed', () => {
+ const meta = m.parseRequestLimit(limitNote('l1', 200));
+ const copy = m.requestLimitText(meta);
+ assert.equal(copy.first, 'Ada paused after 200 requests to Claude in this reply.');
+ assert.match(copy.body, /bot stuck in a loop/);
+ const html = m.renderToStaticMarkup(m.createElement(m.RequestLimitNotice, { messageId: 'l1', meta, canContinue: true, onSend: () => {} }));
+ assert.match(html, /data-request-limit-action="continue"/);
+ assert.match(html, />Continue</);
+ const none = m.renderToStaticMarkup(m.createElement(m.RequestLimitNotice, { messageId: 'l1', meta, canContinue: false, onSend: () => {} }));
+ assert.doesNotMatch(none, /data-request-limit-action/);
+ assert.equal(m.CONTINUE_TEXT, 'Continue where you left off.');
+});
+
+test('shortPath turns the home folder into ~', () => {
+ assert.equal(m.shortPath('/home/oleks'), '~');
+ assert.equal(m.shortPath('/home/oleks/shop'), '~/shop');
+ assert.equal(m.shortPath('/Users/o/x'), '~/x');
+ assert.equal(m.shortPath('/srv/home/x'), '/srv/home/x');
+});
diff --git a/frontend/tests/missionAutofix.test.mjs b/frontend/tests/missionAutofix.test.mjs
index 268f9306..080adbda 100644
--- a/frontend/tests/missionAutofix.test.mjs
+++ b/frontend/tests/missionAutofix.test.mjs
@@ -273,6 +273,9 @@ test('restore errors and results read plainly', () => {
assert.match(m.restoreErrorText(err('stale_preview')), /Files changed since this preview/);
assert.match(m.restoreErrorText(err('not_held')), /isn’t on hold any more/);
assert.match(m.restoreErrorText(err('unknown_force_path', 422)), /isn’t in the preview any more/);
+ assert.match(m.restoreErrorText(err('checkpoint_failed', 500)), /^The safety checkpoint couldn’t be taken/);
+ const moved = new m.MissionError("the task's folder is missing, moved or a symlink now, so the safety checkpoint couldn't be taken and nothing was restored", 500, 'checkpoint_failed');
+ assert.equal(m.restoreErrorText(moved), 'Couldn’t restore: the task’s folder was moved or replaced. Nothing was changed.');
assert.match(m.autofixErrorText(err('over_recovery_budget')), /retry budget/);
const r = { restored: ['a.md', 'b.md'], deleted: ['c.md'], failed: [], task: task({ state: 'ready', held_at: '2026-10-27T12:00:00Z' }) };
assert.equal(m.restoredText(r, false), 'Restored: 2 files put back, 1 file removed. It’s on hold until you press Run.');
diff --git a/frontend/tests/threads.test.mjs b/frontend/tests/threads.test.mjs
index 2878d224..6b57330b 100644
--- a/frontend/tests/threads.test.mjs
+++ b/frontend/tests/threads.test.mjs
@@ -265,3 +265,20 @@ test('long answers collapse behind a toggle', () => {
const html = card.render(props({ meta: t.parseDelegationMeta(metaJson()), text: 'x '.repeat(1000) }));
assert.match(html, /aria-expanded="false"[^>]*>Show the whole answer/);
});
+
+test('vm_busy (#446): its own line across bots, slots kept, cleared by the second turn_started', () => {
+ let m = t.hydrateTurns([]);
+ m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'q1', kwant_id: 'a', context_id: 'a', position: 1, reason: 'vm_busy', slots: 2 }));
+ m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'q2', kwant_id: 'b', context_id: 'b', position: 2, reason: 'vm_busy', slots: 2 }));
+ m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'q3', kwant_id: 'b', context_id: 'b', position: 1, reason: 'agent_busy', slots: 9 }));
+ assert.equal(m.q1.reason, 'vm_busy');
+ assert.equal(m.q1.slots, 2);
+ assert.equal(m.q3.slots, undefined, 'slots only with vm_busy');
+ assert.equal(t.queuePosition(m, 'q2'), 2, 'the VM line spans bots');
+ m = t.applyTurnEvent(m, ev('turn_started', { turn_id: 'q1', kwant_id: 'a', context_id: 'a' }));
+ assert.equal(m.q1.state, 'running');
+ assert.equal(m.q1.reason, undefined);
+ assert.equal(t.queuePosition(m, 'q2'), 1);
+ m = t.applyTurnEvent(m, ev('turn_queued', { turn_id: 'q4', kwant_id: 'c', context_id: 'c', reason: 'something_new' }));
+ assert.equal(m.q4.reason, 'agent_busy', 'unknown reasons read as the bot being busy');
+});
diff --git a/frontend/tests/wording.test.mjs b/frontend/tests/wording.test.mjs
index d875791b..a5c467e2 100644
--- a/frontend/tests/wording.test.mjs
+++ b/frontend/tests/wording.test.mjs
@@ -24,7 +24,9 @@ const ALLOWED = /\bkwant bots?\b|\bcoding agents?\b|\b(?:exec kwnt )?kwnt (?:tok
const MAESTRO = /\bAgent Maestro\b/g;
// T/D preview sheet (0.7.7): Mira's review-396-397 must-fix 7 and Ada's deviation-4 ruling keep "kwant"
// as the subject in these three sentences only.
-const RULED = /\bso kwant can read\b|\bmanifests kwant knows\b|\bnames kwant knows\b/g;
+// Run Claude inside the VM (0.7.7): Mira's ui-check-450 must-fix 2 names kwant, the program on the computer,
+// in these settings and chat-notice sentences ("Restart kwant" is what a person on a phone has to do).
+const RULED = /\bso kwant can read\b|\bmanifests kwant knows\b|\bnames kwant knows\b|\bkwant’s (?:browser|log|own data)\b|\bkwant (?:adds it|couldn’t|won’t share|keeps|is running as root|can’t pass)\b|\b[Rr]estart kwant\b|\bStart kwant as\b/g;
/** Whether a literal reads like text a person sees (a sentence, or a capitalised word). */
const looksVisible = (text, node) => {