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.

Parallel Universe panel: scenarios, runs and labelled comparison

Lin (kwant bot)c3911be41d70
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 1f9b8b3a..bf54813b 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -16,6 +16,7 @@ import { HireCard, type HireDecision } from './components/HireCard';
import type { RoutineFocus } from './components/RoutinesPanel';
import { AwayPage } from './components/AwayView';
import { LooseEndsPage } from './components/LooseEndsView';
+import { ParallelPage } from './components/ParallelUniverseView';
import { AlertTriangle, Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';
import { ChatApproval, OpenChat, approvalFromEvent, approvalsForChat, approvalsFromAway, syncApprovals, upsertApproval, withoutApproval } from './approvals';
import type { AgentFormData } from './components/NewAgentModal';
@@ -261,6 +262,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// "While you were away": open instead of a chat, and its unseen count for the sidebar badge.
const [showAway, setShowAway] = useState(false);
const [showLoose, setShowLoose] = useState(false);
+ const [showParallel, setShowParallel] = useState(false);
const [awayCount, setAwayCount] = useState(0);
const awaySinceRef = useRef<string | null>(null);
const awayTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
@@ -1177,6 +1179,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setOpenThreadId(null);
setShowAway(false);
setShowLoose(false);
+ setShowParallel(false);
setPhoneView('chat');
setSelectedTeamId(team.id);
const targetChannel = channels.find(
@@ -1218,6 +1221,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setOpenThreadId(null);
setShowAway(false);
setShowLoose(false);
+ setShowParallel(false);
setPhoneView('chat');
setSelectedId(channel.id);
selectedIdRef.current = channel.id;
@@ -1235,6 +1239,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setOpenThreadId(null);
setShowAway(false);
setShowLoose(false);
+ setShowParallel(false);
setPhoneView('chat');
setSelectedId(kwant.id);
selectedIdRef.current = kwant.id;
@@ -1292,6 +1297,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
knownThreadsRef.current.add(threadId);
setShowAway(false);
setShowLoose(false);
+ setShowParallel(false);
if (selectedIdRef.current !== kwant.id || isChannelRef.current) handleSelectKwant(kwant);
else playSfx('click');
setOpenThreadId(threadId);
@@ -1306,6 +1312,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (!ok) return pushToast('That chat no longer exists.');
setShowAway(false);
setShowLoose(false);
+ setShowParallel(false);
};
const openDirectChat = () => {
@@ -2420,8 +2427,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
awayCount={awayCount}
awayActive={showAway}
looseActive={showLoose}
+ parallelActive={showParallel}
+ onOpenParallel={() => {
+ setShowParallel(true);
+ setShowLoose(false);
+ setShowAway(false);
+ setPhoneView('chat');
+ playSfx('click');
+ }}
onOpenLooseEnds={() => {
setShowLoose(true);
+ setShowParallel(false);
setShowAway(false);
setPhoneView('chat');
playSfx('click');
@@ -2429,6 +2445,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onOpenAway={() => {
setShowAway(true);
setShowLoose(false);
+ setShowParallel(false);
setPhoneView('chat');
playSfx('click');
}}
@@ -2440,6 +2457,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onBack={isPhone ? () => { setShowAway(false); setPhoneView('list'); } : undefined}
/>
);
+ const parallel = <ParallelPage onBack={isPhone ? () => { setShowParallel(false); setPhoneView('list'); } : undefined} />;
const loose = <LooseEndsPage onBack={isPhone ? () => { setShowLoose(false); setPhoneView('list'); } : undefined} onOpenChat={openThread} />;
const chat = (
<ChatView
@@ -2536,7 +2554,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
contextKey={openCtx}
/>
);
- const mainPane = needsSetup ? setupChecklist : showLoose ? loose : showAway ? away : !loaded ? (
+ const mainPane = needsSetup ? setupChecklist : showParallel ? parallel : showLoose ? loose : showAway ? away : !loaded ? (
<main className="flex-1 flex items-center justify-center text-xs text-zinc-500">
<Loader2 size={14} className="mr-2 animate-spin motion-reduce:animate-none" aria-hidden="true" /> Opening {space.name}…
</main>
@@ -2585,6 +2603,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (t.id === 'inbox') {
setShowAway(true);
setShowLoose(false);
+ setShowParallel(false);
setPhoneView('chat');
return;
}
diff --git a/frontend/src/components/ParallelUniverseView.tsx b/frontend/src/components/ParallelUniverseView.tsx
new file mode 100644
index 00000000..0e130ae2
--- /dev/null
+++ b/frontend/src/components/ParallelUniverseView.tsx
@@ -0,0 +1,953 @@
+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { AlertTriangle, ChevronLeft, ExternalLink, Loader2, Pencil, Play, Plus, RefreshCw, Split, Trash2, X } from 'lucide-react';
+import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
+import { playSfx } from '../audio/chiptune';
+import {
+ FormErrors,
+ INTERRUPTED_TEXT,
+ LIMIT_RANGES,
+ LimitKey,
+ MAX_OPTIONS,
+ MAX_TOTAL_MEMORY_MB,
+ OptionDraft,
+ OptionReport,
+ ParallelError,
+ Price,
+ Report,
+ Run,
+ Scenario,
+ ScenarioBody,
+ ScenarioDraft,
+ Tone,
+ branchStatus,
+ draftFrom,
+ emptyOption,
+ emptyScenario,
+ figureKind,
+ formatValue,
+ leaderLabel,
+ metricLabel,
+ noteLabel,
+ parallelApi,
+ reservedMemory,
+ runProgress,
+ runStatus,
+ safeHttps,
+ sourceHost,
+ validateScenario,
+} from '../parallelUniverse';
+
+const TONES: Record<Tone, string> = {
+ emerald: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200',
+ amber: 'border-amber-500/30 bg-amber-500/10 text-amber-200',
+ violet: 'border-violet-500/30 bg-violet-500/10 text-violet-200',
+ rose: 'border-rose-500/30 bg-rose-500/10 text-rose-200',
+ sky: 'border-sky-500/30 bg-sky-500/10 text-sky-200',
+ zinc: 'border-zinc-700 bg-zinc-800 text-zinc-300',
+};
+
+const actionBtn =
+ 'inline-flex items-center gap-1.5 min-h-[36px] sm:min-h-[30px] px-3 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+const quietBtn = `${actionBtn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600`;
+const mainBtn = `${actionBtn} bg-sky-600 text-white hover:bg-sky-500`;
+const field =
+ 'w-full min-h-[36px] px-2.5 py-1.5 bg-zinc-950 border border-zinc-800 rounded-lg text-xs text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus:border-sky-500 aria-[invalid=true]:border-rose-500/60';
+const card = 'rounded-xl border border-zinc-800 bg-zinc-900/40 p-3 sm:p-4';
+
+const Badge: React.FC<{ tone: Tone; children: React.ReactNode; title?: string }> = ({ tone, children, title }) => (
+ <span title={title} className={`inline-flex items-center shrink-0 px-1.5 py-px rounded border text-[10px] font-semibold uppercase tracking-wide ${TONES[tone]}`}>
+ {children}
+ </span>
+);
+
+/** The Measured / Estimate / Guess label every number carries. */
+export const KindBadge: React.FC<{ tag: string }> = ({ tag }) => {
+ const k = figureKind(tag);
+ return (
+ <Badge tone={k.tone} title={k.hint}>
+ {k.label}
+ </Badge>
+ );
+};
+
+/** Calm notices: amber for things to know, emerald for done. */
+const Notice: React.FC<{ text: string; error?: boolean }> = ({ text, error = false }) => (
+ <p className={`px-3 py-2 rounded-lg border text-xs ${error ? 'border-amber-500/30 bg-amber-500/10 text-amber-200' : 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200'}`}>{text}</p>
+);
+
+// ---------- Scenario list ----------
+
+export const ScenarioList: React.FC<{
+ scenarios: Scenario[];
+ onOpen: (s: Scenario) => void;
+ onNew: () => void;
+}> = ({ scenarios, onOpen, onNew }) =>
+ scenarios.length === 0 ? (
+ <div className="py-12 flex flex-col items-center text-center gap-2" data-empty>
+ <Split size={28} className="text-sky-400" aria-hidden="true" />
+ <p className="text-sm font-medium text-zinc-200">No scenarios yet</p>
+ <p className="text-xs text-zinc-500 max-w-xs">
+ A scenario is one question, like “VPS or serverless?”, with up to {MAX_OPTIONS} ways to run your app. Each one is tried here and compared.
+ </p>
+ <button type="button" onClick={onNew} className={`${mainBtn} mt-2`}>
+ <Plus size={13} aria-hidden="true" /> New scenario
+ </button>
+ </div>
+ ) : (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-xs font-semibold text-zinc-300">Scenarios</h3>
+ <button type="button" onClick={onNew} className={quietBtn}>
+ <Plus size={13} aria-hidden="true" /> New scenario
+ </button>
+ </div>
+ <ul className="space-y-2">
+ {scenarios.map((s) => (
+ <li key={s.id}>
+ <button
+ type="button"
+ onClick={() => onOpen(s)}
+ className={`${card} w-full text-left hover:border-zinc-700 hover:bg-zinc-900/70 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500`}
+ >
+ <span className="block text-sm font-medium text-zinc-100 break-words">{s.title}</span>
+ {s.question && <span className="block mt-0.5 text-xs text-zinc-400 break-words line-clamp-2">{s.question}</span>}
+ <span className="block mt-1.5 text-[11px] text-zinc-500 break-words">
+ {s.options.length} option{s.options.length === 1 ? '' : 's'}: {s.options.map((o) => o.label).join(' · ')}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+
+// ---------- Form ----------
+
+const Field: React.FC<{ label: string; error?: string; hint?: string; children: (id: string, describedBy: string | undefined) => React.ReactNode; className?: string }> = ({
+ label,
+ error,
+ hint,
+ children,
+ className = '',
+}) => {
+ const id = useId();
+ const msg = `${id}-msg`;
+ return (
+ <div className={className}>
+ <label htmlFor={id} className="block text-[11px] font-medium text-zinc-400 mb-1">
+ {label}
+ </label>
+ {children(id, error || hint ? msg : undefined)}
+ {error ? (
+ <p id={msg} className="mt-1 text-[11px] text-rose-300">
+ {error}
+ </p>
+ ) : hint ? (
+ <p id={msg} className="mt-1 text-[11px] text-zinc-500">
+ {hint}
+ </p>
+ ) : null}
+ </div>
+ );
+};
+
+const TextInput: React.FC<{
+ label: string;
+ value: string;
+ onChange: (v: string) => void;
+ error?: string;
+ hint?: string;
+ placeholder?: string;
+ inputMode?: 'numeric' | 'decimal' | 'text';
+ className?: string;
+}> = ({ label, value, onChange, error, hint, placeholder, inputMode = 'text', className }) => (
+ <Field label={label} error={error} hint={hint} className={className}>
+ {(id, describedBy) => (
+ <input
+ id={id}
+ className={field}
+ value={value}
+ placeholder={placeholder}
+ inputMode={inputMode}
+ aria-invalid={error ? true : undefined}
+ aria-describedby={describedBy}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ )}
+ </Field>
+);
+
+const LIMIT_UNITS: Record<LimitKey, string> = { cpus: 'CPUs', memory_mb: 'Memory (MB)', pids: 'Processes', timeout_secs: 'Time limit (s)' };
+
+const OptionFields: React.FC<{
+ o: OptionDraft;
+ i: number;
+ errors: FormErrors;
+ prices: Price[] | null;
+ canRemove: boolean;
+ onChange: (o: OptionDraft) => void;
+ onRemove: () => void;
+}> = ({ o, i, errors, prices, canRemove, onChange, onRemove }) => {
+ const e = (f: string) => errors[`options.${i}.${f}`];
+ const set = (patch: Partial<OptionDraft>) => onChange({ ...o, ...patch });
+ const planId = useId();
+ return (
+ <fieldset className={`${card} space-y-3`}>
+ <legend className="sr-only">Option {i + 1}</legend>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-semibold text-zinc-300">Option {i + 1}</span>
+ {canRemove && (
+ <button type="button" onClick={onRemove} className={`${quietBtn} !min-h-[32px]`} aria-label={`Remove option ${i + 1}`}>
+ <Trash2 size={12} aria-hidden="true" /> Remove
+ </button>
+ )}
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <TextInput label="Name" value={o.label} onChange={(v) => set({ label: v })} error={e('label')} placeholder="DigitalOcean droplet" />
+ <div>
+ <label htmlFor={planId} className="block text-[11px] font-medium text-zinc-400 mb-1">
+ Price plan
+ </label>
+ <select
+ id={planId}
+ className={field}
+ value={o.plan}
+ aria-invalid={e('plan') ? true : undefined}
+ onChange={(ev) => set({ plan: ev.target.value })}
+ >
+ <option value="">None — cost will be a guess</option>
+ {(prices ?? []).map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.provider} · {p.plan} ({p.monthly > 0 ? `${p.monthly.toFixed(2)} ${p.currency}/mo` : `pay per use, ${p.currency}`})
+ </option>
+ ))}
+ {o.plan && prices && !prices.some((p) => p.id === o.plan) && <option value={o.plan}>{o.plan}</option>}
+ </select>
+ {e('plan') && <p className="mt-1 text-[11px] text-rose-300">{e('plan')}</p>}
+ </div>
+ </div>
+
+ <div role="radiogroup" aria-label={`Option ${i + 1}: where the app comes from`} className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-zinc-300">
+ {(
+ [
+ ['image', 'An image on this server'],
+ ['context', 'Build from a folder'],
+ ] as const
+ ).map(([v, l]) => (
+ <label key={v} className="inline-flex items-center gap-1.5 min-h-[32px] cursor-pointer">
+ <input type="radio" name={`source-${planId}`} checked={o.source === v} onChange={() => set({ source: v })} className="accent-sky-500" />
+ {l}
+ </label>
+ ))}
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {o.source === 'image' ? (
+ <TextInput label="Docker image" value={o.image} onChange={(v) => set({ image: v })} error={e('image')} placeholder="myapp:latest" />
+ ) : (
+ <>
+ <TextInput label="Folder" value={o.context} onChange={(v) => set({ context: v })} error={e('context')} placeholder="/home/me/myapp" />
+ <TextInput label="Dockerfile (optional)" value={o.dockerfile} onChange={(v) => set({ dockerfile: v })} error={e('dockerfile')} placeholder="Dockerfile" />
+ </>
+ )}
+ <div className="grid grid-cols-2 gap-3">
+ <TextInput label="Port" value={o.port} onChange={(v) => set({ port: v })} error={e('port')} inputMode="numeric" />
+ <TextInput label="Health path" value={o.health_path} onChange={(v) => set({ health_path: v })} error={e('health_path')} />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ {(Object.keys(LIMIT_RANGES) as LimitKey[]).map((k) => (
+ <TextInput
+ key={k}
+ label={LIMIT_UNITS[k]}
+ value={o[k]}
+ onChange={(v) => set({ [k]: v } as Partial<OptionDraft>)}
+ error={e(k)}
+ hint={e(k) ? undefined : `${LIMIT_RANGES[k].min}–${LIMIT_RANGES[k].max}`}
+ inputMode={k === 'cpus' ? 'decimal' : 'numeric'}
+ />
+ ))}
+ </div>
+
+ <details className="group">
+ <summary className="cursor-pointer text-[11px] text-zinc-400 hover:text-zinc-200 min-h-[32px] flex items-center">Your notes on running and rolling back (optional)</summary>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-2">
+ {(
+ [
+ ['ops_notes', 'Running it'],
+ ['rollback_notes', 'Rolling back'],
+ ] as const
+ ).map(([k, l]) => (
+ <Field key={k} label={l} error={k === 'ops_notes' ? e('ops_notes') : undefined}>
+ {(id, d) => <textarea id={id} aria-describedby={d} rows={3} className={`${field} resize-y`} value={o[k]} onChange={(ev) => set({ [k]: ev.target.value } as Partial<OptionDraft>)} />}
+ </Field>
+ ))}
+ </div>
+ <p className="mt-1 text-[11px] text-zinc-500">These show in the comparison labelled as a guess. Without them you get a general note for the plan.</p>
+ </details>
+ </fieldset>
+ );
+};
+
+export const ScenarioForm: React.FC<{
+ initial: ScenarioDraft;
+ editing: boolean;
+ prices: Price[] | null;
+ saving: boolean;
+ serverError: string | null;
+ /** Tests show the errors without a click. */
+ initialShowErrors?: boolean;
+ onSave: (body: ScenarioBody) => void;
+ onCancel: () => void;
+}> = ({ initial, editing, prices, saving, serverError, initialShowErrors = false, onSave, onCancel }) => {
+ const [d, setD] = useState<ScenarioDraft>(initial);
+ const [showErrors, setShowErrors] = useState(initialShowErrors);
+ const planIds = prices ? new Set(prices.map((p) => p.id)) : undefined;
+ const { errors, body } = validateScenario(d, planIds);
+ const shown = showErrors ? errors : {};
+ const total = reservedMemory(d);
+ const set = (patch: Partial<ScenarioDraft>) => setD((x) => ({ ...x, ...patch }));
+ const errorCount = Object.keys(errors).length;
+
+ const submit = (ev: React.FormEvent) => {
+ ev.preventDefault();
+ setShowErrors(true);
+ if (body) onSave(body);
+ };
+
+ return (
+ <form onSubmit={submit} noValidate className="space-y-4" aria-label={editing ? 'Edit scenario' : 'New scenario'}>
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-sm font-semibold text-zinc-100">{editing ? 'Edit scenario' : 'New scenario'}</h3>
+ </div>
+
+ <div className={`${card} space-y-3`}>
+ <TextInput label="Name" value={d.title} onChange={(v) => set({ title: v })} error={shown.title} placeholder="Move booktun.ing off managed hosting?" />
+ <Field label="The question (optional)" error={shown.question}>
+ {(id, desc) => (
+ <textarea
+ id={id}
+ aria-describedby={desc}
+ rows={2}
+ className={`${field} resize-y`}
+ value={d.question}
+ placeholder="Stay where we are, move to a VPS or go serverless?"
+ onChange={(e) => set({ question: e.target.value })}
+ />
+ )}
+ </Field>
+ </div>
+
+ <fieldset className={`${card} space-y-3`}>
+ <legend className="sr-only">Traffic and load test</legend>
+ <p className="text-xs font-semibold text-zinc-300">Traffic, for the cost estimate</p>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ <TextInput label="Requests a month" value={d.monthly_requests} onChange={(v) => set({ monthly_requests: v })} error={shown.monthly_requests} inputMode="numeric" />
+ <TextInput label="Busiest req/s" value={d.peak_rps} onChange={(v) => set({ peak_rps: v })} error={shown.peak_rps} inputMode="decimal" />
+ <TextInput label="Response size (KB)" value={d.avg_response_kb} onChange={(v) => set({ avg_response_kb: v })} error={shown.avg_response_kb} inputMode="decimal" />
+ <TextInput label="Work per request (ms)" value={d.avg_duration_ms} onChange={(v) => set({ avg_duration_ms: v })} error={shown.avg_duration_ms} inputMode="decimal" />
+ </div>
+ <p className="text-xs font-semibold text-zinc-300 pt-1">Load test, run here</p>
+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
+ <TextInput label="Requests" value={d.load_requests} onChange={(v) => set({ load_requests: v })} error={shown.load_requests} inputMode="numeric" />
+ <TextInput label="At once" value={d.load_concurrency} onChange={(v) => set({ load_concurrency: v })} error={shown.load_concurrency} inputMode="numeric" />
+ <TextInput label="Path" value={d.load_path} onChange={(v) => set({ load_path: v })} error={shown.load_path} className="col-span-2 sm:col-span-1" />
+ </div>
+ </fieldset>
+
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="text-xs font-semibold text-zinc-300">
+ Options <span className="font-normal text-zinc-500">({d.options.length} of {MAX_OPTIONS})</span>
+ </p>
+ <p className={`text-[11px] ${total > MAX_TOTAL_MEMORY_MB ? 'text-rose-300' : 'text-zinc-500'}`} data-memory-total>
+ Memory reserved: {total} of {MAX_TOTAL_MEMORY_MB} MB
+ </p>
+ </div>
+ {shown.memory_total && (
+ <p role="alert" className="text-[11px] text-rose-300">
+ {shown.memory_total}
+ </p>
+ )}
+ {shown.options && <p className="text-[11px] text-rose-300">{shown.options}</p>}
+ {d.options.map((o, i) => (
+ <OptionFields
+ key={i}
+ o={o}
+ i={i}
+ errors={shown}
+ prices={prices}
+ canRemove={d.options.length > 1}
+ onChange={(next) => set({ options: d.options.map((x, j) => (j === i ? next : x)) })}
+ onRemove={() => set({ options: d.options.filter((_, j) => j !== i) })}
+ />
+ ))}
+ {d.options.length < MAX_OPTIONS ? (
+ <button type="button" onClick={() => set({ options: [...d.options, emptyOption()] })} className={quietBtn}>
+ <Plus size={13} aria-hidden="true" /> Add an option
+ </button>
+ ) : (
+ <p className="text-[11px] text-zinc-500">That’s the most options a scenario can have.</p>
+ )}
+ </div>
+
+ <div className={`${card} space-y-1`}>
+ <label className="flex items-start gap-2 text-xs text-zinc-200 cursor-pointer min-h-[32px]">
+ <input type="checkbox" checked={d.build_network} onChange={(e) => set({ build_network: e.target.checked })} className="mt-0.5 accent-sky-500" />
+ <span>Let the build step use the internet</span>
+ </label>
+ <p className={`text-[11px] pl-6 ${d.build_network ? 'text-amber-200' : 'text-zinc-500'}`}>
+ Only while building, for apps that download packages. The app itself is always tested offline, and results will say the build had internet.
+ </p>
+ </div>
+
+ <div role="status" aria-live="polite">
+ {serverError && <Notice text={`Couldn’t save: ${serverError}`} error />}
+ {showErrors && errorCount > 0 && <Notice text={`Fix ${errorCount === 1 ? 'the highlighted field' : `the ${errorCount} highlighted fields`} to save.`} error />}
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ <button type="submit" disabled={saving} className={mainBtn}>
+ {saving && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {editing ? 'Save changes' : 'Save scenario'}
+ </button>
+ <button type="button" onClick={onCancel} className={quietBtn}>
+ Cancel
+ </button>
+ </div>
+ </form>
+ );
+};
+
+// ---------- Run and comparison ----------
+
+export const RunProgress: React.FC<{ run: Run }> = ({ run }) => {
+ const p = runProgress(run);
+ const st = runStatus(run.status);
+ return (
+ <div className={`${card} space-y-2`} data-run={run.status}>
+ <div className="flex flex-wrap items-center gap-2">
+ <Badge tone={st.tone}>{st.label}</Badge>
+ <span className="text-xs text-zinc-300">{p.text}</span>
+ {run.status === 'running' && <Loader2 size={13} className="text-sky-400 animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ </div>
+ {run.status === 'running' && (
+ <div className="h-1.5 rounded-full bg-zinc-800 overflow-hidden" role="progressbar" aria-label="Run progress" aria-valuemin={0} aria-valuemax={p.total} aria-valuenow={p.done}>
+ <div className="h-full bg-sky-500 transition-all" style={{ width: `${p.total ? (p.done / p.total) * 100 : 0}%` }} />
+ </div>
+ )}
+ {run.status === 'interrupted' && (
+ <p className="flex items-start gap-1.5 text-xs text-rose-200">
+ <AlertTriangle size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
+ {INTERRUPTED_TEXT}
+ </p>
+ )}
+ <ul className="space-y-1">
+ {run.branches.map((b) => {
+ const bs = branchStatus(b.status);
+ return (
+ <li key={b.key} className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs">
+ <Badge tone={bs.tone}>{bs.label}</Badge>
+ <span className="text-zinc-200 break-words min-w-0">{b.label}</span>
+ {b.status === 'failed' && (b.error || b.error_code) && <span className="text-rose-300 break-words min-w-0 basis-full sm:basis-auto">{b.error || b.error_code}</span>}
+ </li>
+ );
+ })}
+ </ul>
+ {run.cleanup_errors.length > 0 && <p className="text-[11px] text-amber-200 break-words">Cleanup: {run.cleanup_errors.join('; ')}</p>}
+ </div>
+ );
+};
+
+const FigureRow: React.FC<{ f: OptionReport['measured'][number] }> = ({ f }) => (
+ <li className="py-1.5 border-t border-zinc-800/80 first:border-t-0">
+ <div className="flex items-center gap-2 text-xs">
+ <span className="text-zinc-400 flex-1 min-w-0">{metricLabel(f.metric)}</span>
+ <span className="font-mono text-zinc-100 tabular-nums">{formatValue(f.value, f.unit)}</span>
+ <KindBadge tag={f.tag} />
+ </div>
+ {f.tag === 'verified' && (
+ <details className="mt-1">
+ <summary className="cursor-pointer text-[11px] text-zinc-500 hover:text-zinc-300">How it was measured</summary>
+ <code className="block mt-1 p-2 rounded bg-zinc-950 border border-zinc-800 text-[10px] text-zinc-300 whitespace-pre-wrap break-all">{f.command}</code>
+ </details>
+ )}
+ </li>
+);
+
+const CostRow: React.FC<{ f: OptionReport['cost'] }> = ({ f }) => (
+ <div className="pt-2 space-y-1">
+ <div className="flex items-center gap-2 text-xs">
+ <span className="text-zinc-400 flex-1 min-w-0">{metricLabel(f.metric)}</span>
+ {f.tag === 'speculation' ? <span className="text-zinc-400 italic">unknown</span> : <span className="font-mono text-zinc-100 tabular-nums">about {formatValue(f.value, f.unit)}</span>}
+ <KindBadge tag={f.tag} />
+ </div>
+ {f.tag === 'estimate' && (
+ <p className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] text-zinc-500">
+ <span>Prices as of {f.as_of} from</span>
+ {safeHttps(f.source_url) ? (
+ <a href={f.source_url} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-0.5 text-sky-300 hover:text-sky-200 underline underline-offset-2">
+ {sourceHost(f.source_url)}
+ <ExternalLink size={10} aria-hidden="true" />
+ <span className="sr-only">(opens in a new tab)</span>
+ </a>
+ ) : (
+ <span className="break-all">{f.source_url}</span>
+ )}
+ {f.stale && <Badge tone="rose">Price may be out of date</Badge>}
+ </p>
+ )}
+ {f.tag === 'speculation' && <p className="text-[11px] text-zinc-500">{f.note.charAt(0).toUpperCase() + f.note.slice(1)}.</p>}
+ </div>
+);
+
+export const OptionCard: React.FC<{ o: OptionReport; leaders: string[] }> = ({ o, leaders }) => {
+ const bs = branchStatus(o.status);
+ return (
+ <li className={`${card} space-y-2 min-w-0`}>
+ <div className="flex flex-wrap items-center gap-2">
+ <h4 className="text-sm font-medium text-zinc-100 break-words min-w-0">{o.label}</h4>
+ {o.status !== 'ok' && <Badge tone={bs.tone}>{bs.label}</Badge>}
+ {leaders.map((l) => (
+ <Badge key={l} tone="sky">
+ {l}
+ </Badge>
+ ))}
+ </div>
+ {o.status === 'failed' && <p className="text-xs text-rose-300 break-words">{o.error || o.error_code || 'This option failed.'}</p>}
+ {o.build_network_used && <p className="text-[11px] text-amber-200">The build step had internet.</p>}
+ {o.measured.length > 0 ? (
+ <ul>{o.measured.map((f) => <FigureRow key={f.metric} f={f} />)}</ul>
+ ) : (
+ <p className="text-xs text-zinc-500">Nothing measured{o.status === 'failed' ? ' — the test didn’t finish.' : '.'}</p>
+ )}
+ <CostRow f={o.cost} />
+ {o.notes.length > 0 && (
+ <ul className="pt-2 space-y-1.5">
+ {o.notes.map((n, i) => (
+ <li key={i} className="text-xs">
+ <div className="flex items-center gap-2">
+ <span className="text-zinc-400 flex-1">{noteLabel(n.criterion)}</span>
+ <KindBadge tag={n.tag} />
+ </div>
+ <p className="mt-0.5 text-zinc-300 break-words">{n.text}</p>
+ </li>
+ ))}
+ </ul>
+ )}
+ </li>
+ );
+};
+
+/** The comparison. Leaders show only when the report gives them; every figure keeps its label. */
+export const ComparisonReport: React.FC<{ report: Report }> = ({ report }) => {
+ const byOption = (key: string) => report.leaders.filter((l) => l.option === key).map((l) => leaderLabel(l.criterion));
+ const label = (key: string) => report.options.find((o) => o.key === key)?.label ?? key;
+ return (
+ <section aria-label="Comparison" className="space-y-3">
+ <h3 className="text-xs font-semibold text-zinc-300">Comparison</h3>
+ {report.leaders.length > 0 && (
+ <ul className="flex flex-col sm:flex-row sm:flex-wrap gap-2" aria-label="Leaders">
+ {report.leaders.map((l) => (
+ <li key={l.criterion} className="flex flex-wrap items-center gap-2 px-3 py-2 rounded-lg border border-zinc-800 bg-zinc-900/60 text-xs">
+ <span className="text-zinc-400">{leaderLabel(l.criterion)}:</span>
+ <span className="text-zinc-100 font-medium break-words">{label(l.option)}</span>
+ <span className="font-mono text-zinc-300">{l.criterion === 'cost' ? 'about ' : ''}{formatValue(l.value, l.unit)}</span>
+ <KindBadge tag={l.basis} />
+ </li>
+ ))}
+ </ul>
+ )}
+ <ul className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ {report.options.map((o) => (
+ <OptionCard key={o.key} o={o} leaders={byOption(o.key)} />
+ ))}
+ </ul>
+ {report.caveats.length > 0 && (
+ <div className="rounded-lg border border-amber-500/20 bg-amber-500/5 p-3">
+ <p className="text-xs font-medium text-amber-200 mb-1">Keep in mind</p>
+ <ul className="list-disc pl-4 space-y-0.5 text-[11px] text-amber-100/80">
+ {report.caveats.map((c, i) => (
+ <li key={i} className="break-words">
+ {c}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </section>
+ );
+};
+
+export const ScenarioDetail: React.FC<{
+ scenario: Scenario;
+ runs: Run[] | null;
+ current: { run: Run; report: Report } | null;
+ starting: boolean;
+ /** Another run is going (409 busy, or the server says so). */
+ busy: boolean;
+ notice: { text: string; error: boolean } | null;
+ onStart: () => void;
+ onPickRun: (id: string) => void;
+ onEdit: () => void;
+ onDelete: () => void;
+}> = ({ scenario, runs, current, starting, busy, notice, onStart, onPickRun, onEdit, onDelete }) => {
+ const live = current?.run.status === 'running';
+ const runPick = useId();
+ return (
+ <div className="space-y-4">
+ <div className="space-y-1">
+ <h3 className="text-base font-semibold text-zinc-100 break-words">{scenario.title}</h3>
+ {scenario.question && <p className="text-xs text-zinc-400 break-words">{scenario.question}</p>}
+ <p className="text-[11px] text-zinc-500 break-words">
+ {scenario.options.map((o) => o.label).join(' · ')}
+ {scenario.build_network && ' · build has internet'}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" onClick={onStart} disabled={starting || live || busy} className={mainBtn}>
+ {starting ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Play size={13} aria-hidden="true" />}
+ {live ? 'Running…' : 'Start a run'}
+ </button>
+ <button type="button" onClick={onEdit} disabled={live} className={quietBtn}>
+ <Pencil size={12} aria-hidden="true" /> Edit
+ </button>
+ <button type="button" onClick={onDelete} disabled={live} className={quietBtn}>
+ <Trash2 size={12} aria-hidden="true" /> Delete
+ </button>
+ </div>
+ <p className="text-[11px] text-zinc-500">Each option runs in a sealed-off container on this server, one after another. No cloud account is used and nothing is spent.</p>
+
+ <div role="status" aria-live="polite">
+ {busy && !live && <Notice text="Another run is going right now. You can start this one when it finishes." error />}
+ {notice && <Notice text={notice.text} error={notice.error} />}
+ </div>
+
+ {runs && runs.length > 1 && (
+ <div className="flex flex-wrap items-center gap-2">
+ <label htmlFor={runPick} className="text-[11px] text-zinc-400">
+ Run
+ </label>
+ <select id={runPick} className={`${field} !w-auto max-w-full`} value={current?.run.id ?? ''} onChange={(e) => onPickRun(e.target.value)}>
+ {runs.map((r) => (
+ <option key={r.id} value={r.id}>
+ {new Date(r.started_at).toLocaleString(undefined, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })} · {runStatus(r.status).label}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {runs && runs.length === 0 && !current && <p className="text-xs text-zinc-500">No runs yet. Start one to measure each option.</p>}
+
+ {current && (
+ <>
+ <RunProgress run={current.run} />
+ {current.report.options.some((o) => o.measured.length > 0 || o.status !== 'pending') && <ComparisonReport report={current.report} />}
+ </>
+ )}
+ </div>
+ );
+};
+
+// ---------- Page ----------
+
+type Screen = { kind: 'list' } | { kind: 'edit'; scenario: Scenario | null } | { kind: 'scenario'; id: string };
+
+export interface ParallelViewProps {
+ screen: Screen;
+ scenarios: Scenario[] | null;
+ loading: boolean;
+ error: string | null;
+ needsToken?: boolean;
+ body: React.ReactNode;
+ onRefresh: () => void;
+ onBack?: () => void;
+ onList: () => void;
+}
+
+/** The frame: header, sign-in and load errors; `body` is the current screen. */
+export const ParallelView: React.FC<ParallelViewProps> = ({ screen, scenarios, loading, error, needsToken = false, body, onRefresh, onBack, onList }) => (
+ <div className="flex-1 flex flex-col h-full bg-zinc-950 overflow-hidden">
+ <div className={`h-14 border-b border-zinc-800/80 ${onBack ? 'px-2' : 'px-4'} sm:px-6 flex items-center justify-between gap-3 bg-zinc-900/30 backdrop-blur-sm select-none`}>
+ {onBack && (
+ <button
+ type="button"
+ onClick={onBack}
+ aria-label="Back to chats"
+ className="shrink-0 p-2 -ml-0.5 -mr-2 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <ChevronLeft size={18} />
+ </button>
+ )}
+ <div className="min-w-0 flex-1">
+ <h2 className="text-sm font-semibold text-zinc-100 truncate">Parallel Universe</h2>
+ <p className="text-[11px] text-zinc-400 truncate mt-0.5">Try ways to run your app side by side</p>
+ </div>
+ <button
+ type="button"
+ onClick={onRefresh}
+ disabled={loading || needsToken}
+ aria-label="Refresh"
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs text-zinc-300 border border-zinc-700/60 hover:bg-zinc-800 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <RefreshCw size={12} className={loading ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />
+ <span className="hidden sm:inline">Refresh</span>
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto overflow-x-hidden p-4 sm:p-6" aria-busy={loading}>
+ <div className="max-w-3xl mx-auto space-y-5">
+ {screen.kind !== 'list' && (
+ <button type="button" onClick={onList} className="inline-flex items-center gap-1 -ml-1 min-h-[32px] px-1 rounded text-xs text-zinc-400 hover:text-zinc-200 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">
+ <ChevronLeft size={14} aria-hidden="true" /> All scenarios
+ </button>
+ )}
+
+ {needsToken && (
+ <div role="alert" className="px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 flex flex-wrap items-center gap-2 text-xs text-amber-100">
+ <span>Only you can use Parallel Universe. Confirm it’s you to open it.</span>
+ <button type="button" onClick={requestPersonToken} className="ml-auto px-2 py-0.5 rounded border border-amber-500/40 hover:bg-amber-500/10">
+ Confirm it’s you
+ </button>
+ </div>
+ )}
+
+ {error && !needsToken && (
+ <div role="alert" className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 flex items-center gap-2 text-xs text-rose-300">
+ <span>{error}</span>
+ <button type="button" onClick={onRefresh} className="ml-auto shrink-0 px-2 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10">
+ Retry
+ </button>
+ </div>
+ )}
+
+ {!scenarios && loading && (
+ <p className="flex items-center gap-2 text-xs text-zinc-400">
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading…
+ </p>
+ )}
+
+ {scenarios && !needsToken && body}
+ </div>
+ </div>
+ </div>
+);
+
+const POLL_MS = 2000;
+
+/** Loads scenarios and prices, saves the form, starts runs and follows them. */
+export const ParallelPage: React.FC<{ onBack?: () => void }> = ({ onBack }) => {
+ const [screen, setScreen] = useState<Screen>({ kind: 'list' });
+ const [scenarios, setScenarios] = useState<Scenario[] | null>(null);
+ const [prices, setPrices] = useState<Price[] | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [needsToken, setNeedsToken] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [saveError, setSaveError] = useState<string | null>(null);
+ const [runs, setRuns] = useState<Run[] | null>(null);
+ const [current, setCurrent] = useState<{ run: Run; report: Report } | null>(null);
+ const [starting, setStarting] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [notice, setNotice] = useState<{ text: string; error: boolean } | null>(null);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const alive = useRef(true);
+
+ const fail = (e: unknown) => {
+ if (!alive.current) return;
+ if (e instanceof ParallelError && e.status === 401) setNeedsToken(true);
+ else setError(e instanceof Error ? e.message : 'Something went wrong.');
+ };
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const list = await parallelApi.scenarios();
+ if (!alive.current) return;
+ setScenarios(list);
+ setError(null);
+ setNeedsToken(false);
+ parallelApi.prices().then((p) => alive.current && setPrices(p.prices), () => {});
+ } catch (e) {
+ fail(e);
+ } finally {
+ if (alive.current) setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ alive.current = true;
+ load();
+ const again = () => load();
+ window.addEventListener(PERSON_SIGNED_IN_EVENT, again);
+ return () => {
+ alive.current = false;
+ window.removeEventListener(PERSON_SIGNED_IN_EVENT, again);
+ };
+ }, [load]);
+
+ const openRun = useCallback(async (id: string) => {
+ try {
+ const r = await parallelApi.run(id);
+ if (alive.current) setCurrent(r);
+ } catch (e) {
+ if (alive.current) setNotice({ text: `Couldn’t load that run: ${e instanceof Error ? e.message : 'something went wrong.'}`, error: true });
+ }
+ }, []);
+
+ const loadRuns = useCallback(
+ async (scenarioId: string, pick = true) => {
+ try {
+ const r = await parallelApi.runs(scenarioId);
+ if (!alive.current) return;
+ setRuns(r.runs);
+ setBusy(r.running && !r.runs.some((x) => x.status === 'running'));
+ if (pick && r.runs[0]) openRun(r.runs[0].id);
+ } catch (e) {
+ if (alive.current) setNotice({ text: `Couldn’t load runs: ${e instanceof Error ? e.message : 'something went wrong.'}`, error: true });
+ }
+ },
+ [openRun],
+ );
+
+ const scenarioId = screen.kind === 'scenario' ? screen.id : null;
+ useEffect(() => {
+ setRuns(null);
+ setCurrent(null);
+ setNotice(null);
+ setBusy(false);
+ setConfirmDelete(false);
+ if (scenarioId) loadRuns(scenarioId);
+ }, [scenarioId, loadRuns]);
+
+ // While the shown run is going, look again every couple of seconds.
+ const runningId = current?.run.status === 'running' ? current.run.id : null;
+ useEffect(() => {
+ if (!runningId) return;
+ const t = window.setInterval(async () => {
+ try {
+ const r = await parallelApi.run(runningId);
+ if (!alive.current) return;
+ setCurrent(r);
+ if (r.run.status !== 'running') {
+ setNotice(r.run.status === 'finished' ? { text: 'Run finished.', error: false } : { text: 'The run was interrupted.', error: true });
+ if (scenarioId) loadRuns(scenarioId, false);
+ }
+ } catch {
+ // the next tick tries again
+ }
+ }, POLL_MS);
+ return () => window.clearInterval(t);
+ }, [runningId, scenarioId, loadRuns]);
+
+ const save = async (body: ScenarioBody) => {
+ if (screen.kind !== 'edit') return;
+ setSaving(true);
+ setSaveError(null);
+ try {
+ const s = screen.scenario ? await parallelApi.update(screen.scenario, body) : await parallelApi.create(body);
+ if (!alive.current) return;
+ setScenarios((list) => [s, ...(list ?? []).filter((x) => x.id !== s.id)]);
+ playSfx('click');
+ setScreen({ kind: 'scenario', id: s.id });
+ } catch (e) {
+ if (e instanceof ParallelError && e.status === 401) setNeedsToken(true);
+ else if (alive.current) setSaveError(e instanceof Error ? e.message : 'Something went wrong.');
+ } finally {
+ if (alive.current) setSaving(false);
+ }
+ };
+
+ const start = async (s: Scenario) => {
+ setStarting(true);
+ setNotice(null);
+ try {
+ const { run } = await parallelApi.start(s.id);
+ if (!alive.current) return;
+ setBusy(false);
+ setRuns((list) => [run, ...(list ?? [])]);
+ openRun(run.id);
+ } catch (e) {
+ if (!alive.current) return;
+ if (e instanceof ParallelError && e.busy) setBusy(true);
+ else setNotice({ text: `Couldn’t start a run: ${e instanceof Error ? e.message : 'something went wrong.'}`, error: true });
+ } finally {
+ if (alive.current) setStarting(false);
+ }
+ };
+
+ const remove = async (s: Scenario) => {
+ try {
+ await parallelApi.remove(s.id);
+ if (!alive.current) return;
+ setScenarios((list) => (list ?? []).filter((x) => x.id !== s.id));
+ setScreen({ kind: 'list' });
+ } catch (e) {
+ if (alive.current) setNotice({ text: `Couldn’t delete it: ${e instanceof Error ? e.message : 'something went wrong.'}`, error: true });
+ }
+ };
+
+ const shownScenario = scenarioId ? (scenarios ?? []).find((s) => s.id === scenarioId) ?? null : null;
+ let body: React.ReactNode = null;
+ if (screen.kind === 'list') {
+ body = <ScenarioList scenarios={scenarios ?? []} onOpen={(s) => setScreen({ kind: 'scenario', id: s.id })} onNew={() => (setSaveError(null), setScreen({ kind: 'edit', scenario: null }))} />;
+ } else if (screen.kind === 'edit') {
+ body = (
+ <ScenarioForm
+ key={screen.scenario?.id ?? 'new'}
+ initial={screen.scenario ? draftFrom(screen.scenario) : emptyScenario()}
+ editing={!!screen.scenario}
+ prices={prices}
+ saving={saving}
+ serverError={saveError}
+ onSave={save}
+ onCancel={() => setScreen(screen.scenario ? { kind: 'scenario', id: screen.scenario.id } : { kind: 'list' })}
+ />
+ );
+ } else if (shownScenario) {
+ body = (
+ <>
+ <ScenarioDetail
+ scenario={shownScenario}
+ runs={runs}
+ current={current}
+ starting={starting}
+ busy={busy}
+ notice={notice}
+ onStart={() => start(shownScenario)}
+ onPickRun={openRun}
+ onEdit={() => (setSaveError(null), setScreen({ kind: 'edit', scenario: shownScenario }))}
+ onDelete={() => setConfirmDelete(true)}
+ />
+ {confirmDelete && (
+ <div role="alertdialog" aria-label="Delete scenario" className="px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/5 flex flex-wrap items-center gap-2 text-xs text-rose-200">
+ <span className="flex-1 min-w-[12rem]">Delete “{shownScenario.title}”? You won’t be able to open its past runs here afterwards.</span>
+ <button type="button" onClick={() => remove(shownScenario)} className={`${actionBtn} border border-rose-500/40 text-rose-100 hover:bg-rose-500/10`}>
+ <Trash2 size={12} aria-hidden="true" /> Delete
+ </button>
+ <button type="button" onClick={() => setConfirmDelete(false)} className={quietBtn}>
+ <X size={12} aria-hidden="true" /> Keep it
+ </button>
+ </div>
+ )}
+ </>
+ );
+ } else {
+ body = <p className="text-xs text-zinc-500">That scenario no longer exists.</p>;
+ }
+
+ return (
+ <ParallelView
+ screen={screen}
+ scenarios={scenarios}
+ loading={loading}
+ error={error}
+ needsToken={needsToken}
+ body={body}
+ onRefresh={() => (load(), scenarioId && loadRuns(scenarioId))}
+ onBack={onBack}
+ onList={() => { setScreen({ kind: 'list' }); load(); }}
+ />
+ );
+};
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 5b37deef..aa5a9dec 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useState } from 'react';
-import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock, ShieldOff, ListChecks } from 'lucide-react';
+import { Hash, Plus, CheckCircle2, AlertTriangle, Loader2, Users, ChevronDown, Settings2, X, Crown, UserPlus, Pencil, Inbox, Search, CalendarClock, ShieldOff, ListChecks, Split } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { playSfx } from '../audio/chiptune';
import { badgeText } from '../away';
@@ -91,6 +91,8 @@ export interface SidebarProps {
awayActive?: boolean;
looseActive?: boolean;
onOpenLooseEnds?: () => void;
+ parallelActive?: boolean;
+ onOpenParallel?: () => void;
onOpenAway?: () => void;
/** Opens Space settings → Accounts from the footer. */
onOpenAccounts?: () => void;
@@ -143,6 +145,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
awayCount = 0,
awayActive = false,
looseActive = false,
+ parallelActive = false,
+ onOpenParallel,
onOpenLooseEnds,
onOpenAway,
onOpenAccounts,
@@ -284,6 +288,12 @@ export const Sidebar: React.FC<SidebarProps> = ({
<span className="truncate flex-1">Loose ends</span>
</button>
)}
+ {onOpenParallel && (
+ <button type="button" onClick={onOpenParallel} aria-current={parallelActive ? 'page' : undefined} className={navRow(parallelActive)}>
+ <Split size={15} className={parallelActive ? 'text-sky-400' : 'text-zinc-500'} aria-hidden="true" />
+ <span className="truncate flex-1">Parallel Universe</span>
+ </button>
+ )}
<button type="button" onClick={onOpenRoutines} className={navRow(false)}>
<CalendarClock size={15} className="text-zinc-500" aria-hidden="true" />
<span className="truncate flex-1">Routines</span>
diff --git a/frontend/src/parallelUniverse.ts b/frontend/src/parallelUniverse.ts
new file mode 100644
index 00000000..f9519a16
--- /dev/null
+++ b/frontend/src/parallelUniverse.ts
@@ -0,0 +1,517 @@
+// Parallel Universe: try up to three ways to deploy one app in throwaway containers on this server
+// and compare them. Every route is person-only. Nothing here touches a cloud account or spends money:
+// costs come from a dated price table checked into kwant, never from a live call.
+//
+// Every number the server returns is a `Figure` with a `tag`. The UI never shows a number without
+// saying which kind it is, so an estimate can't pass for a measurement.
+
+import { PersonCancelledError, personFetch } from './auth';
+
+export const MAX_OPTIONS = 3;
+export const MAX_TOTAL_MEMORY_MB = 3072;
+export const LIMIT_RANGES = {
+ cpus: { min: 0.1, max: 2, label: 'CPUs' },
+ memory_mb: { min: 64, max: 2048, label: 'Memory' },
+ pids: { min: 16, max: 512, label: 'Processes' },
+ timeout_secs: { min: 30, max: 900, label: 'Time limit' },
+} as const;
+export type LimitKey = keyof typeof LIMIT_RANGES;
+
+export interface Limits {
+ cpus: number;
+ memory_mb: number;
+ pids: number;
+ timeout_secs: number;
+}
+
+export interface AppSpec {
+ image?: string | null;
+ context?: string | null;
+ dockerfile?: string | null;
+ port: number;
+ health_path: string;
+}
+
+export interface DeployOption {
+ key: string;
+ label: string;
+ plan?: string | null;
+ app: AppSpec;
+ limits: Limits;
+ ops_notes: string;
+ rollback_notes: string;
+}
+
+export type CriterionKey = 'cost' | 'p95_latency' | 'ops_burden' | 'rollback';
+
+export interface Scenario {
+ id: string;
+ title: string;
+ question: string;
+ requirements: { notes: string; min_memory_mb: number | null; needs_persistent_disk: boolean; regions: string[] };
+ traffic: { monthly_requests: number; peak_rps: number; avg_response_kb: number; avg_duration_ms: number };
+ load: { requests: number; concurrency: number; path: string };
+ criteria: Array<{ key: CriterionKey; weight: number }>;
+ options: DeployOption[];
+ build_network: boolean;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface Price {
+ id: string;
+ provider: string;
+ plan: string;
+ kind: string;
+ currency: string;
+ monthly: number;
+ source_url: string;
+ as_of: string;
+ notes: string;
+}
+
+export type Figure = {
+ metric: string;
+ value: number;
+ unit: string;
+} & (
+ | { tag: 'verified'; command: string; raw_output: string; measured_at: string }
+ | { tag: 'estimate'; source_url: string; as_of: string; stale: boolean; assumptions: string[] }
+ | { tag: 'speculation'; note: string }
+);
+export type FigureTag = Figure['tag'];
+
+export type RunStatus = 'running' | 'finished' | 'interrupted';
+export type BranchStatus = 'pending' | 'running' | 'ok' | 'failed';
+
+export interface Branch {
+ key: string;
+ label: string;
+ status: BranchStatus;
+ error_code: string | null;
+ error: string | null;
+ figures: Figure[];
+ cleanup_errors: string[];
+ build_network_used: boolean;
+ started_at: string | null;
+ finished_at: string | null;
+}
+
+export interface Run {
+ id: string;
+ scenario_id: string;
+ status: RunStatus;
+ scenario: Scenario;
+ branches: Branch[];
+ cleanup_errors: string[];
+ started_at: string;
+ finished_at: string | null;
+ swept_at: string | null;
+}
+
+export interface Note {
+ criterion: CriterionKey;
+ text: string;
+ tag: 'speculation';
+ note: string;
+}
+
+export interface OptionReport {
+ key: string;
+ label: string;
+ plan: string | null;
+ status: BranchStatus;
+ error_code: string | null;
+ error: string | null;
+ measured: Figure[];
+ cost: Figure;
+ notes: Note[];
+ build_network_used: boolean;
+}
+
+export interface Leader {
+ criterion: CriterionKey;
+ option: string;
+ value: number;
+ unit: string;
+ basis: string;
+}
+
+export interface Report {
+ run_id: string;
+ scenario_id: string;
+ title: string;
+ question: string;
+ status: RunStatus;
+ started_at: string;
+ finished_at: string | null;
+ build_network_used: boolean;
+ options: OptionReport[];
+ leaders: Leader[];
+ caveats: string[];
+}
+
+export type Tone = 'emerald' | 'amber' | 'violet' | 'rose' | 'sky' | 'zinc';
+
+/** What a number is, in the words the person sees. Unknown tags read as a guess, never as measured. */
+export function figureKind(tag: string): { label: 'Measured' | 'Estimate' | 'Guess'; tone: Tone; hint: string } {
+ if (tag === 'verified') return { label: 'Measured', tone: 'emerald', hint: 'Measured on this server by a load test.' };
+ if (tag === 'estimate') return { label: 'Estimate', tone: 'amber', hint: 'Worked out from a dated price list, not measured.' };
+ return { label: 'Guess', tone: 'violet', hint: 'Neither measured nor priced.' };
+}
+
+const METRICS: Record<string, string> = {
+ p50_latency: 'Median response',
+ p95_latency: '95% answered within',
+ p99_latency: '99% answered within',
+ requests_per_sec: 'Requests per second',
+ ok_share: 'Requests answered OK',
+ success_rate: 'Requests completed',
+ memory_after_load: 'Memory after load',
+ monthly_cost: 'Monthly cost',
+};
+const humanize = (s: string) => {
+ const t = s.replace(/[_-]+/g, ' ').trim();
+ return t ? t[0].toUpperCase() + t.slice(1) : 'Other';
+};
+export const metricLabel = (metric: string): string => METRICS[metric] ?? humanize(metric);
+
+const CRITERIA: Record<string, string> = { cost: 'Cheapest', p95_latency: 'Fastest', ops_burden: 'Easiest to run', rollback: 'Easiest to roll back' };
+export const leaderLabel = (c: string): string => CRITERIA[c] ?? humanize(c);
+const NOTE_LABELS: Record<string, string> = { ops_burden: 'Running it', rollback: 'Rolling back' };
+export const noteLabel = (c: string): string => NOTE_LABELS[c] ?? humanize(c);
+
+/** `57.5 ms`, `591 /s`, `99.5 %`, `6.00 USD`. */
+export function formatValue(value: number, unit: string): string {
+ if (!Number.isFinite(value)) return '—';
+ if (unit === 'ratio') return `${(value * 100).toFixed(value === 1 ? 0 : 1)} %`;
+ if (unit === '1/s') return `${value >= 100 ? Math.round(value) : value.toFixed(1)} /s`;
+ if (/^[A-Z]{3}$/.test(unit)) return `${value.toFixed(2)} ${unit}`;
+ const n = value >= 100 ? Math.round(value).toString() : value >= 10 ? value.toFixed(1) : value.toFixed(value === 0 ? 0 : 2);
+ return `${n} ${unit}`;
+}
+
+/** The host of a price source, for a short link text. */
+export function sourceHost(url: string): string {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '');
+ } catch {
+ return url;
+ }
+}
+export const safeHttps = (url: string | null | undefined): string | null => (url && /^https:\/\//i.test(url) ? url : null);
+
+export const RUN_STATUS: Record<RunStatus, { label: string; tone: Tone }> = {
+ running: { label: 'Running', tone: 'sky' },
+ finished: { label: 'Finished', tone: 'emerald' },
+ interrupted: { label: 'Interrupted', tone: 'rose' },
+};
+export const runStatus = (s: string): { label: string; tone: Tone } => RUN_STATUS[s as RunStatus] ?? { label: humanize(s), tone: 'zinc' };
+
+export const BRANCH_STATUS: Record<BranchStatus, { label: string; tone: Tone }> = {
+ pending: { label: 'Waiting', tone: 'zinc' },
+ running: { label: 'Testing', tone: 'sky' },
+ ok: { label: 'Done', tone: 'emerald' },
+ failed: { label: 'Failed', tone: 'rose' },
+};
+export const branchStatus = (s: string): { label: string; tone: Tone } => BRANCH_STATUS[s as BranchStatus] ?? { label: humanize(s), tone: 'zinc' };
+
+/** "2 of 3 options tried". */
+export function runProgress(run: Pick<Run, 'branches'>): { done: number; total: number; text: string } {
+ const total = run.branches.length;
+ const done = run.branches.filter((b) => b.status === 'ok' || b.status === 'failed').length;
+ return { done, total, text: `${done} of ${total} option${total === 1 ? '' : 's'} tried` };
+}
+
+/** What an interrupted run means, said plainly. */
+export const INTERRUPTED_TEXT =
+ 'The server stopped before this run finished. Options that hadn’t finished have no numbers, and their containers were removed when the server started again.';
+
+// ---------- The form ----------
+
+/** The form keeps what the person typed, so a half-typed number isn't lost. */
+export interface OptionDraft {
+ key: string;
+ label: string;
+ plan: string;
+ source: 'image' | 'context';
+ image: string;
+ context: string;
+ dockerfile: string;
+ port: string;
+ health_path: string;
+ cpus: string;
+ memory_mb: string;
+ pids: string;
+ timeout_secs: string;
+ ops_notes: string;
+ rollback_notes: string;
+}
+
+export interface ScenarioDraft {
+ title: string;
+ question: string;
+ monthly_requests: string;
+ peak_rps: string;
+ avg_response_kb: string;
+ avg_duration_ms: string;
+ load_requests: string;
+ load_concurrency: string;
+ load_path: string;
+ build_network: boolean;
+ options: OptionDraft[];
+}
+
+export const emptyOption = (): OptionDraft => ({
+ key: '',
+ label: '',
+ plan: '',
+ source: 'image',
+ image: '',
+ context: '',
+ dockerfile: '',
+ port: '8080',
+ health_path: '/',
+ cpus: '1',
+ memory_mb: '512',
+ pids: '128',
+ timeout_secs: '300',
+ ops_notes: '',
+ rollback_notes: '',
+});
+
+export const emptyScenario = (): ScenarioDraft => ({
+ title: '',
+ question: '',
+ monthly_requests: '100000',
+ peak_rps: '5',
+ avg_response_kb: '20',
+ avg_duration_ms: '50',
+ load_requests: '2000',
+ load_concurrency: '10',
+ load_path: '/',
+ build_network: false,
+ options: [emptyOption()],
+});
+
+export function draftFrom(s: Scenario): ScenarioDraft {
+ return {
+ title: s.title,
+ question: s.question,
+ monthly_requests: String(s.traffic.monthly_requests),
+ peak_rps: String(s.traffic.peak_rps),
+ avg_response_kb: String(s.traffic.avg_response_kb),
+ avg_duration_ms: String(s.traffic.avg_duration_ms),
+ load_requests: String(s.load.requests),
+ load_concurrency: String(s.load.concurrency),
+ load_path: s.load.path,
+ build_network: s.build_network,
+ options: s.options.map((o) => ({
+ key: o.key,
+ label: o.label,
+ plan: o.plan ?? '',
+ source: o.app.context ? 'context' : 'image',
+ image: o.app.image ?? '',
+ context: o.app.context ?? '',
+ dockerfile: o.app.dockerfile ?? '',
+ port: String(o.app.port),
+ health_path: o.app.health_path,
+ cpus: String(o.limits.cpus),
+ memory_mb: String(o.limits.memory_mb),
+ pids: String(o.limits.pids),
+ timeout_secs: String(o.limits.timeout_secs),
+ ops_notes: o.ops_notes,
+ rollback_notes: o.rollback_notes,
+ })),
+ };
+}
+
+/** `DigitalOcean droplet` → `digitalocean-droplet`: the option key the server wants. */
+export function slugify(s: string): string {
+ return s
+ .toLowerCase()
+ .normalize('NFKD')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 32)
+ .replace(/-+$/, '');
+}
+
+const num = (s: string): number | null => {
+ const t = s.trim().replace(',', '.');
+ if (!t) return null;
+ const n = Number(t);
+ return Number.isFinite(n) ? n : null;
+};
+const isInt = (n: number | null): n is number => n !== null && Number.isInteger(n);
+const isImageRef = (s: string) => s.length > 0 && s.length <= 256 && !s.startsWith('-') && /^[A-Za-z0-9./:_@-]+$/.test(s);
+const isUrlPath = (s: string) => s.startsWith('/') && s.length <= 512 && /^[\x21-\x7e]+$/.test(s);
+
+/** Total memory the options reserve, counting only what parses. */
+export const reservedMemory = (d: ScenarioDraft): number => d.options.reduce((sum, o) => sum + (num(o.memory_mb) ?? 0), 0);
+
+/** Problems by field name (`title`, `options.1.memory_mb`, `memory_total`, …), in the order they appear. */
+export type FormErrors = Record<string, string>;
+
+/** Checks the draft the way the server will and builds the body. Messages say what to change. */
+export function validateScenario(d: ScenarioDraft, planIds?: Set<string>): { errors: FormErrors; body: Omit<Scenario, 'id' | 'created_at' | 'updated_at' | 'requirements' | 'criteria'> | null } {
+ const errors: FormErrors = {};
+ const title = d.title.trim();
+ if (!title) errors.title = 'Give the scenario a name.';
+ else if ([...title].length > 120) errors.title = 'Keep the name to 120 characters.';
+ if ([...d.question].length > 2000) errors.question = 'Keep the question to 2000 characters.';
+
+ const traffic = {
+ monthly_requests: num(d.monthly_requests),
+ peak_rps: num(d.peak_rps),
+ avg_response_kb: num(d.avg_response_kb),
+ avg_duration_ms: num(d.avg_duration_ms),
+ };
+ if (!isInt(traffic.monthly_requests) || traffic.monthly_requests < 0 || traffic.monthly_requests > 100_000_000_000)
+ errors.monthly_requests = 'A whole number from 0.';
+ for (const k of ['peak_rps', 'avg_response_kb', 'avg_duration_ms'] as const) {
+ const v = traffic[k];
+ if (v === null || v < 0 || v > 1e7) errors[k] = 'A number from 0.';
+ }
+ const load = { requests: num(d.load_requests), concurrency: num(d.load_concurrency), path: d.load_path.trim() };
+ if (!isInt(load.requests) || load.requests < 1 || load.requests > 100_000) errors.load_requests = 'From 1 to 100,000.';
+ if (!isInt(load.concurrency) || load.concurrency < 1 || load.concurrency > 64) errors.load_concurrency = 'From 1 to 64.';
+ if (!isUrlPath(load.path)) errors.load_path = 'Starts with /, like /health.';
+
+ if (d.options.length === 0) errors.options = 'Add at least one option.';
+ if (d.options.length > MAX_OPTIONS) errors.options = `At most ${MAX_OPTIONS} options.`;
+
+ const keys = new Set<string>();
+ const options: DeployOption[] = d.options.map((o, i) => {
+ const at = (f: string) => `options.${i}.${f}`;
+ const label = o.label.trim();
+ if (!label) errors[at('label')] = 'Name this option.';
+ else if ([...label].length > 80) errors[at('label')] = 'Keep it to 80 characters.';
+ // A new option gets its key from its name; an existing one keeps its key so past runs still match.
+ let key = o.key || slugify(label) || `option-${i + 1}`;
+ if (keys.has(key)) {
+ if (o.key) errors[at('label')] = 'Two options have the same key. Rename one.';
+ else {
+ let n = 2;
+ while (keys.has(`${key.slice(0, 29)}-${n}`)) n++;
+ key = `${key.slice(0, 29)}-${n}`;
+ }
+ }
+ keys.add(key);
+
+ if (o.plan && planIds && !planIds.has(o.plan)) errors[at('plan')] = 'That plan isn’t in the price table.';
+
+ const app: AppSpec = { port: 0, health_path: o.health_path.trim() || '/' };
+ if (o.source === 'image') {
+ const image = o.image.trim();
+ if (!isImageRef(image)) errors[at('image')] = 'A Docker image on this server, like myapp:latest.';
+ app.image = image;
+ } else {
+ const context = o.context.trim();
+ if (!context.startsWith('/') || context.length > 1024 || context.split('/').includes('..'))
+ errors[at('context')] = 'A full folder path on this server, like /home/me/app, without “..”.';
+ app.context = context;
+ const df = o.dockerfile.trim();
+ if (df) {
+ if (df.startsWith('/') || df.split('/').some((p) => p === '..' || p === '.' || p === '')) errors[at('dockerfile')] = 'A path inside the folder, like Dockerfile.';
+ app.dockerfile = df;
+ }
+ }
+ const port = num(o.port);
+ if (!isInt(port) || port < 1 || port > 65535) errors[at('port')] = 'From 1 to 65535.';
+ else app.port = port;
+ if (!isUrlPath(app.health_path)) errors[at('health_path')] = 'Starts with /.';
+
+ const limits = {} as Limits;
+ for (const k of Object.keys(LIMIT_RANGES) as LimitKey[]) {
+ const r = LIMIT_RANGES[k];
+ const v = num(o[k]);
+ const ok = v !== null && v >= r.min && v <= r.max && (k === 'cpus' || Number.isInteger(v));
+ if (!ok) errors[at(k)] = `From ${r.min} to ${r.max}.`;
+ limits[k] = v ?? 0;
+ }
+ if ([...o.ops_notes].length > 2000 || [...o.rollback_notes].length > 2000) errors[at('ops_notes')] = 'Keep notes to 2000 characters each.';
+ return { key, label, plan: o.plan || null, app, limits, ops_notes: o.ops_notes.trim(), rollback_notes: o.rollback_notes.trim() };
+ });
+
+ const total = reservedMemory(d);
+ if (total > MAX_TOTAL_MEMORY_MB) errors.memory_total = `The options reserve ${total} MB together. The limit is ${MAX_TOTAL_MEMORY_MB} MB, so lower the memory of one or more options.`;
+
+ if (Object.keys(errors).length) return { errors, body: null };
+ return {
+ errors,
+ body: {
+ title,
+ question: d.question.trim(),
+ traffic: traffic as Scenario['traffic'],
+ load: load as Scenario['load'],
+ options,
+ build_network: d.build_network,
+ },
+ };
+}
+
+// ---------- API ----------
+
+/** Why a call failed, as the panel shows it. */
+export class ParallelError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ /** 409 `code: "busy"`: another run is going. Not an error the person caused. */
+ public busy = false,
+ ) {
+ super(message);
+ }
+}
+
+const sentence = (s: string) => {
+ const t = s.trim();
+ if (!t) return t;
+ const c = t[0].toUpperCase() + t.slice(1);
+ return /[.!?]$/.test(c) ? c : `${c}.`;
+};
+
+/** Turns a response the server refused into a `ParallelError`. */
+export function errorFrom(status: number, answer: unknown): ParallelError {
+ const a = answer && typeof answer === 'object' ? (answer as Record<string, unknown>) : {};
+ if (status === 409 && a.code === 'busy') return new ParallelError('Another run is going. It can start once that one finishes.', 409, true);
+ const err = typeof a.error === 'string' && a.error.trim() ? sentence(a.error) : null;
+ if (status === 403) return new ParallelError('Only you can see and run Parallel Universe.', 403);
+ if (status === 404 && !err) return new ParallelError('This server doesn’t have Parallel Universe yet. Update the app and try again.', 404);
+ return new ParallelError(err ?? `Something went wrong (HTTP ${status}).`, status);
+}
+
+async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T> {
+ let res: Response;
+ try {
+ res = await personFetch(url, {
+ method,
+ cache: 'no-store',
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch (e) {
+ if (e instanceof PersonCancelledError) throw new ParallelError(e.message, 401);
+ throw new ParallelError('Couldn’t reach the server. Check your connection and try again.', 0);
+ }
+ const answer = await res.json().catch(() => null);
+ if (res.ok) return answer as T;
+ throw errorFrom(res.status, answer);
+}
+
+const enc = encodeURIComponent;
+export type ScenarioBody = NonNullable<ReturnType<typeof validateScenario>['body']>;
+
+export const parallelApi = {
+ scenarios: () => call<{ scenarios: Scenario[] }>('/api/parallel/scenarios').then((r) => r.scenarios),
+ create: (s: ScenarioBody) => call<Scenario>('/api/parallel/scenarios', 'POST', s),
+ /** PUT replaces the whole scenario, so the fields the form doesn't show come from `old`. */
+ update: (old: Scenario, s: ScenarioBody) =>
+ call<Scenario>(`/api/parallel/scenarios/${enc(old.id)}`, 'PUT', { ...s, requirements: old.requirements, criteria: old.criteria }),
+ remove: (id: string) => call<unknown>(`/api/parallel/scenarios/${enc(id)}`, 'DELETE'),
+ prices: () => call<{ prices: Price[]; stale_after_days: number }>('/api/parallel/prices'),
+ start: (id: string) => call<{ run: Run }>(`/api/parallel/scenarios/${enc(id)}/run`, 'POST', {}),
+ runs: (scenarioId: string) => call<{ runs: Run[]; running: boolean }>(`/api/parallel/scenarios/${enc(scenarioId)}/runs`),
+ run: (id: string) => call<{ run: Run; report: Report }>(`/api/parallel/runs/${enc(id)}`),
+};
diff --git a/frontend/tests/parallelUniverse.test.mjs b/frontend/tests/parallelUniverse.test.mjs
new file mode 100644
index 00000000..4d240cc9
--- /dev/null
+++ b/frontend/tests/parallelUniverse.test.mjs
@@ -0,0 +1,239 @@
+// Parallel Universe (plan item 7): every number shows whether it was measured, estimated from a dated
+// price or guessed; the form checks the server's caps before saving; a busy server and an interrupted
+// run read calmly and honestly.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const m = await loadBundled(`export * from './src/parallelUniverse';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { ComparisonReport, RunProgress, ScenarioDetail, ScenarioForm, ScenarioList, KindBadge } from './src/components/ParallelUniverseView';
+ const r = (C) => (props) => renderToStaticMarkup(React.createElement(C, props));
+ export const report = r(ComparisonReport);
+ export const progress = r(RunProgress);
+ export const detail = r(ScenarioDetail);
+ export const form = r(ScenarioForm);
+ export const list = r(ScenarioList);
+ export const badge = r(KindBadge);
+`);
+
+const noop = () => {};
+const at = '2026-10-20T20:00:00Z';
+const verified = (metric, value, unit) => ({ metric, value, unit, tag: 'verified', command: 'docker run … oha', raw_output: '{}', measured_at: at });
+const estimate = (value, stale = false) => ({
+ metric: 'monthly_cost', value, unit: 'USD', tag: 'estimate', source_url: 'https://www.digitalocean.com/pricing/droplets', as_of: '2026-10-20', stale, assumptions: [],
+});
+const guess = { metric: 'monthly_cost', value: 0, unit: 'USD', tag: 'speculation', note: 'no priced plan chosen for this option' };
+
+// Shaped like run::Report in src/parallel/run.rs.
+const reportOf = (over = {}) => ({
+ run_id: 'r1', scenario_id: 's1', title: 'Leave managed hosting?', question: '', status: 'finished', started_at: at, finished_at: at, build_network_used: false,
+ criteria: [],
+ options: [
+ {
+ key: 'vps', label: 'DigitalOcean droplet', plan: 'do-basic-1gb', status: 'ok', error_code: null, error: null, build_network_used: false,
+ measured: [verified('p95_latency', 57.5, 'ms'), verified('requests_per_sec', 591, '1/s'), verified('memory_after_load', 23.5, 'MB')],
+ cost: estimate(6),
+ notes: [{ criterion: 'rollback', text: 'Keep the previous image tagged.', tag: 'speculation', note: 'general note for vm plans' }],
+ },
+ { key: 'lambda', label: 'AWS Lambda', plan: null, status: 'failed', error_code: 'health_timeout', error: 'the app never answered', build_network_used: false, measured: [], cost: guess, notes: [] },
+ ],
+ leaders: [{ criterion: 'p95_latency', option: 'vps', value: 57.5, unit: 'ms', basis: 'verified' }],
+ caveats: ['These numbers are from this server, not the provider’s hardware.'],
+ ...over,
+});
+const branch = (key, status, extra = {}) => ({ key, label: key.toUpperCase(), status, error_code: null, error: null, figures: [], cleanup_errors: [], build_network_used: false, started_at: null, finished_at: null, ...extra });
+const runOf = (status, branches) => ({ id: 'r1', scenario_id: 's1', status, scenario: {}, branches, cleanup_errors: [], started_at: at, finished_at: null, swept_at: null });
+const scenario = { id: 's1', title: 'Leave managed hosting?', question: 'VPS or serverless?', options: [{ key: 'vps', label: 'Droplet' }], build_network: false };
+
+test('each tag maps to one visible label, and anything unknown is a guess, never measured', () => {
+ assert.equal(m.figureKind('verified').label, 'Measured');
+ assert.equal(m.figureKind('estimate').label, 'Estimate');
+ assert.equal(m.figureKind('speculation').label, 'Guess');
+ assert.equal(m.figureKind('something_new').label, 'Guess');
+ assert.match(ui.badge({ tag: 'estimate' }), />Estimate</);
+});
+
+test('the comparison labels every figure and never shows an estimate as measured', () => {
+ const html = ui.report({ report: reportOf() });
+ // 3 measured figures + the leader's basis.
+ assert.equal(html.match(/>Measured</g).length, 4);
+ // The cost, with "about", its source, date and the Estimate label.
+ assert.match(html, /about 6\.00 USD/);
+ assert.match(html, />Estimate</);
+ assert.match(html, /Prices as of 2026-10-20/);
+ assert.match(html, /href="https:\/\/www\.digitalocean\.com\/pricing\/droplets"[^>]*target="_blank"[^>]*rel="noopener noreferrer"/);
+ assert.match(html, />digitalocean\.com</);
+ // No plan: no number at all, labelled a guess.
+ assert.match(html, /unknown/);
+ assert.doesNotMatch(html, /0\.00 USD/);
+ // Notes are guesses.
+ assert.match(html, /Keep the previous image tagged/);
+ assert.ok(html.match(/>Guess</g).length >= 2);
+ assert.doesNotMatch(html, /Price may be out of date/);
+ assert.match(ui.report({ report: reportOf({ options: [{ ...reportOf().options[0], cost: estimate(6, true) }] }) }), /Price may be out of date/);
+});
+
+test('leaders and caveats show only when the report gives them', () => {
+ const html = ui.report({ report: reportOf() });
+ assert.match(html, /Fastest:/);
+ assert.doesNotMatch(html, /Cheapest/);
+ assert.match(html, /Keep in mind/);
+ assert.match(html, /not the provider’s hardware/);
+ const bare = ui.report({ report: reportOf({ leaders: [], caveats: [] }) });
+ assert.doesNotMatch(bare, /Fastest|Cheapest|aria-label="Leaders"|Keep in mind/);
+ // A failed option says why and has no numbers.
+ assert.match(html, /the app never answered/);
+ assert.match(html, /Nothing measured — the test didn’t finish/);
+});
+
+test('a price source that is not https is shown, not linked', () => {
+ const r = reportOf();
+ r.options[0].cost = { ...estimate(6), source_url: 'javascript:alert(1)' };
+ const html = ui.report({ report: r });
+ assert.doesNotMatch(html, /href="javascript/);
+ assert.match(html, /javascript:alert\(1\)/);
+});
+
+test('values read as a person would say them', () => {
+ assert.equal(m.formatValue(57.5, 'ms'), '57.5 ms');
+ assert.equal(m.formatValue(591.2, '1/s'), '591 /s');
+ assert.equal(m.formatValue(1, 'ratio'), '100 %');
+ assert.equal(m.formatValue(0.987, 'ratio'), '98.7 %');
+ assert.equal(m.formatValue(5.123, 'USD'), '5.12 USD');
+ assert.equal(m.metricLabel('p95_latency'), '95% answered within');
+ assert.equal(m.metricLabel('cold_start'), 'Cold start');
+});
+
+const option = (over = {}) => ({ ...m.emptyOption(), label: 'Droplet', image: 'kwnt-executor:v1', ...over });
+const draft = (over = {}) => ({ ...m.emptyScenario(), title: 'Leave managed hosting?', options: [option()], ...over });
+
+test('a valid draft becomes the body the server expects', () => {
+ const { errors, body } = m.validateScenario(draft({ options: [option(), option({ label: 'Droplet', plan: 'do-basic-1gb' })] }), new Set(['do-basic-1gb']));
+ assert.deepEqual(errors, {});
+ assert.equal(body.options.length, 2);
+ assert.deepEqual(body.options.map((o) => o.key), ['droplet', 'droplet-2'], 'keys come from the names and stay unique');
+ assert.deepEqual(body.options[0].limits, { cpus: 1, memory_mb: 512, pids: 128, timeout_secs: 300 });
+ assert.deepEqual(body.options[0].app, { port: 8080, health_path: '/', image: 'kwnt-executor:v1' });
+ assert.equal(body.options[1].plan, 'do-basic-1gb');
+ assert.equal(body.build_network, false);
+ assert.equal(body.traffic.monthly_requests, 100000);
+});
+
+test('the form refuses what the server would: caps, ranges, paths', () => {
+ const v = (d) => m.validateScenario(d).errors;
+ assert.match(v(draft({ title: ' ' })).title, /name/);
+ assert.match(v(draft({ options: [option(), option(), option(), option()] })).options, /At most 3/);
+ assert.match(v(draft({ options: [] })).options, /at least one/);
+ // 3 × 1100 MB is over the 3072 MB the options may reserve together.
+ const big = v(draft({ options: [option({ memory_mb: '1100' }), option({ memory_mb: '1100' }), option({ memory_mb: '1100' })] }));
+ assert.match(big.memory_total, /3300 MB together.*3072 MB/);
+ const o = v(draft({ options: [option({ cpus: '4', memory_mb: '32', pids: '1000', timeout_secs: '10.5', port: '0', health_path: 'health' })] }));
+ assert.match(o['options.0.cpus'], /0\.1 to 2/);
+ assert.match(o['options.0.memory_mb'], /64 to 2048/);
+ assert.match(o['options.0.pids'], /16 to 512/);
+ assert.match(o['options.0.timeout_secs'], /30 to 900/);
+ assert.match(o['options.0.port'], /1 to 65535/);
+ assert.match(o['options.0.health_path'], /Starts with \//);
+ assert.match(v(draft({ options: [option({ image: '--privileged' })] }))['options.0.image'], /Docker image/);
+ assert.match(v(draft({ options: [option({ source: 'context', context: 'app' })] }))['options.0.context'], /full folder path/);
+ assert.match(v(draft({ options: [option({ source: 'context', context: '/tmp/../etc' })] }))['options.0.context'], /without/);
+ assert.match(v(draft({ options: [option({ source: 'context', context: '/srv/app', dockerfile: '../Dockerfile' })] }))['options.0.dockerfile'], /inside the folder/);
+ assert.match(m.validateScenario(draft({ options: [option({ plan: 'nope' })] }), new Set(['do-basic-1gb'])).errors['options.0.plan'], /price table/);
+ assert.match(v(draft({ load_concurrency: '100' })).load_concurrency, /1 to 64/);
+ assert.match(v(draft({ monthly_requests: '1.5' })).monthly_requests, /whole number/);
+});
+
+test('editing keeps option keys, so past runs still line up', () => {
+ const saved = {
+ id: 's1', title: 'T', question: '', requirements: { notes: 'x', min_memory_mb: null, needs_persistent_disk: false, regions: [] },
+ traffic: { monthly_requests: 10, peak_rps: 1, avg_response_kb: 2, avg_duration_ms: 3 }, load: { requests: 100, concurrency: 2, path: '/' },
+ criteria: [{ key: 'cost', weight: 5 }], build_network: true, created_at: at, updated_at: at,
+ options: [{ key: 'vps', label: 'Renamed droplet', plan: null, app: { context: '/srv/app', dockerfile: null, port: 80, health_path: '/' }, limits: { cpus: 0.5, memory_mb: 256, pids: 64, timeout_secs: 60 }, ops_notes: '', rollback_notes: '' }],
+ };
+ const d = m.draftFrom(saved);
+ assert.equal(d.options[0].source, 'context');
+ assert.equal(d.build_network, true);
+ const { body } = m.validateScenario(d);
+ assert.equal(body.options[0].key, 'vps');
+ assert.equal(body.options[0].app.context, '/srv/app');
+});
+
+test('the form shows the memory total, the 3-option cap and an off-by-default build-network box with its warning', () => {
+ const html = ui.form({ initial: m.emptyScenario(), editing: false, prices: [], saving: false, serverError: null, onSave: noop, onCancel: noop });
+ assert.match(html, /Memory reserved: 512 of 3072 MB/);
+ assert.match(html, /\(1 of 3\)/);
+ assert.match(html, /Add an option/);
+ assert.match(html, /<input type="checkbox"(?![^>]*checked)[^>]*>/);
+ assert.match(html, /Let the build step use the internet/);
+ assert.match(html, /The app itself is always tested offline/);
+ const full = ui.form({ initial: draft({ options: [option(), option(), option()] }), editing: false, prices: [], saving: false, serverError: null, onSave: noop, onCancel: noop });
+ assert.doesNotMatch(full, /Add an option/);
+ assert.match(full, /the most options a scenario can have/);
+});
+
+test('form errors are tied to their fields for screen readers', () => {
+ const html = ui.form({ initial: draft({ title: '', options: [option({ memory_mb: '5000' })] }), editing: false, prices: [], saving: false, serverError: null, initialShowErrors: true, onSave: noop, onCancel: noop });
+ assert.match(html, /aria-invalid="true"/);
+ assert.match(html, /Give the scenario a name/);
+ assert.match(html, /From 64 to 2048/);
+ assert.match(html, /Fix the 3 highlighted fields to save/);
+ const id = html.match(/aria-invalid="true" aria-describedby="([^"]+)"/)[1];
+ assert.match(html, new RegExp(`id="${id}"[^>]*>Give the scenario a name`));
+});
+
+test('a 409 busy is a calm notice, not an error', () => {
+ const e = m.errorFrom(409, { error: 'a run is already going; wait for it to finish', code: 'busy' });
+ assert.equal(e.busy, true);
+ assert.match(e.message, /Another run is going/);
+ assert.equal(m.errorFrom(409, { error: 'conflict' }).busy, false);
+ assert.match(m.errorFrom(400, { error: 'fly: memory_mb must be between 64 and 2048' }).message, /^Fly: memory_mb .*2048\.$/);
+ assert.match(m.errorFrom(403, {}).message, /Only you/);
+ assert.match(m.errorFrom(500, null).message, /HTTP 500/);
+
+ const html = ui.detail({ scenario, runs: [], current: null, starting: false, busy: true, notice: null, onStart: noop, onPickRun: noop, onEdit: noop, onDelete: noop });
+ assert.match(html, /Another run is going right now/);
+ assert.match(html, /border-amber-500/);
+ assert.doesNotMatch(html, /rose-500/);
+ assert.match(html, /<button type="button" disabled=""[^>]*>.*Start a run/);
+});
+
+test('a running run shows per-option progress; the start button waits', () => {
+ const run = runOf('running', [branch('vps', 'ok'), branch('fly', 'running'), branch('lambda', 'pending')]);
+ const p = ui.progress({ run });
+ assert.match(p, /1 of 3 options tried/);
+ assert.match(p, /role="progressbar"[^>]*aria-valuemax="3" aria-valuenow="1"/);
+ assert.match(p, />Done<.*>VPS</);
+ assert.match(p, />Testing<.*>FLY</);
+ assert.match(p, />Waiting<.*>LAMBDA</);
+ const pending = reportOf({ status: 'running', options: reportOf().options.map((o) => ({ ...o, status: 'pending', measured: [] })), leaders: [] });
+ const html = ui.detail({ scenario, runs: [run], current: { run, report: pending }, starting: false, busy: false, notice: null, onStart: noop, onPickRun: noop, onEdit: noop, onDelete: noop });
+ assert.match(html, /Running…/);
+ assert.doesNotMatch(html, /Another run is going/);
+ assert.doesNotMatch(html, /Comparison/, 'nothing to compare until an option finishes');
+});
+
+test('an interrupted run says so plainly and keeps what finished', () => {
+ const run = runOf('interrupted', [branch('vps', 'ok'), branch('fly', 'running'), branch('lambda', 'pending')]);
+ const p = ui.progress({ run });
+ assert.match(p, />Interrupted</);
+ assert.match(p, /The server stopped before this run finished/);
+ assert.doesNotMatch(p, /progressbar/);
+ assert.equal(m.runProgress(run).done, 1);
+ const failed = ui.progress({ run: runOf('finished', [branch('vps', 'failed', { error: 'the app never answered' })]) });
+ assert.match(failed, />Failed<.*the app never answered/);
+ assert.equal(m.runStatus('archived').label, 'Archived');
+});
+
+test('the empty list explains what a scenario is and offers to make one', () => {
+ const html = ui.list({ scenarios: [], onOpen: noop, onNew: noop });
+ assert.match(html, /data-empty/);
+ assert.match(html, /No scenarios yet/);
+ assert.match(html, /New scenario/);
+ const one = ui.list({ scenarios: [{ ...scenario, options: [{ label: 'Droplet' }, { label: 'Fly' }] }], onOpen: noop, onNew: noop });
+ assert.match(one, /2 options: Droplet · Fly/);
+});