Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: clearer sandbox setup with live download progress

ogsamrat7450dab3c56c
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index 92d8733b..1dc3f85a 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -452,10 +452,21 @@ export type OmniRushWorkspaceBox = {
/** The computer's backend setting: "auto", one backend id, or "native"; and the values it takes here. */
backendSetting: { value: string; source: "env" | "setting" | "auto"; choices: Array<{ id: string; label: string }> };
image: { ref: string; stack: string; present: boolean | null; downloading: boolean } | null;
+ /** The image download's progress while it downloads (bytes when the server knows the layer sizes). Older servers: absent. */
+ progress?: OmniRushWorkspaceBoxProgress | null;
container: { name: string; exists: boolean; running: boolean } | null;
+ /** The server's OS. Older servers: absent. */
+ platform?: string;
notice: string | null;
error: string | null;
};
+export type OmniRushWorkspaceBoxProgress = {
+ bytesDone: number | null;
+ bytesTotal: number | null;
+ layersDone: number;
+ layersTotal: number;
+ startedAt: number | null;
+};
export type OmniRushWorkspaceBoxChange = OmniRushWorkspaceBox & {
engine: { status: "unchanged" | "applied" | "deferred" | "failed" | "unmanaged" };
};
@@ -1973,6 +1984,11 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
requestJson<OmniRushWorkspaceBoxChange>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/box`, {
token, hostToken, method: "PUT", body: { backend }, timeoutMs: ENGINE_RELOAD_TIMEOUT_MS,
}),
+ retryWorkspaceBox: (workspaceId: string) =>
+ // A fresh backend check, then the status (each bounded at 10 s on the server).
+ requestJson<OmniRushWorkspaceBox>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/box/retry`, {
+ token, hostToken, method: "POST", body: {}, timeoutMs: 30_000,
+ }),
resetWorkspaceBox: (workspaceId: string) =>
requestJson<{ removed: boolean }>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/box/reset`, {
token, hostToken, method: "POST", body: {}, timeoutMs: 90_000,
diff --git a/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx b/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx
index bc4878eb..3e73dc7f 100644
--- a/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx
+++ b/apps/app/src/react-app/domains/session/chat/new-task-composer.tsx
@@ -13,6 +13,7 @@ import { DEFAULT_MODEL } from "@/app/constants";
import { ReactSessionComposer } from "@/react-app/domains/session/surface/composer/composer";
import { WorkspaceRunModeMenu } from "@/react-app/domains/session/surface/composer/workspace-run-mode-menu";
import { FullPermissionsToggle } from "@/react-app/domains/session/surface/composer/full-permissions-toggle";
+import { SandboxStatusChip } from "@/react-app/domains/session/surface/composer/sandbox-status-chip";
import { SubagentModelMenu } from "@/react-app/domains/session/surface/composer/subagent-model-menu";
import {
snapshotComposerSessionState,
@@ -433,6 +434,7 @@ export function NewTaskComposer(props: NewTaskComposerProps) {
<ReactSessionComposer
runModeControl={<WorkspaceRunModeMenu client={workspaceClient} workspaceId={workspaceId} busy={props.busy} />}
fullPermissionsControl={<FullPermissionsToggle client={workspaceClient} workspaceId={workspaceId} />}
+ sandboxControl={<SandboxStatusChip client={workspaceClient} workspaceId={workspaceId} onOpenSettings={() => context?.onOpenSettingsSection?.("sandbox")} />}
subagentModelControl={<SubagentModelMenu client={workspaceClient} />}
voiceClient={workspaceClient}
voiceWorkspaceId={workspaceId}
diff --git a/apps/app/src/react-app/domains/session/surface/composer/composer.tsx b/apps/app/src/react-app/domains/session/surface/composer/composer.tsx
index d33e5c30..fd91c6b9 100644
--- a/apps/app/src/react-app/domains/session/surface/composer/composer.tsx
+++ b/apps/app/src/react-app/domains/session/surface/composer/composer.tsx
@@ -128,6 +128,8 @@ type ComposerProps = {
fullPermissionsControl?: ReactNode;
/** The "Sub-agents" model and effort menu, shown right after the model selector. */
subagentModelControl?: ReactNode;
+ /** The Linux sandbox indicator (only while the project's sandbox is on or offered), after Full permissions. */
+ sandboxControl?: ReactNode;
/** Voice dictation's local server hop; without it there is no mic button. */
voiceClient?: VoiceClient | null;
/** The workspace whose repository and branch hint the transcription. */
@@ -1819,6 +1821,7 @@ export const ReactSessionComposer = memo(function ReactSessionComposer(props: Co
/>
{props.subagentModelControl}
{props.fullPermissionsControl}
+ {props.sandboxControl}
{props.modelUnavailable ? props.onRefreshOrganizationModels ? (
<button
type="button"
diff --git a/apps/app/src/react-app/domains/session/surface/composer/sandbox-status-chip.tsx b/apps/app/src/react-app/domains/session/surface/composer/sandbox-status-chip.tsx
new file mode 100644
index 00000000..2df605af
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/surface/composer/sandbox-status-chip.tsx
@@ -0,0 +1,93 @@
+/** @jsxImportSource react */
+import { useState } from "react";
+import { Box, X } from "lucide-react";
+
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { linuxSandboxView, useLinuxSandbox, type LinuxSandboxClient, type LinuxSandboxView } from "@/react-app/domains/settings/linux-sandbox";
+
+type Props = {
+ client: LinuxSandboxClient | null;
+ workspaceId: string | null;
+ /** Opens Settings > General at the sandbox card. */
+ onOpenSettings?: () => void;
+};
+
+const DOT: Record<LinuxSandboxView["tone"], string> = {
+ off: "bg-gray-8",
+ busy: "bg-amber-9 motion-safe:animate-pulse",
+ ready: "bg-green-9",
+ attention: "bg-amber-9",
+ error: "bg-red-9",
+};
+
+/**
+ * The composer's sandbox indicator, beside Full permissions: shown only when
+ * the project's Linux sandbox is on (its state as a dot, the line in the
+ * tooltip; a click opens its Settings card), or as a small dismissible
+ * "Use sandbox" prompt when the server offers it. Nothing otherwise.
+ */
+export function SandboxStatusChip(props: Props) {
+ if (!props.client || !props.workspaceId) return null;
+ return <SandboxChip key={props.workspaceId} client={props.client} workspaceId={props.workspaceId} onOpenSettings={props.onOpenSettings} />;
+}
+
+function SandboxChip(props: { client: LinuxSandboxClient; workspaceId: string; onOpenSettings?: () => void }) {
+ const sandbox = useLinuxSandbox(props.client, props.workspaceId, { fresh: false });
+ const [offerDismissed, setOfferDismissed] = useState(false);
+ const box = sandbox.box;
+ if (!box) return null;
+ const chip = "flex h-9 max-h-9 shrink-0 items-center gap-1.5 rounded-md px-2.5 text-sm text-gray-10 transition-colors hover:bg-gray-3 hover:text-gray-12";
+
+ if (!box.on && sandbox.pending !== "on") {
+ if (!box.offer || offerDismissed) return null;
+ return (
+ <div className="flex shrink-0 items-center rounded-md border border-dashed border-gray-6" data-testid="sandbox-offer-chip">
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button type="button" className={`${chip} h-8 max-h-8 pr-1.5`} onClick={() => void sandbox.setEnabled(true)} data-testid="sandbox-offer-accept" />
+ }
+ >
+ <Box className="size-4" aria-hidden />
+ <span className="whitespace-nowrap">Use sandbox</span>
+ </TooltipTrigger>
+ <TooltipContent>Your omnirush.ai server recommends running this project's commands in a Linux sandbox. Click to turn it on.</TooltipContent>
+ </Tooltip>
+ <button type="button" aria-label="Not now" className="mr-1 flex size-6 items-center justify-center rounded text-gray-9 hover:bg-gray-3 hover:text-gray-12" onClick={() => setOfferDismissed(true)}>
+ <X className="size-3.5" aria-hidden />
+ </button>
+ </div>
+ );
+ }
+
+ const view = linuxSandboxView(box, sandbox.pending);
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-label={`Linux sandbox: ${view.title}`}
+ data-testid="sandbox-status-chip"
+ data-tone={view.tone}
+ className={chip}
+ onClick={props.onOpenSettings}
+ />
+ }
+ >
+ <span className="relative">
+ <Box className="size-4" aria-hidden />
+ <span aria-hidden className={`absolute -right-0.5 -bottom-0.5 size-2 rounded-full ring-2 ring-dls-surface ${DOT[view.tone]}`} />
+ </span>
+ {/* An icon (its state in the tooltip and aria-label) until the composer is wide enough. */}
+ <span className="hidden whitespace-nowrap @min-[760px]/composer:inline">Sandbox</span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <div className="flex max-w-64 flex-col">
+ <span className="font-medium">Linux sandbox: {view.title}</span>
+ {view.progress ? <span>{view.progress.label}</span> : view.detail ? <span>{view.detail}</span> : null}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
index 6dcf5c3f..09db38c6 100644
--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx
+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
@@ -53,6 +53,7 @@ import type {
import { ReactSessionComposer } from "./composer/composer";
import { WorkspaceRunModeMenu } from "./composer/workspace-run-mode-menu";
import { FullPermissionsToggle } from "./composer/full-permissions-toggle";
+import { SandboxStatusChip } from "./composer/sandbox-status-chip";
import { SubagentModelMenu } from "./composer/subagent-model-menu";
import { useSessionModelSelection } from "./session-model-store";
import type { ProviderCatalog } from "./use-model-behavior";
@@ -3477,6 +3478,7 @@ export function SessionSurface(props: SessionSurfaceProps) {
<ReactSessionComposer
runModeControl={<WorkspaceRunModeMenu client={props.client} workspaceId={props.workspaceId} busy={chatStreaming || preparingCloudTools || Boolean(props.activePermission || props.activeQuestion)} />}
fullPermissionsControl={<FullPermissionsToggle client={props.client} workspaceId={props.workspaceId} />}
+ sandboxControl={<SandboxStatusChip client={props.client} workspaceId={props.workspaceId} onOpenSettings={() => props.onOpenSettingsSection?.("sandbox")} />}
subagentModelControl={<SubagentModelMenu client={props.client} />}
voiceClient={props.client}
voiceWorkspaceId={props.workspaceId}
diff --git a/apps/app/src/react-app/domains/settings/library.ts b/apps/app/src/react-app/domains/settings/library.ts
index 23142ba2..9ea0829a 100644
--- a/apps/app/src/react-app/domains/settings/library.ts
+++ b/apps/app/src/react-app/domains/settings/library.ts
@@ -16,7 +16,9 @@ export type ComposerSettingsSection =
| "plugins"
| "connections"
| "extensions"
- | "providers";
+ | "providers"
+ /** Settings > General > Linux sandbox. */
+ | "sandbox";
/** Fallback when Configure has no + menu section (opens the full inventory). */
export const COMPOSER_CONFIGURE_SECTION = "extensions" satisfies ComposerSettingsSection;
@@ -43,7 +45,7 @@ export function composerConfigureSectionForMenu(section: string): ComposerSettin
/** URL tail under /extensions for a composer Configure destination. */
export function libraryPathForSection(section: ComposerSettingsSection): string {
- if (section === "providers" || section === "extensions") return LIBRARY_ROUTE_PATH;
+ if (section === "providers" || section === "extensions" || section === "sandbox") return LIBRARY_ROUTE_PATH;
return section;
}
@@ -153,13 +155,14 @@ export function libraryAgentsFromOpencode(
export type ComposerConfigureDestination =
| { kind: "library"; path: string }
- | { kind: "settings"; route: "/settings/ai" };
+ | { kind: "settings"; route: "/settings/ai" | "/settings/general#linux-sandbox" };
-/** Configure from the composer opens the matching Library filter, except providers. */
+/** Configure from the composer opens the matching Library filter, except providers and the sandbox (Settings). */
export function composerConfigureDestination(
section: ComposerSettingsSection,
): ComposerConfigureDestination {
if (section === "providers") return { kind: "settings", route: "/settings/ai" };
+ if (section === "sandbox") return { kind: "settings", route: "/settings/general#linux-sandbox" };
return { kind: "library", path: libraryPathForSection(section) };
}
diff --git a/apps/app/src/react-app/domains/settings/linux-sandbox-card.tsx b/apps/app/src/react-app/domains/settings/linux-sandbox-card.tsx
new file mode 100644
index 00000000..416123cc
--- /dev/null
+++ b/apps/app/src/react-app/domains/settings/linux-sandbox-card.tsx
@@ -0,0 +1,324 @@
+/** @jsxImportSource react */
+import { useEffect, useId, useRef, useState } from "react";
+import { AlertTriangle, Box, Check, CheckCircle2, ChevronRight, Copy, LoaderCircle, Power, RotateCcw, XCircle } from "lucide-react";
+
+import type { OmniRushWorkspaceBox } from "@/app/lib/omnirush-server";
+import { Button } from "@/components/ui/button";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { Progress as ProgressPrimitive } from "@base-ui/react/progress";
+import { ProgressIndicator, ProgressTrack } from "@/components/ui/progress";
+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { ConfirmModal } from "@/react-app/design-system/modals/confirm-modal";
+
+import {
+ LINUX_SANDBOX_HELP,
+ linuxSandboxBackendChoices,
+ linuxSandboxBackendSummary,
+ linuxSandboxView,
+ type LinuxSandboxNextStep,
+ type LinuxSandboxPending,
+ type LinuxSandboxProblem,
+ type LinuxSandboxView,
+} from "./linux-sandbox";
+
+export type LinuxSandboxCardProps = {
+ box: OmniRushWorkspaceBox | null;
+ pending: LinuxSandboxPending;
+ problem: LinuxSandboxProblem | null;
+ notice: string;
+ onToggle: (enabled: boolean) => void;
+ onRetry: () => void;
+ onReset: () => void;
+ onBackend?: (backend: string) => void;
+ /** Opens the Advanced section from the start (tests, a link to the backend). */
+ defaultAdvancedOpen?: boolean;
+};
+
+const TONE_CLASS: Record<LinuxSandboxView["tone"], string> = {
+ off: "text-dls-secondary",
+ busy: "text-dls-secondary",
+ ready: "text-green-11",
+ attention: "text-amber-11",
+ error: "text-red-11",
+};
+
+function ToneIcon({ tone }: { tone: LinuxSandboxView["tone"] }) {
+ const className = `mt-px size-4 shrink-0 ${TONE_CLASS[tone]}`;
+ switch (tone) {
+ case "busy":
+ return <LoaderCircle aria-hidden className={`${className} motion-safe:animate-spin`} />;
+ case "ready":
+ return <CheckCircle2 aria-hidden className={className} />;
+ case "attention":
+ return <AlertTriangle aria-hidden className={className} />;
+ case "error":
+ return <XCircle aria-hidden className={className} />;
+ default:
+ return <Power aria-hidden className={className} />;
+ }
+}
+
+function CopyCommand({ command }: { command: string }) {
+ const [copied, setCopied] = useState(false);
+ useEffect(() => {
+ if (!copied) return;
+ const timer = setTimeout(() => setCopied(false), 1_500);
+ return () => clearTimeout(timer);
+ }, [copied]);
+ return (
+ <div className="mt-2 flex items-center gap-2 rounded-lg border border-dls-border bg-dls-hover py-1 pl-3 pr-1">
+ <code className="min-w-0 flex-1 truncate font-mono text-[11px] text-dls-text" title={command} data-testid="linux-sandbox-command">{command}</code>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={copied ? "Copied" : "Copy command"}
+ onClick={() => void navigator.clipboard?.writeText(command).then(() => setCopied(true)).catch(() => undefined)}
+ >
+ {copied ? <Check aria-hidden /> : <Copy aria-hidden />}
+ </Button>
+ </div>
+ );
+}
+
+function NextStep({ step }: { step: LinuxSandboxNextStep }) {
+ return (
+ <div className="text-[11px] text-dls-secondary" data-testid="linux-sandbox-next-step">
+ <div className="mt-1">{step.detail}</div>
+ {step.command ? <CopyCommand command={step.command} /> : null}
+ </div>
+ );
+}
+
+function Details({ text }: { text: string }) {
+ const [open, setOpen] = useState(false);
+ return (
+ <Collapsible open={open} onOpenChange={setOpen}>
+ <CollapsibleTrigger className="mt-1 inline-flex items-center gap-0.5 rounded text-[11px] text-dls-secondary underline-offset-2 hover:text-dls-text hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-dls-border">
+ <ChevronRight aria-hidden className={`size-3 motion-safe:transition-transform ${open ? "rotate-90" : ""}`} />
+ {open ? "Hide details" : "Show details"}
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <pre className="mt-1 max-h-32 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-dls-border bg-dls-hover p-2 font-mono text-[11px] text-dls-secondary" data-testid="linux-sandbox-error-detail">{text}</pre>
+ </CollapsibleContent>
+ </Collapsible>
+ );
+}
+
+/** The status row: one icon, one title, one line (or the download bar), one button; same height in every state. */
+function StatusRow(props: { view: LinuxSandboxView; busy: boolean; onAction: () => void }) {
+ const { view } = props;
+ return (
+ <div className="px-4 py-3" data-testid="linux-sandbox-status" data-tone={view.tone}>
+ <div className="flex min-h-9 items-start gap-3">
+ <ToneIcon tone={view.tone} />
+ <div className="min-w-0 flex-1">
+ <div className="text-[12px] font-medium text-dls-text" role="status" aria-live="polite" data-testid="linux-sandbox-state">{view.title}</div>
+ {view.progress ? (
+ <ProgressPrimitive.Root
+ value={view.progress.value}
+ aria-label="Sandbox download"
+ getAriaValueText={() => view.progress?.label ?? ""}
+ className="flex h-[18px] items-center gap-2"
+ data-testid="linux-sandbox-progress"
+ >
+ <ProgressTrack className="h-1.5 flex-1 bg-dls-hover">
+ <ProgressIndicator className={`rounded-full bg-dls-text/70 motion-safe:duration-500 motion-reduce:transition-none ${view.progress.value === null ? "w-1/4 motion-safe:animate-pulse" : ""}`} />
+ </ProgressTrack>
+ <span className="shrink-0 text-[11px] tabular-nums text-dls-secondary">{view.progress.label}</span>
+ </ProgressPrimitive.Root>
+ ) : view.detail ? (
+ <div className="text-[11px] leading-[18px] text-dls-secondary" data-testid="linux-sandbox-detail">{view.detail}</div>
+ ) : null}
+ {view.step ? <NextStep step={view.step} /> : null}
+ {view.errorDetail ? <Details text={view.errorDetail} /> : null}
+ </div>
+ {view.action ? (
+ <Button variant="outline" size="xs" disabled={props.busy} onClick={props.onAction}>
+ {view.action.kind === "auto-backend" ? null : <RotateCcw aria-hidden />}
+ {view.action.label}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function Advanced(props: { box: OmniRushWorkspaceBox; busy: boolean; defaultOpen: boolean; onBackend?: (backend: string) => void; onReset: () => void }) {
+ const { box } = props;
+ const [open, setOpen] = useState(props.defaultOpen);
+ const [confirmReset, setConfirmReset] = useState(false);
+ const selectId = useId();
+ const choices = linuxSandboxBackendChoices(box);
+ const others = (box.backend?.alternatives ?? []).filter((alt) => alt.id !== box.backend?.id);
+ const lockedByEnv = box.backendSetting.source === "env";
+ const canReset = Boolean(box.container?.exists);
+ return (
+ <Collapsible open={open} onOpenChange={setOpen} className="border-t border-dls-border">
+ <CollapsibleTrigger className="flex w-full items-center gap-1.5 rounded-b-2xl px-4 py-2.5 text-left text-[12px] text-dls-secondary hover:text-dls-text focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-dls-border" data-testid="linux-sandbox-advanced">
+ <ChevronRight aria-hidden className={`size-3.5 motion-safe:transition-transform ${open ? "rotate-90" : ""}`} />
+ <span className="font-medium">Advanced</span>
+ <span className={`ml-auto truncate text-[11px] ${open ? "invisible" : ""}`}>{choices.find((choice) => choice.value === box.backendSetting.value)?.label ?? box.backendSetting.value}</span>
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <div className="space-y-4 px-4 pb-4 pt-1">
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <div className="min-w-0 flex-1">
+ <label htmlFor={selectId} className="text-[12px] font-medium text-dls-text">Backend</label>
+ <div className="text-[11px] text-dls-secondary" data-testid="linux-sandbox-backend">{linuxSandboxBackendSummary(box)}</div>
+ </div>
+ {props.onBackend ? (
+ <div className="w-full sm:w-56">
+ <Select
+ value={box.backendSetting.value}
+ items={choices}
+ onValueChange={(value) => {
+ if (typeof value === "string" && value !== box.backendSetting.value) props.onBackend?.(value);
+ }}
+ disabled={props.busy || lockedByEnv}
+ >
+ <SelectTrigger id={selectId} className="w-full" aria-label="Sandbox backend">
+ <SelectValue placeholder="Automatic (recommended)" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {choices.map((item) => (
+ <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ </div>
+ ) : null}
+ </div>
+ {others.length ? (
+ <div>
+ <div className="text-[11px] font-medium text-dls-secondary">Other backends on this computer</div>
+ <ul className="mt-1 space-y-0.5" data-testid="linux-sandbox-others">
+ {others.map((alt) => (
+ <li key={alt.id} className="flex min-w-0 items-baseline gap-2 text-[11px]">
+ <span aria-hidden className={`size-1.5 shrink-0 translate-y-[-1px] rounded-full ${alt.ok ? "bg-green-9" : "bg-gray-7"}`} />
+ <span className="shrink-0 text-dls-text">{alt.label}</span>
+ <span className="min-w-0 truncate text-dls-secondary" title={alt.reason ?? undefined}>{alt.ok ? "available" : alt.reason ?? "not available"}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <div className="min-w-0 flex-1">
+ <div className="text-[12px] font-medium text-dls-text">Reset sandbox</div>
+ <div className="text-[11px] text-dls-secondary">
+ {canReset ? "Removes this project's container and everything installed in it. Your project files are not touched." : "Nothing to reset: this project has no sandbox yet."}
+ </div>
+ </div>
+ <Button variant="destructive" size="xs" disabled={props.busy || !canReset} onClick={() => setConfirmReset(true)}>Reset…</Button>
+ </div>
+ </div>
+ </CollapsibleContent>
+ <ConfirmModal
+ open={confirmReset}
+ variant="danger"
+ title="Reset the sandbox?"
+ message="This removes the project's Linux container and everything installed in it. Your project files stay as they are. The next command starts a fresh sandbox."
+ confirmLabel="Reset sandbox"
+ cancelLabel="Cancel"
+ onCancel={() => setConfirmReset(false)}
+ onConfirm={() => {
+ setConfirmReset(false);
+ props.onReset();
+ }}
+ />
+ </Collapsible>
+ );
+}
+
+/**
+ * Settings > General > Linux sandbox (beta), for the selected project: the
+ * switch, one status row, the server's offer, and the backend and Reset
+ * under Advanced.
+ */
+export function LinuxSandboxCard(props: LinuxSandboxCardProps) {
+ const { box, pending } = props;
+ const [offerDismissed, setOfferDismissed] = useState(false);
+ const switchId = useId();
+ const sectionRef = useRef<HTMLElement>(null);
+ // Opened from the composer's sandbox chip (#linux-sandbox): bring the card into view.
+ useEffect(() => {
+ if (typeof window === "undefined" || window.location.hash !== "#linux-sandbox") return;
+ const reduce = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
+ sectionRef.current?.scrollIntoView({ block: "center", behavior: reduce ? "auto" : "smooth" });
+ }, []);
+ const busy = pending !== null;
+ // The switch shows the user's choice at once; the server's answer follows.
+ const checked = pending === "on" ? true : pending === "off" ? false : box?.on === true;
+ const view = box ? linuxSandboxView(box, pending) : null;
+ const showOffer = Boolean(box?.offer && !box.on && !busy && !offerDismissed);
+ const action = () => {
+ if (view?.action?.kind === "auto-backend") props.onBackend?.("auto");
+ else props.onRetry();
+ };
+ return (
+ <section ref={sectionRef} className="scroll-mt-6 space-y-3" id="linux-sandbox" aria-labelledby={`${switchId}-heading`} data-testid="linux-sandbox-card">
+ <div id={`${switchId}-heading`} className="text-[11px] font-semibold uppercase tracking-[0.15em] text-dls-secondary">Linux sandbox</div>
+ <div className="rounded-2xl border border-dls-border bg-dls-surface">
+ <div className="flex items-center gap-4 p-4">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-dls-border bg-dls-hover">
+ <Box size={17} aria-hidden className={box?.on && box.state === "ready" ? "text-green-11" : "text-dls-secondary"} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <label htmlFor={switchId} className="text-[13px] font-medium text-dls-text">Run commands in a Linux sandbox</label>
+ <span className="rounded-full border border-dls-border px-1.5 py-px text-[10px] font-medium uppercase tracking-wide text-dls-secondary">Beta</span>
+ </div>
+ <div id="linux-sandbox-help" className="text-[11px] text-dls-secondary">{LINUX_SANDBOX_HELP}</div>
+ {/* TODO(Sam): data-collection wording for sandboxed chats goes here (what uploads record about the
+ sandbox: Linux as the OS, the container image, per-turn changes outside the project). No copy yet. */}
+ </div>
+ <Switch
+ id={switchId}
+ aria-label="Run commands in a Linux sandbox"
+ aria-describedby="linux-sandbox-help"
+ aria-busy={busy || undefined}
+ checked={checked}
+ disabled={busy || !box || box.source === "env"}
+ onCheckedChange={props.onToggle}
+ />
+ </div>
+
+ {showOffer ? (
+ <div className="mx-4 mb-3 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-xl border border-dls-border bg-dls-hover px-3 py-2" data-testid="linux-sandbox-offer">
+ <div className="min-w-0 flex-1 text-[11px] text-dls-text">Your omnirush.ai server recommends the sandbox for this project.</div>
+ <div className="flex items-center gap-1.5">
+ <Button size="xs" onClick={() => props.onToggle(true)}>Turn on</Button>
+ <Button size="xs" variant="ghost" onClick={() => setOfferDismissed(true)}>Not now</Button>
+ </div>
+ </div>
+ ) : null}
+
+ <div className="border-t border-dls-border">
+ {view ? (
+ <StatusRow view={view} busy={busy} onAction={action} />
+ ) : (
+ <div className="px-4 py-3" data-testid="linux-sandbox-status" data-tone="loading">
+ <div className="flex min-h-9 items-start gap-3">
+ <LoaderCircle aria-hidden className="mt-px size-4 shrink-0 text-dls-secondary motion-safe:animate-spin" />
+ <div className="text-[12px] text-dls-secondary" role="status">Checking the sandbox…</div>
+ </div>
+ </div>
+ )}
+ {props.problem || props.notice ? (
+ <div className="-mt-1 flex items-center gap-2 px-4 pb-3 pl-11 text-[11px]" data-testid="linux-sandbox-message">
+ <span className={props.problem ? "text-red-11" : "text-dls-secondary"} role={props.problem ? "alert" : "status"}>{props.problem?.message ?? props.notice}</span>
+ {props.problem?.retry ? (
+ <Button variant="link" size="xs" className="h-auto px-0" onClick={props.problem.retry}>Try again</Button>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+
+ {box ? <Advanced box={box} busy={busy} defaultOpen={props.defaultAdvancedOpen ?? false} onBackend={props.onBackend} onReset={props.onReset} /> : null}
+ </div>
+ </section>
+ );
+}
diff --git a/apps/app/src/react-app/domains/settings/linux-sandbox.ts b/apps/app/src/react-app/domains/settings/linux-sandbox.ts
index 48aa6687..e4fc09d6 100644
--- a/apps/app/src/react-app/domains/settings/linux-sandbox.ts
+++ b/apps/app/src/react-app/domains/settings/linux-sandbox.ts
@@ -1,140 +1,276 @@
import { useCallback, useEffect, useRef, useState } from "react";
-import type { OmniRushServerClient, OmniRushWorkspaceBox } from "@/app/lib/omnirush-server";
+import type { OmniRushServerClient, OmniRushWorkspaceBox, OmniRushWorkspaceBoxProgress } from "@/app/lib/omnirush-server";
-export type LinuxSandboxClient = Pick<OmniRushServerClient, "getWorkspaceBox" | "setWorkspaceBox" | "setWorkspaceBoxBackend" | "resetWorkspaceBox">;
+export type LinuxSandboxClient = Pick<OmniRushServerClient, "getWorkspaceBox" | "setWorkspaceBox" | "setWorkspaceBoxBackend" | "resetWorkspaceBox" | "retryWorkspaceBox">;
export const LINUX_SANDBOX_HELP = "Commands run in a Linux container for this project. Your files stay in this folder; installs are kept per project.";
-/** The one line under the switch: what the sandbox is doing now, or why it is not used. */
-export function linuxSandboxStatusLine(box: OmniRushWorkspaceBox): string {
+/** What the user can do next when no sandbox backend works here: one step, with a command to copy when there is one. */
+export type LinuxSandboxNextStep = { title: string; detail: string; command: string | null };
+
+/** Everything the status row shows. `tone` picks its icon and colour. */
+export type LinuxSandboxView = {
+ tone: "off" | "busy" | "ready" | "attention" | "error";
+ title: string;
+ detail: string | null;
+ /** A bar while the image downloads: `value` 0–100, null when the size is not known yet. */
+ progress: { value: number | null; label: string } | null;
+ step: LinuxSandboxNextStep | null;
+ /** The row's button: try again, look again, or switch the backend back to automatic. */
+ action: { kind: "retry" | "check" | "auto-backend"; label: string } | null;
+ /** The raw error, behind "Show details". */
+ errorDetail: string | null;
+};
+
+/** A change the user made that the server has not answered yet (the switch already shows it). */
+export type LinuxSandboxPending = "on" | "off" | "backend" | "reset" | "retry" | null;
+
+const RUNS_HERE = "Commands run on this computer for now.";
+const LOAD_FAILED = "The sandbox status could not be loaded.";
+
+function runtimeLabel(box: OmniRushWorkspaceBox): string | null {
+ const backend = box.backend;
+ if (backend?.id) return [backend.label ?? backend.id, backend.version].filter(Boolean).join(" ");
+ if (box.runtime?.ok && box.runtime.name) return [box.runtime.name, box.runtime.version].filter(Boolean).join(" ");
+ return null;
+}
+
+function megabytes(bytes: number): string {
+ const mb = bytes / 1_000_000;
+ return mb >= 100 ? `${Math.round(mb)}` : mb >= 10 ? mb.toFixed(0) : mb.toFixed(1);
+}
+
+/** The download bar: bytes when the server knows the layer sizes, else layers, else the image's rough size. */
+export function linuxSandboxProgress(progress: OmniRushWorkspaceBoxProgress | null | undefined): { value: number | null; label: string } {
+ if (progress?.bytesTotal && progress.bytesDone !== null) {
+ const value = Math.min(100, Math.round((progress.bytesDone / progress.bytesTotal) * 100));
+ return { value, label: `${megabytes(progress.bytesDone)} of ${megabytes(progress.bytesTotal)} MB · ${value}%` };
+ }
+ if (progress && progress.layersTotal > 0) {
+ const value = Math.min(100, Math.round((progress.layersDone / progress.layersTotal) * 100));
+ return { value, label: `${progress.layersDone} of ${progress.layersTotal} parts · ${value}%` };
+ }
+ return { value: null, label: "Starting the download…" };
+}
+
+function commandIn(reason: string | null | undefined): string | null {
+ return reason ? /`([^`]+)`/.exec(reason)?.[1] ?? null : null;
+}
+
+/** A short title for a reason the backend probe gave (with its command, when it names one). */
+function stepFor(reason: string, platform: string | undefined): LinuxSandboxNextStep | null {
+ const command = commandIn(reason);
+ if (/sandbox enable/.test(reason)) return { title: "Allow the sandbox on this computer", detail: "Ubuntu blocks it until an admin allows it once. Run this in a terminal (OmniRush CLI), then check again.", command };
+ if (/usermod -aG docker/.test(reason)) return { title: "Let this user run Docker", detail: "Run this in a terminal, log out and back in, then check again.", command };
+ if (/wsl --install/.test(reason)) return { title: "Turn on WSL 2", detail: "Run this in PowerShell as administrator, restart the computer, then check again.", command: "wsl --install --no-distribution" };
+ if (/wsl --update/.test(reason)) return { title: "Update WSL", detail: "Run this in PowerShell, then check again.", command };
+ if (/podman machine start/.test(reason)) return { title: "Start the Podman machine", detail: "Run this in a terminal, then check again.", command };
+ if (/apt install bubblewrap/.test(reason)) return { title: "Install bubblewrap", detail: "Run this in a terminal (or use your system's package), then check again.", command };
+ if (/Docker Desktop is installed but not running|Docker is installed but not running/.test(reason)) {
+ return { title: "Start your container app", detail: "Open Docker Desktop, OrbStack or colima, wait until it is running, then check again.", command: null };
+ }
+ if (/Docker daemon is not running/.test(reason)) return { title: "Start Docker", detail: "Run this in a terminal, then check again.", command: "sudo systemctl start docker" };
+ return null;
+}
+
+/**
+ * The one next step when no backend works here: the first fix a backend's
+ * probe names (in the order they are tried), else the usual setup for this
+ * computer's OS.
+ */
+export function linuxSandboxNextStep(box: OmniRushWorkspaceBox): LinuxSandboxNextStep {
+ const platform = box.platform;
+ const reasons = [...(box.backend?.alternatives ?? []).map((alt) => alt.reason), box.runtime?.reason ?? null].filter((reason): reason is string => Boolean(reason));
+ for (const reason of reasons) {
+ const step = stepFor(reason, platform);
+ if (step) return step;
+ }
+ if (platform === "win32") return { title: "Turn on WSL 2", detail: "Run this in PowerShell as administrator, restart the computer, then check again. Docker Desktop or Podman work too.", command: "wsl --install --no-distribution" };
+ if (platform === "darwin") return { title: "Install a container app", detail: "colima is free and installs with Homebrew; OrbStack and Docker Desktop work too. Then check again.", command: "brew install colima docker && colima start" };
+ if (platform === "linux") return { title: "Install Podman or Docker", detail: "Run this in a terminal (or use your system's package), then check again.", command: "sudo apt install podman" };
+ return { title: "No sandbox backend works here", detail: box.runtime?.reason ?? "No container runtime was found on this computer.", command: null };
+}
+
+/** The status row: what the sandbox is doing now, or why it is not used and what to do. */
+export function linuxSandboxView(box: OmniRushWorkspaceBox, pending: LinuxSandboxPending = null): LinuxSandboxView {
+ const base = { progress: null, step: null, action: null, errorDetail: null };
+ if (pending === "on") return { ...base, tone: "busy", title: "Turning on…", detail: RUNS_HERE.replace(" for now", " until the sandbox is ready") };
+ if (pending === "off") return { ...base, tone: "busy", title: "Turning off…", detail: null };
+ if (pending === "reset") return { ...base, tone: "busy", title: "Resetting the sandbox…", detail: "Removing its container and installs." };
+ if (pending === "retry") return { ...base, tone: "busy", title: "Trying again…", detail: null };
if (!box.on) {
- if (box.offer) return "Your omnirush.ai server suggests turning this on for this project.";
- if (box.source === "env") return "Turned off for this app (OMNIRUSH_BOX).";
- return "Off. Commands run on this computer.";
+ if (box.source === "env") return { ...base, tone: "off", title: "Off for this app", detail: "Set by OMNIRUSH_BOX where the app is launched." };
+ return { ...base, tone: "off", title: "Off", detail: "Commands run on this computer." };
}
- const runtime = box.runtime?.ok ? [box.runtime.name, box.runtime.flavor && box.runtime.flavor !== "engine" ? box.runtime.flavor : null].filter(Boolean).join(", ") : null;
+ const using = runtimeLabel(box);
switch (box.state) {
- case "unavailable":
- return box.notice ?? `Not available: ${box.runtime?.reason ?? "no container runtime found"}. Commands run on this computer.`;
case "downloading":
- return "Downloading the sandbox image (once). Commands run on this computer until it is ready.";
+ return { ...base, tone: "busy", title: "Downloading the sandbox (once)", detail: RUNS_HERE.replace(" for now", " until it is ready"), progress: linuxSandboxProgress(box.progress) };
case "starting":
- return runtime ? `Starting the sandbox (${runtime})…` : "Starting the sandbox…";
+ return { ...base, tone: "busy", title: "Starting the sandbox…", detail: using ? `Using ${using}. This takes a few seconds.` : "This takes a few seconds." };
case "ready":
- return `Ready${runtime ? ` (${runtime})` : ""}${box.container?.running ? ", container running" : ""}.`;
+ return { ...base, tone: "ready", title: "Ready", detail: using ? `Commands run in a Linux container (${using}).` : "Commands run in a Linux container." };
case "failed":
- return `The sandbox could not start${box.error ? `: ${box.error}` : ""}. Commands run on this computer.`;
+ return { ...base, tone: "error", title: "The sandbox could not start", detail: RUNS_HERE, action: { kind: "retry", label: "Try again" }, errorDetail: box.error ?? box.notice };
+ case "unavailable": {
+ if (box.backendSetting.value === "native") {
+ return { ...base, tone: "attention", title: "The backend is set to Off", detail: "Commands run on this computer. Choose Automatic to use the sandbox.", action: { kind: "auto-backend", label: "Use automatic" } };
+ }
+ if (box.runtime?.ok) {
+ // A backend works, but this project went on without the box (its helpers, a start that timed out).
+ return { ...base, tone: "attention", title: "The sandbox is not running", detail: RUNS_HERE, action: { kind: "retry", label: "Try again" }, errorDetail: box.notice?.replace(/^Sandbox off for now: /, "").replace(/\.$/, "") ?? box.error };
+ }
+ const step = linuxSandboxNextStep(box);
+ return { ...base, tone: "attention", title: step.title, detail: RUNS_HERE, step, action: { kind: "check", label: "Check again" }, errorDetail: box.runtime?.reason ?? null };
+ }
case "off":
- return box.notice ?? "Off. Commands run on this computer.";
+ return { ...base, tone: "off", title: "Off", detail: box.notice ?? "Commands run on this computer." };
}
}
-/** "Backend: <label> <version>": what runs the sandbox on this computer. */
-export function linuxSandboxBackendLine(box: OmniRushWorkspaceBox): string {
- if (box.backendSetting.value === "native") return "Backend: off (commands run on this computer)";
- const backend = box.backend;
- if (!backend?.id) return "Backend: none available";
- return `Backend: ${[backend.label ?? backend.id, backend.version].filter(Boolean).join(" ")}`;
+/** The backend in use and how it was picked, for the Advanced section. */
+export function linuxSandboxBackendSummary(box: OmniRushWorkspaceBox): string {
+ if (box.backendSetting.value === "native") return "Set to Off: commands run on this computer.";
+ const using = runtimeLabel(box);
+ if (!using) return "No backend works on this computer yet.";
+ if (box.backendSetting.source === "env") return `Using ${using} (set by OMNIRUSH_BOX_BACKEND).`;
+ return box.backendSetting.value === "auto" ? `Using ${using}, picked automatically.` : `Using ${using}.`;
}
-/** The other backends here, one short entry each: available, or why not. */
-export function linuxSandboxOthersLine(box: OmniRushWorkspaceBox): string | null {
- const others = (box.backend?.alternatives ?? []).filter((alt) => alt.id !== box.backend?.id);
- if (!others.length) return null;
- return `Others: ${others.map((alt) => `${alt.label} (${alt.ok ? "available" : alt.reason ?? "not available"})`).join("; ")}`;
+/** The backend choices for the picker: "Automatic (recommended)" first. */
+export function linuxSandboxBackendChoices(box: OmniRushWorkspaceBox): Array<{ value: string; label: string }> {
+ return box.backendSetting.choices.map((choice) => ({ value: choice.id, label: choice.id === "auto" ? "Automatic (recommended)" : choice.label }));
}
-/** States that change on their own: the card asks again while it shows one. */
+/** States that change on their own: asked about again quickly while they last. */
const MOVING = new Set<OmniRushWorkspaceBox["state"]>(["downloading", "starting"]);
-const POLL_MS = 5_000;
+/** Poll every second while the sandbox moves, slower after a minute (a long download). */
+const FAST_POLL_MS = 1_000;
+const SLOW_POLL_MS = 3_000;
+const FAST_FOR_MS = 60_000;
+
+export function linuxSandboxMoving(box: OmniRushWorkspaceBox | null): boolean {
+ return Boolean(box?.on && MOVING.has(box.state));
+}
+
+export type LinuxSandboxProblem = { message: string; retry: (() => void) | null };
-/** The selected workspace's sandbox: its status (polled while it moves), the switch and Reset. */
-export function useLinuxSandbox(client: LinuxSandboxClient | null, workspaceId: string | null) {
+/**
+ * The selected workspace's sandbox: its status (asked again every second
+ * while it moves, and when the window comes back), the switch (shown at
+ * once, before the server answers), the backend, Retry and Reset.
+ */
+export function useLinuxSandbox(client: LinuxSandboxClient | null, workspaceId: string | null, { fresh: freshOnOpen = true }: { fresh?: boolean } = {}) {
const [box, setBox] = useState<OmniRushWorkspaceBox | null>(null);
- const [busy, setBusy] = useState(false);
- const [status, setStatus] = useState("");
+ const [pending, setPending] = useState<LinuxSandboxPending>(null);
+ const [problem, setProblem] = useState<LinuxSandboxProblem | null>(null);
+ const [notice, setNotice] = useState("");
const sequence = useRef(0);
+ const movingSince = useRef<number | null>(null);
const load = useCallback(async (fresh = false) => {
if (!client || !workspaceId) return;
const startedAt = sequence.current;
const value = await client.getWorkspaceBox(workspaceId, { fresh }).catch(() => null);
if (sequence.current !== startedAt) return;
- if (value) setBox(value);
- else setStatus("The sandbox status could not be loaded.");
+ if (value) {
+ setBox(value);
+ setProblem((current) => (current?.message === LOAD_FAILED ? null : current));
+ } else {
+ setProblem({ message: LOAD_FAILED, retry: () => void load(true) });
+ }
}, [client, workspaceId]);
+ // Another project: start from nothing. The same project with a new client (the engine
+ // reloaded after the switch): keep what is shown and ask again, so nothing flickers.
+ const shownFor = useRef<string | null>(null);
useEffect(() => {
- sequence.current += 1;
- setBox(null);
- setBusy(false);
- setStatus("");
- void load(true);
- }, [load]);
+ if (shownFor.current !== workspaceId) {
+ shownFor.current = workspaceId;
+ sequence.current += 1;
+ setBox(null);
+ setPending(null);
+ setProblem(null);
+ setNotice("");
+ }
+ void load(freshOnOpen);
+ }, [load, freshOnOpen, workspaceId]);
+ // While it moves: every second for a minute, then every 3 s.
+ const moving = linuxSandboxMoving(box);
useEffect(() => {
- if (!box || !box.on || !MOVING.has(box.state)) return;
- const timer = setTimeout(() => void load(), POLL_MS);
+ if (!moving) {
+ movingSince.current = null;
+ return;
+ }
+ movingSince.current ??= Date.now();
+ const delay = Date.now() - movingSince.current < FAST_FOR_MS ? FAST_POLL_MS : SLOW_POLL_MS;
+ const timer = setTimeout(() => void load(), delay);
return () => clearTimeout(timer);
- }, [box, load]);
+ }, [box, moving, load]);
- const setEnabled = useCallback(async (enabled: boolean) => {
- if (!client || !workspaceId || busy) return;
+ // Back to the window (a runtime started or installed meanwhile): look again.
+ useEffect(() => {
+ if (typeof document === "undefined") return;
+ const onVisible = () => {
+ if (document.visibilityState === "visible" && !pending) void load(freshOnOpen);
+ };
+ document.addEventListener("visibilitychange", onVisible);
+ return () => document.removeEventListener("visibilitychange", onVisible);
+ }, [freshOnOpen, load, pending]);
+
+ /** One change at a time; an answer to an older request never overwrites a newer one. */
+ const change = useCallback(async (kind: Exclude<LinuxSandboxPending, null>, act: () => Promise<OmniRushWorkspaceBox | null>, failure: string, again: () => void) => {
+ if (!client || !workspaceId || pending) return;
sequence.current += 1;
const startedAt = sequence.current;
- setBusy(true);
- setStatus(enabled ? "Turning the sandbox on…" : "Turning the sandbox off…");
+ setPending(kind);
+ setProblem(null);
+ setNotice("");
try {
- const result = await client.setWorkspaceBox(workspaceId, enabled ? "on" : "off");
+ const result = await act();
if (sequence.current !== startedAt) return;
- setBox(result);
- setStatus(result.engine.status === "failed" ? "Saved. The engine change could not be confirmed: use Reload in Settings." : "");
+ if (result) setBox(result);
} catch {
if (sequence.current !== startedAt) return;
- setStatus("The choice could not be saved. Try again.");
+ setProblem({ message: failure, retry: again });
} finally {
- if (sequence.current === startedAt) setBusy(false);
+ if (sequence.current === startedAt) setPending(null);
}
- }, [busy, client, workspaceId]);
+ }, [client, pending, workspaceId]);
- const reset = useCallback(async () => {
- if (!client || !workspaceId || busy) return;
- sequence.current += 1;
- const startedAt = sequence.current;
- setBusy(true);
- setStatus("Resetting the sandbox…");
- try {
+ const setEnabled = useCallback((enabled: boolean) => {
+ if (!client || !workspaceId) return Promise.resolve();
+ return change(enabled ? "on" : "off", async () => {
+ const result = await client.setWorkspaceBox(workspaceId, enabled ? "on" : "off");
+ if (result.engine.status === "failed") setNotice("Saved. The engine did not confirm the change: use Reload in Settings > Advanced.");
+ return result;
+ }, enabled ? "The sandbox could not be turned on." : "The sandbox could not be turned off.", () => void setEnabled(enabled));
+ }, [change, client, workspaceId]);
+
+ const setBackend = useCallback((backend: string) => {
+ if (!client || !workspaceId) return Promise.resolve();
+ return change("backend", () => client.setWorkspaceBoxBackend(workspaceId, backend), "The backend could not be saved.", () => void setBackend(backend));
+ }, [change, client, workspaceId]);
+
+ const retry = useCallback(() => {
+ if (!client || !workspaceId) return Promise.resolve();
+ return change("retry", () => client.retryWorkspaceBox(workspaceId), "The sandbox could not be asked to try again.", () => void retry());
+ }, [change, client, workspaceId]);
+
+ const reset = useCallback(() => {
+ if (!client || !workspaceId) return Promise.resolve();
+ return change("reset", async () => {
const result = await client.resetWorkspaceBox(workspaceId);
- if (sequence.current !== startedAt) return;
- setStatus(result.removed ? "Sandbox reset. The next chat starts a fresh one." : "There was no sandbox to reset.");
- } catch {
- if (sequence.current !== startedAt) return;
- setStatus("The sandbox could not be reset. Try again.");
- } finally {
- if (sequence.current === startedAt) setBusy(false);
- }
- await load(true);
- }, [busy, client, load, workspaceId]);
+ setNotice(result.removed ? "Sandbox reset. The next command starts a fresh one." : "There was no sandbox to reset.");
+ return client.getWorkspaceBox(workspaceId, { fresh: true }).catch(() => null);
+ }, "The sandbox could not be reset.", () => void reset());
+ }, [change, client, workspaceId]);
- const setBackend = useCallback(async (backend: string) => {
- if (!client || !workspaceId || busy) return;
- sequence.current += 1;
- const startedAt = sequence.current;
- setBusy(true);
- setStatus("Saving the backend…");
- try {
- const result = await client.setWorkspaceBoxBackend(workspaceId, backend);
- if (sequence.current !== startedAt) return;
- setBox(result);
- setStatus("");
- } catch {
- if (sequence.current !== startedAt) return;
- setStatus("The backend could not be saved. Try again.");
- } finally {
- if (sequence.current === startedAt) setBusy(false);
- }
- }, [busy, client, workspaceId]);
+ const refresh = useCallback(() => load(true), [load]);
- return { box, busy, status, setEnabled, setBackend, reset };
+ return { box, pending, problem, notice, setEnabled, setBackend, retry, reset, refresh };
}
+
+export type LinuxSandboxState = ReturnType<typeof useLinuxSandbox>;
diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
index 8b4858bc..fdd60065 100644
--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
@@ -10,15 +10,12 @@ import {
ShieldCheck,
Sparkles,
Terminal,
- Box,
Wrench,
UserRoundCheck,
} from "lucide-react";
import type { OmniRushAccountSignOutReason } from "@omnirush/types/desktop-ipc";
-import { Button } from "@/components/ui/button";
-import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { t } from "../../../../i18n";
import type { SettingsTab } from "../../../../app/types";
@@ -27,7 +24,7 @@ import {
omnirushAccountSignOut,
omnirushAccountStatus,
} from "../../../../app/lib/desktop";
-import type { OmniRushRuntimeApprovals, OmniRushWorkspaceBox } from "../../../../app/lib/omnirush-server";
+import type { OmniRushRuntimeApprovals } from "../../../../app/lib/omnirush-server";
import { omnirushUsageSummary } from "../../../../app/lib/omnirush-usage";
import { isElectronRuntime } from "../../../../app/utils";
import {
@@ -38,7 +35,8 @@ import {
} from "../approval-mode";
import { DiagnosticsSection } from "./diagnostics-section";
import { BEST_PRACTICES_HELP, useBestPractices, type BestPracticesClient } from "../best-practices";
-import { LINUX_SANDBOX_HELP, linuxSandboxBackendLine, linuxSandboxOthersLine, linuxSandboxStatusLine, useLinuxSandbox, type LinuxSandboxClient } from "../linux-sandbox";
+import { useLinuxSandbox, type LinuxSandboxClient } from "../linux-sandbox";
+import { LinuxSandboxCard } from "../linux-sandbox-card";
export type GeneralSettingsViewProps = {
onNavigateTab: (tab: SettingsTab) => void;
@@ -218,85 +216,6 @@ export function BestPracticesCard(props: {
);
}
-/**
- * Settings > General > Linux sandbox (beta): the selected project's choice,
- * what the sandbox is doing, and Reset (removes its container and installs).
- */
-export function LinuxSandboxCard(props: {
- box: OmniRushWorkspaceBox | null;
- busy: boolean;
- status: string;
- onToggle: (enabled: boolean) => void;
- onReset: () => void;
- onBackend?: (backend: string) => void;
-}) {
- const box = props.box;
- const backendItems = box?.backendSetting.choices.map((choice) => ({ value: choice.id, label: choice.label })) ?? [];
- const others = box ? linuxSandboxOthersLine(box) : null;
- return (
- <div className="space-y-3">
- <div className="text-[11px] font-semibold uppercase tracking-[0.15em] text-dls-secondary">Linux sandbox</div>
- <div className="flex items-center gap-4 rounded-2xl border border-dls-border bg-dls-surface p-4">
- <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-dls-border bg-dls-hover">
- <Box size={17} className="text-dls-secondary" />
- </div>
- <div className="min-w-0 flex-1">
- <div className="text-[13px] font-medium text-dls-text">Run commands in a Linux sandbox (beta)</div>
- <div id="linux-sandbox-help" className="text-[11px] text-dls-secondary">{LINUX_SANDBOX_HELP}</div>
- {/* TODO(Sam): data-collection wording for sandboxed chats goes here (what uploads record about the
- sandbox: Linux as the OS, the container image, per-turn changes outside the project). No copy yet. */}
- {box ? (
- <div className="mt-0.5 text-[11px] text-dls-secondary" role="status" data-testid="linux-sandbox-state">{linuxSandboxStatusLine(box)}</div>
- ) : null}
- {box ? (
- <div className="mt-0.5 text-[11px] text-dls-secondary" data-testid="linux-sandbox-backend">
- {linuxSandboxBackendLine(box)}
- {box.backend?.why ? <span className="block">{box.backend.why}</span> : null}
- {others ? <span className="block">{others}</span> : null}
- </div>
- ) : null}
- {props.status ? (
- <div className="mt-0.5 text-[11px] text-dls-secondary" data-testid="linux-sandbox-status">{props.status}</div>
- ) : null}
- </div>
- {box && props.onBackend ? (
- <div className="w-44 shrink-0">
- <Select
- value={box.backendSetting.value}
- items={backendItems}
- onValueChange={(value) => {
- if (typeof value === "string") props.onBackend?.(value);
- }}
- disabled={props.busy || box.backendSetting.source === "env"}
- >
- <SelectTrigger className="w-full" aria-label="Sandbox backend">
- <SelectValue placeholder="Automatic" />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- {backendItems.map((item) => (
- <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>
- ))}
- </SelectGroup>
- </SelectContent>
- </Select>
- </div>
- ) : null}
- {box?.on && box.container?.exists ? (
- <Button variant="outline" size="xs" disabled={props.busy} onClick={props.onReset}>Reset sandbox</Button>
- ) : null}
- <Switch
- aria-label="Run commands in a Linux sandbox"
- aria-describedby="linux-sandbox-help"
- checked={box?.on === true}
- disabled={props.busy || !box || box.source === "env"}
- onCheckedChange={props.onToggle}
- />
- </div>
- </div>
- );
-}
-
export function GeneralSettingsView(props: GeneralSettingsViewProps) {
const [account, setAccount] = useState<NativeAccountStatus | null>(null);
const [accountBusy, setAccountBusy] = useState(false);
@@ -466,9 +385,11 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
{linuxSandboxClient && props.sandboxWorkspaceId ? (
<LinuxSandboxCard
box={linuxSandbox.box}
- busy={linuxSandbox.busy}
- status={linuxSandbox.status}
+ pending={linuxSandbox.pending}
+ problem={linuxSandbox.problem}
+ notice={linuxSandbox.notice}
onToggle={(enabled) => void linuxSandbox.setEnabled(enabled)}
+ onRetry={() => void linuxSandbox.retry()}
onReset={() => void linuxSandbox.reset()}
onBackend={(backend) => void linuxSandbox.setBackend(backend)}
/>
diff --git a/apps/app/tests/linux-sandbox-card.test.tsx b/apps/app/tests/linux-sandbox-card.test.tsx
index 3879c6aa..b00ca03b 100644
--- a/apps/app/tests/linux-sandbox-card.test.tsx
+++ b/apps/app/tests/linux-sandbox-card.test.tsx
@@ -2,8 +2,17 @@ import { describe, expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import type { OmniRushWorkspaceBox } from "../src/app/lib/omnirush-server";
-import { LinuxSandboxCard } from "../src/react-app/domains/settings/pages/general-view";
-import { LINUX_SANDBOX_HELP, linuxSandboxBackendLine, linuxSandboxOthersLine, linuxSandboxStatusLine } from "../src/react-app/domains/settings/linux-sandbox";
+import { LinuxSandboxCard, type LinuxSandboxCardProps } from "../src/react-app/domains/settings/linux-sandbox-card";
+import {
+ LINUX_SANDBOX_HELP,
+ linuxSandboxBackendChoices,
+ linuxSandboxBackendSummary,
+ linuxSandboxMoving,
+ linuxSandboxNextStep,
+ linuxSandboxProgress,
+ linuxSandboxView,
+} from "../src/react-app/domains/settings/linux-sandbox";
+import { composerConfigureDestination } from "../src/react-app/domains/settings/library";
function box(overrides: Partial<OmniRushWorkspaceBox> = {}): OmniRushWorkspaceBox {
return {
@@ -25,13 +34,29 @@ function box(overrides: Partial<OmniRushWorkspaceBox> = {}): OmniRushWorkspaceBo
},
backendSetting: { value: "auto", source: "auto", choices: [{ id: "auto", label: "Automatic" }, { id: "apple", label: "Apple container" }, { id: "docker-desktop", label: "Docker Desktop" }, { id: "native", label: "Off (this computer)" }] },
image: { ref: "ghcr.io/omnirush-ai/box-base:2026.10.1", stack: "base", present: true, downloading: false },
+ progress: null,
container: null,
+ platform: "darwin",
notice: null,
error: null,
...overrides,
};
}
+const on = { mode: "on", on: true, source: "project" } as const;
+const noRuntime = (reason: string, platform: string, alternatives: Array<{ id: string; label: string; ok: boolean; reason: string | null }> = []): Partial<OmniRushWorkspaceBox> => ({
+ ...on,
+ platform,
+ state: "unavailable",
+ runtime: { ok: false, name: null, flavor: null, version: null, reason },
+ backend: { id: null, label: null, version: null, flavor: null, why: reason, alternatives, allowed: null },
+ container: null,
+});
+
+function card(props: Partial<LinuxSandboxCardProps> = {}): string {
+ return renderToStaticMarkup(<LinuxSandboxCard box={box()} pending={null} problem={null} notice="" onToggle={() => {}} onRetry={() => {}} onReset={() => {}} onBackend={() => {}} {...props} />);
+}
+
function switchMarkup(markup: string): string {
const match = markup.match(/<[a-z]+[^>]*role="switch"[^>]*>/);
if (!match) throw new Error(`no switch in ${markup}`);
@@ -39,41 +64,139 @@ function switchMarkup(markup: string): string {
}
describe("Linux sandbox card", () => {
- test("off: the switch, its help, and the offer line when the server suggests it", () => {
- const markup = renderToStaticMarkup(<LinuxSandboxCard box={box({ serverDefault: "offer", source: "server", offer: true })} busy={false} status="" onToggle={() => {}} onReset={() => {}} />);
- expect(markup).toContain("Run commands in a Linux sandbox (beta)");
+ test("off: the switch, its help, one calm status row, Advanced closed", () => {
+ const markup = card();
+ expect(markup).toContain("Run commands in a Linux sandbox");
+ expect(markup).toContain("Beta");
expect(markup).toContain(LINUX_SANDBOX_HELP);
- expect(markup).toContain("suggests turning this on");
expect(switchMarkup(markup)).toContain('aria-checked="false"');
- expect(markup).not.toContain("Reset sandbox");
+ expect(markup).toContain('data-tone="off"');
+ expect(markup).toContain("Commands run on this computer.");
+ expect(markup).toContain("Advanced");
+ // Backend and Reset stay inside Advanced (closed).
+ expect(markup).not.toContain("Sandbox backend");
+ expect(markup).not.toContain("Reset…");
+ });
+
+ test("offer: a small prompt with Turn on and Not now, only while off", () => {
+ const offer = card({ box: box({ serverDefault: "offer", source: "server", offer: true }) });
+ expect(offer).toContain('data-testid="linux-sandbox-offer"');
+ expect(offer).toContain("recommends the sandbox");
+ expect(offer).toContain("Turn on");
+ expect(offer).toContain("Not now");
+ expect(card({ box: box({ offer: true }), pending: "on" })).not.toContain("linux-sandbox-offer");
});
- test("on: what the sandbox is doing, and Reset once a container exists", () => {
- const ready = renderToStaticMarkup(<LinuxSandboxCard box={box({ mode: "on", on: true, source: "project", state: "ready", container: { name: "omnirush-box-abc", exists: true, running: true } })} busy={false} status="" onToggle={() => {}} onReset={() => {}} />);
- expect(switchMarkup(ready)).toContain('aria-checked="true"');
- expect(ready).toContain("Ready (docker, desktop), container running.");
- expect(ready).toContain("Reset sandbox");
+ test("the switch shows the choice at once while the server answers, and is locked meanwhile", () => {
+ const turningOn = card({ pending: "on" });
+ expect(switchMarkup(turningOn)).toContain('aria-checked="true"');
+ expect(switchMarkup(turningOn)).toContain('aria-disabled="true"');
+ expect(turningOn).toContain("Turning on…");
+ const turningOff = card({ box: box({ ...on, state: "ready" }), pending: "off" });
+ expect(switchMarkup(turningOff)).toContain('aria-checked="false"');
+ expect(turningOff).toContain("Turning off…");
// Nothing is claimed before the server answers.
- const loading = renderToStaticMarkup(<LinuxSandboxCard box={null} busy={false} status="" onToggle={() => {}} onReset={() => {}} />);
+ const loading = card({ box: null });
expect(switchMarkup(loading)).toContain('aria-disabled="true"');
+ expect(loading).toContain("Checking the sandbox…");
});
- test("status lines: unavailable, downloading, failed, forced by the environment", () => {
- expect(linuxSandboxStatusLine(box({ on: true, state: "unavailable", runtime: { ok: false, name: null, flavor: null, version: null, reason: "Docker is installed but not running" } }))).toBe("Not available: Docker is installed but not running. Commands run on this computer.");
- expect(linuxSandboxStatusLine(box({ on: true, state: "downloading" }))).toContain("Downloading the sandbox image (once)");
- expect(linuxSandboxStatusLine(box({ on: true, state: "failed", error: "could not start the sandbox: x" }))).toBe("The sandbox could not start: could not start the sandbox: x. Commands run on this computer.");
- expect(linuxSandboxStatusLine(box({ source: "env" }))).toContain("OMNIRUSH_BOX");
+ test("downloading: a real bar with MB and percent, or layers, or an indeterminate bar", () => {
+ const markup = card({ box: box({ ...on, state: "downloading", image: { ref: "r", stack: "base", present: false, downloading: true }, progress: { bytesDone: 141_000_000, bytesTotal: 346_000_000, layersDone: 3, layersTotal: 7, startedAt: 1 } }) });
+ expect(markup).toContain("Downloading the sandbox (once)");
+ expect(markup).toContain('role="progressbar"');
+ expect(markup).toContain('aria-valuenow="41"');
+ expect(markup).toContain("141 of 346 MB · 41%");
+ expect(linuxSandboxProgress({ bytesDone: null, bytesTotal: null, layersDone: 2, layersTotal: 8, startedAt: null })).toEqual({ value: 25, label: "2 of 8 parts · 25%" });
+ expect(linuxSandboxProgress(null)).toEqual({ value: null, label: "Starting the download…" });
+ expect(linuxSandboxProgress({ bytesDone: 5_400_000, bytesTotal: 71_000_000, layersDone: 0, layersTotal: 1, startedAt: null }).label).toBe("5.4 of 71 MB · 8%");
});
- test("backend: the chosen one with its version and why, the others with why not, and the override", () => {
- const value = box({ mode: "on", on: true, source: "project", state: "ready" });
- expect(linuxSandboxBackendLine(value)).toBe("Backend: Docker Desktop 27.1");
- expect(linuxSandboxOthersLine(value)).toBe("Others: Apple container (Apple container needs macOS 26 or later (this is macOS 25)); colima (available)");
- const markup = renderToStaticMarkup(<LinuxSandboxCard box={value} busy={false} status="" onToggle={() => {}} onReset={() => {}} onBackend={() => {}} />);
- expect(markup).toContain("Backend: Docker Desktop 27.1");
- expect(markup).toContain("in order: apple &gt; orbstack");
+ test("starting and ready: the backend in plain words; ready is calm (no buttons in the row)", () => {
+ expect(linuxSandboxView(box({ ...on, state: "starting" }))).toMatchObject({ tone: "busy", title: "Starting the sandbox…", detail: "Using Docker Desktop 27.1. This takes a few seconds.", action: null });
+ const ready = linuxSandboxView(box({ ...on, state: "ready", container: { name: "omnirush-box-abc", exists: true, running: true } }));
+ expect(ready).toMatchObject({ tone: "ready", title: "Ready", detail: "Commands run in a Linux container (Docker Desktop 27.1).", action: null, step: null, errorDetail: null });
+ const markup = card({ box: box({ ...on, state: "ready", container: { name: "omnirush-box-abc", exists: true, running: true } }) });
+ expect(switchMarkup(markup)).toContain('aria-checked="true"');
+ expect(markup).not.toContain("Try again");
+ });
+
+ test("failed: plain words, Try again, the raw error behind Show details", () => {
+ const raw = "could not start the sandbox: boxd did not answer on 127.0.0.1:41871 within 20s";
+ const view = linuxSandboxView(box({ ...on, state: "failed", error: raw }));
+ expect(view).toMatchObject({ tone: "error", title: "The sandbox could not start", detail: "Commands run on this computer for now.", action: { kind: "retry", label: "Try again" }, errorDetail: raw });
+ const markup = card({ box: box({ ...on, state: "failed", error: raw }) });
+ expect(markup).toContain("Try again");
+ expect(markup).toContain("Show details");
+ // The raw error is not in the row itself.
+ expect(markup).not.toContain("127.0.0.1:41871");
+ });
+
+ test("no backend: one next step per OS with a command to copy and Check again", () => {
+ const win = linuxSandboxNextStep(box(noRuntime("no sandbox backend found (turn on WSL 2: `wsl --install --no-distribution` as administrator, then `wsl --update` for WSL containers; or Docker Desktop, Podman)", "win32")));
+ expect(win).toMatchObject({ title: "Turn on WSL 2", command: "wsl --install --no-distribution" });
+ const mac = linuxSandboxNextStep(box(noRuntime("no container runtime found (free: `brew install colima docker && colima start`; also OrbStack, Docker Desktop, Podman; Apple container only when chosen in Settings)", "darwin")));
+ expect(mac).toMatchObject({ title: "Install a container app", command: "brew install colima docker && colima start" });
+ const ubuntu = linuxSandboxNextStep(box(noRuntime("bwrap: blocked", "linux", [{ id: "bwrap", label: "bubblewrap (no daemon)", ok: false, reason: "unprivileged user namespaces are blocked by AppArmor; one-time admin fix: `sudo omnirush sandbox enable` (OmniRush CLI)" }, { id: "docker", label: "Docker", ok: false, reason: "not found" }])));
+ expect(ubuntu).toMatchObject({ title: "Allow the sandbox on this computer", command: "sudo omnirush sandbox enable" });
+ expect(linuxSandboxNextStep(box(noRuntime("docker: x", "linux", [{ id: "docker", label: "Docker", ok: false, reason: "Docker refused this user (add it to the docker group: `sudo usermod -aG docker $USER`, then log in again), or use rootless Podman" }])))).toMatchObject({ title: "Let this user run Docker", command: "sudo usermod -aG docker $USER" });
+ expect(linuxSandboxNextStep(box(noRuntime("podman: not found", "linux")))).toMatchObject({ title: "Install Podman or Docker", command: "sudo apt install podman" });
+ expect(linuxSandboxNextStep(box(noRuntime("x", "win32", [{ id: "docker-desktop", label: "Docker Desktop", ok: false, reason: "Docker is installed but not running (start Docker Desktop, OrbStack or colima)" }])))).toMatchObject({ title: "Start your container app", command: null });
+
+ const markup = card({ box: box(noRuntime("no sandbox backend found (turn on WSL 2: `wsl --install --no-distribution` as administrator)", "win32")) });
+ expect(markup).toContain('data-tone="attention"');
+ expect(markup).toContain("Turn on WSL 2");
+ expect(markup).toContain("wsl --install --no-distribution");
+ expect(markup).toContain('aria-label="Copy command"');
+ expect(markup).toContain("Check again");
+ });
+
+ test("the backend set to Off is one button away from automatic; a project gone native can try again", () => {
+ expect(linuxSandboxView(box({ ...on, state: "unavailable", runtime: { ok: false, name: null, flavor: null, version: null, reason: "set to native" }, backendSetting: { value: "native", source: "setting", choices: [] } }))).toMatchObject({ title: "The backend is set to Off", action: { kind: "auto-backend", label: "Use automatic" } });
+ expect(linuxSandboxView(box({ ...on, state: "unavailable", notice: "Sandbox off for now: the sandbox did not start in time." }))).toMatchObject({ title: "The sandbox is not running", action: { kind: "retry" }, errorDetail: "the sandbox did not start in time" });
+ });
+
+ test("forced by the environment: the switch is locked and says where", () => {
+ const markup = card({ box: box({ source: "env" }) });
+ expect(switchMarkup(markup)).toContain('aria-disabled="true"');
+ expect(markup).toContain("Set by OMNIRUSH_BOX where the app is launched.");
+ });
+
+ test("Advanced: automatic (recommended) first, the backend in use, the others with why not, Reset behind a confirm", () => {
+ const value = box({ ...on, state: "ready", container: { name: "omnirush-box-abc", exists: true, running: true } });
+ expect(linuxSandboxBackendChoices(value)[0]).toEqual({ value: "auto", label: "Automatic (recommended)" });
+ expect(linuxSandboxBackendSummary(value)).toBe("Using Docker Desktop 27.1, picked automatically.");
+ expect(linuxSandboxBackendSummary(box({ backendSetting: { value: "native", source: "setting", choices: [] } }))).toBe("Set to Off: commands run on this computer.");
+ expect(linuxSandboxBackendSummary(box({ runtime: null, backend: null }))).toBe("No backend works on this computer yet.");
+ const markup = card({ box: value, defaultAdvancedOpen: true });
expect(markup).toContain('aria-label="Sandbox backend"');
- expect(linuxSandboxBackendLine(box({ backend: { id: null, label: null, version: null, flavor: null, why: "no sandbox backend works here", alternatives: [], allowed: null } }))).toBe("Backend: none available");
- expect(linuxSandboxBackendLine(box({ backendSetting: { value: "native", source: "setting", choices: [] } }))).toBe("Backend: off (commands run on this computer)");
+ expect(markup).toContain("Apple container needs macOS 26 or later");
+ expect(markup).toContain("colima");
+ expect(markup).toContain("Reset…");
+ // The confirm dialog is not open until Reset… is pressed.
+ expect(markup).not.toContain("Reset the sandbox?");
+ // No container yet: nothing to reset.
+ expect(card({ box: box({ ...on, state: "starting" }), defaultAdvancedOpen: true })).toContain("Nothing to reset");
+ });
+
+ test("errors from the server are plain words with a retry; polling only while it moves", () => {
+ const markup = card({ problem: { message: "The sandbox could not be turned on.", retry: () => {} } });
+ expect(markup).toContain('role="alert"');
+ expect(markup).toContain("The sandbox could not be turned on.");
+ expect(markup).toContain("Try again");
+ expect(linuxSandboxMoving(box({ ...on, state: "downloading" }))).toBe(true);
+ expect(linuxSandboxMoving(box({ ...on, state: "starting" }))).toBe(true);
+ expect(linuxSandboxMoving(box({ ...on, state: "ready" }))).toBe(false);
+ expect(linuxSandboxMoving(box({ state: "starting" }))).toBe(false);
+ });
+
+ test("reduced motion: spinners and the bar animate only with motion allowed", () => {
+ const markup = card({ pending: "on" });
+ expect(markup).toContain("motion-safe:animate-spin");
+ expect(markup).not.toMatch(/class="[^"]*(?<!motion-safe:)animate-spin/);
+ });
+
+ test("the composer's sandbox chip opens Settings > General at the card", () => {
+ expect(composerConfigureDestination("sandbox")).toEqual({ kind: "settings", route: "/settings/general#linux-sandbox" });
});
});
diff --git a/apps/desktop/box/go/cmd/boxrun/main.go b/apps/desktop/box/go/cmd/boxrun/main.go
index d6eea7d5..7d69a6ca 100644
--- a/apps/desktop/box/go/cmd/boxrun/main.go
+++ b/apps/desktop/box/go/cmd/boxrun/main.go
@@ -149,6 +149,15 @@ func cmdPull(args []string) error {
defer cancel()
start := time.Now()
s := oci.Store{Dir: *store}
+ // A progress line on stderr at most every 200 ms (and at the end of each
+ // layer): {"progress":{"bytes":N,"total":M}}, read by the CLI's progress line.
+ var last time.Time
+ s.Bytes = func(done, total int64) {
+ if now := time.Now(); now.Sub(last) >= 200*time.Millisecond || done == total {
+ last = now
+ fmt.Fprintf(os.Stderr, "{\"progress\":{\"bytes\":%d,\"total\":%d}}\n", done, total)
+ }
+ }
img, id, err := s.Pull(ctx, oci.NewClient(), ref, *arch, oci.ApplyOptions{Chown: os.Geteuid() == 0}, func(i, n int, digest string, size int64) {
fmt.Fprintf(os.Stderr, "layer %d/%d %s %d bytes\n", i, n, digest, size)
})
diff --git a/apps/desktop/box/go/cmd/boxsh/main.go b/apps/desktop/box/go/cmd/boxsh/main.go
index d25fc8f6..5f2b46cc 100644
--- a/apps/desktop/box/go/cmd/boxsh/main.go
+++ b/apps/desktop/box/go/cmd/boxsh/main.go
@@ -174,9 +174,17 @@ func waitReady(key string) (*Record, error) {
limit = time.Duration(v) * time.Millisecond
}
start := time.Now()
- said := false
+ said := ""
+ // While the image downloads (a first --sandbox run) the wait has no short
+ // limit: the download has its own (an hour), and the command runs once it is in.
+ pulled := time.Duration(0)
+ last := time.Now()
for {
rec, err := readRecord(key)
+ if err == nil && rec.State == "pulling" {
+ pulled += time.Since(last)
+ }
+ last = time.Now()
if err == nil {
switch rec.State {
case "ready":
@@ -191,15 +199,21 @@ func waitReady(key string) (*Record, error) {
return nil, fmt.Errorf("the sandbox is not available (%s); run `omnirush sandbox status`", msg)
}
}
- if time.Since(start) > limit {
+ if time.Since(start)-pulled > limit || pulled > 61*time.Minute {
if err != nil {
return nil, fmt.Errorf("no sandbox record for this project (%v)", err)
}
return nil, errors.New("the sandbox did not start in time; run `omnirush sandbox status`")
}
- if !said && time.Since(start) > 1500*time.Millisecond {
- fmt.Fprintln(os.Stderr, "omnirush: waiting for the sandbox to start...")
- said = true
+ if time.Since(start) > 1500*time.Millisecond {
+ msg := "omnirush: waiting for the sandbox to start..."
+ if err == nil && rec.State == "pulling" {
+ msg = "omnirush: waiting for the sandbox image to download (once)..."
+ }
+ if msg != said {
+ fmt.Fprintln(os.Stderr, msg)
+ said = msg
+ }
}
time.Sleep(100 * time.Millisecond)
}
diff --git a/apps/desktop/box/go/cmd/boxsh/main_test.go b/apps/desktop/box/go/cmd/boxsh/main_test.go
index 6ca6ec37..c3e4d8d2 100644
--- a/apps/desktop/box/go/cmd/boxsh/main_test.go
+++ b/apps/desktop/box/go/cmd/boxsh/main_test.go
@@ -1,9 +1,13 @@
package main
import (
+ "os"
+ "path/filepath"
"reflect"
"runtime"
+ "strings"
"testing"
+ "time"
)
func TestParseShellArgs(t *testing.T) {
@@ -72,3 +76,32 @@ func TestWindowsToBox(t *testing.T) {
t.Fatal(got)
}
}
+
+// A box whose image is downloading is waited for past the start limit; the limit counts once it starts.
+func TestWaitReadyThroughDownload(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("OMNIRUSH_BOX_HOME", home)
+ t.Setenv("OMNIRUSH_BOX_WAIT_MS", "300")
+ if err := os.MkdirAll(filepath.Join(home, "boxes"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ write := func(state string) {
+ data := `{"v":1,"key":"abc123","root":"/p","croot":"/p","state":"` + state + `","port":1,"token":"t"}`
+ if err := os.WriteFile(filepath.Join(home, "boxes", "abc123.json"), []byte(data), 0o600); err != nil {
+ t.Error(err)
+ }
+ }
+ write("pulling")
+ go func() {
+ time.Sleep(700 * time.Millisecond)
+ write("ready")
+ }()
+ rec, err := waitReady("abc123")
+ if err != nil || rec == nil || rec.State != "ready" {
+ t.Fatalf("waited through the download: %v %+v", err, rec)
+ }
+ write("starting")
+ if _, err := waitReady("abc123"); err == nil || !strings.Contains(err.Error(), "did not start in time") {
+ t.Fatalf("a start that hangs still times out: %v", err)
+ }
+}
diff --git a/apps/desktop/box/go/oci/oci_test.go b/apps/desktop/box/go/oci/oci_test.go
index 56b3d685..e1b7de90 100644
--- a/apps/desktop/box/go/oci/oci_test.go
+++ b/apps/desktop/box/go/oci/oci_test.go
@@ -259,12 +259,23 @@ func TestPullIndexWithToken(t *testing.T) {
t.Fatal(err)
}
ref.Registry = strings.TrimPrefix(srv.URL, "http://")
- store := Store{Dir: t.TempDir()}
+ var seen, lastDone, lastTotal int64
+ store := Store{Dir: t.TempDir(), Bytes: func(done, total int64) {
+ if done < lastDone {
+ t.Errorf("progress went back: %d after %d", done, lastDone)
+ }
+ seen++
+ lastDone, lastTotal = done, total
+ }}
c := NewClient()
img, id, err := store.Pull(context.Background(), c, ref, "x64", ApplyOptions{}, nil)
if err != nil {
t.Fatal(err)
}
+ if want := int64(len(l1) + len(l2)); seen < 2 || lastTotal != want || lastDone != want {
+ t.Fatalf("progress: %d calls, ended at %d/%d, want %d", seen, lastDone, lastTotal, want)
+ }
+ store.Bytes = nil
if img.Digest != idxDigest || img.Arch != "amd64" || len(img.Env) != 2 || img.WorkDir != "/root" {
t.Fatalf("%+v", img)
}
diff --git a/apps/desktop/box/go/oci/store.go b/apps/desktop/box/go/oci/store.go
index 96298da2..51a13106 100644
--- a/apps/desktop/box/go/oci/store.go
+++ b/apps/desktop/box/go/oci/store.go
@@ -24,6 +24,9 @@ import (
// Store keeps unpacked images: <dir>/images/<id>/{rootfs/,image.json}.
type Store struct {
Dir string
+ // Bytes, when set, hears the download as it goes: compressed bytes read
+ // so far over the image's total (the layers' sizes), for a progress line.
+ Bytes func(done, total int64)
}
// ImageID names an unpacked image: the digest it was pinned by, per arch.
@@ -162,13 +165,28 @@ func (s Store) Pull(ctx context.Context, c *Client, ref Ref, arch string, opt Ap
if err := os.MkdirAll(u.Root, 0o755); err != nil {
return nil, "", err
}
+ var total, done int64
+ for _, layer := range img.Layers {
+ total += layer.Size
+ }
+ if s.Bytes != nil {
+ s.Bytes(0, total)
+ }
for i, layer := range img.Layers {
var lastErr error
+ base := done
for attempt := 0; attempt < 3; attempt++ {
if attempt > 0 {
time.Sleep(time.Duration(attempt*2) * time.Second)
}
- lastErr = s.applyBlob(ctx, c, ref, u, layer.Digest)
+ // A retry re-reads the whole layer: its bytes count again from its start.
+ done = base
+ lastErr = s.applyBlob(ctx, c, ref, u, layer.Digest, func(n int64) {
+ done += n
+ if s.Bytes != nil {
+ s.Bytes(done, total)
+ }
+ })
if lastErr == nil || ctx.Err() != nil {
break
}
@@ -192,22 +210,40 @@ func (s Store) Pull(ctx context.Context, c *Client, ref Ref, arch string, opt Ap
// applyBlob streams one layer into the unpacker. A retry after a failure
// half-way re-applies the whole layer, which is idempotent.
-func (s Store) applyBlob(ctx context.Context, c *Client, ref Ref, u *Unpacker, digest string) error {
+func (s Store) applyBlob(ctx context.Context, c *Client, ref Ref, u *Unpacker, digest string, read func(int64)) error {
rc, err := c.OpenBlob(ctx, ref, digest)
if err != nil {
return err
}
defer rc.Close()
- if _, err := u.Apply(rc); err != nil {
+ var r io.Reader = rc
+ if read != nil {
+ r = countingReader{r: rc, read: read}
+ }
+ if _, err := u.Apply(r); err != nil {
return err
}
// Read to the end so the digest is checked.
- if _, err := io.Copy(io.Discard, rc); err != nil {
+ if _, err := io.Copy(io.Discard, r); err != nil {
return err
}
return rc.Close()
}
+// countingReader reports how many bytes each Read returned.
+type countingReader struct {
+ r io.Reader
+ read func(int64)
+}
+
+func (c countingReader) Read(p []byte) (int, error) {
+ n, err := c.r.Read(p)
+ if n > 0 {
+ c.read(int64(n))
+ }
+ return n, err
+}
+
func (s Store) rememberTag(ref Ref, arch, id string) error {
if ref.Digest != "" || ref.Tag == "" {
return nil
diff --git a/apps/server/src/box/backends/bwrap.ts b/apps/server/src/box/backends/bwrap.ts
index 125cafe8..0a5d9e75 100644
--- a/apps/server/src/box/backends/bwrap.ts
+++ b/apps/server/src/box/backends/bwrap.ts
@@ -22,7 +22,7 @@ import os from "node:os";
import path from "node:path";
import { GOARCH, RUN_DIR, SHIMS_DIR, containerName, containerRoot, helperPath, newToken, readJson, writeJson, type BoxInstallLog, type BoxRuntime } from "../common.js";
-import { runCommand, type RunCommand } from "../run.js";
+import { runCommand, type RunCommand, type RunOptions } from "../run.js";
import type { RuntimeResult } from "../runtime.js";
import { boxshExec, num, parseOut, str } from "./shared.js";
import type { BoxDriver, ListedBox, OpenContext, Opened, PresentImage, Removed } from "./types.js";
@@ -121,8 +121,9 @@ async function imagePresent(runtime: BoxRuntime, image: { pull: string }, { run
return presentOf(parseOut(res.stdout));
}
-async function pull(runtime: BoxRuntime, image: { pull: string }, { run = runCommand, home = "" }: { run?: RunCommand; home?: string } = {}): Promise<{ ok: true } | { ok: false; error: string }> {
- const res = await run(runtime.bin, ["pull", ...storeArgs(home), "--ref", image.pull, "--arch", runtime.arch || GOARCH[process.arch] || "amd64"], { timeoutMs: 60 * 60_000 });
+/** `onLine`: boxrun's output lines as they come (its progress, for a progress line). */
+async function pull(runtime: BoxRuntime, image: { pull: string }, { run = runCommand, home = "", onLine }: { run?: RunCommand; home?: string; onLine?: RunOptions["onLine"] } = {}): Promise<{ ok: true } | { ok: false; error: string }> {
+ const res = await run(runtime.bin, ["pull", ...storeArgs(home), "--ref", image.pull, "--arch", runtime.arch || GOARCH[process.arch] || "amd64"], { timeoutMs: 60 * 60_000, ...(onLine ? { onLine } : {}) });
const out = parseOut(res.stdout);
return out?.ok ? { ok: true } : { ok: false, error: String(out?.error || res.stderr || `boxrun pull exited ${res.code}`).slice(0, 300) };
}
@@ -153,7 +154,7 @@ export function newMeta({ key, root, croot, present, image }: { key: string; roo
}
async function open(ctx: OpenContext): Promise<Opened> {
- const { key, root, croot, runtime, run, home, runFolder, image, pull: mayPull, shims, pkglog, env, log, onPulling } = ctx;
+ const { key, root, croot, runtime, run, home, runFolder, image, pull: mayPull, shims, pkglog, env, log, onPulling, onLine } = ctx;
const file = metaFile(home, key);
let meta = readJson<BoxMeta>(file);
if (meta && meta.root !== root) return { ok: false, error: `box ${key} belongs to another folder` };
@@ -163,7 +164,7 @@ async function open(ctx: OpenContext): Promise<Opened> {
if (!present) {
if (!mayPull) return { ok: false, error: "the sandbox image is not downloaded yet" };
onPulling();
- const pulled = await pull(runtime, image, { run, home });
+ const pulled = await pull(runtime, image, { run, home, onLine });
if (!pulled.ok) return { ok: false, error: `could not download the sandbox image: ${pulled.error}` };
present = await imagePresent(runtime, image, { run, home });
if (!present) return { ok: false, error: "the sandbox image is not there after the download" };
diff --git a/apps/server/src/box/backends/container.ts b/apps/server/src/box/backends/container.ts
index 9576a94e..188b739b 100644
--- a/apps/server/src/box/backends/container.ts
+++ b/apps/server/src/box/backends/container.ts
@@ -75,10 +75,10 @@ export async function inspectImage(runtime: BoxRuntime, image: string, { run = r
}
/** `pull` with retries (a flaky link picks up where it stopped). */
-export async function pullImage(runtime: BoxRuntime, image: string, { run = runCommand, pauses = [2_000, 8_000], timeoutMs = 60 * 60_000, sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) }: { run?: RunCommand; pauses?: number[]; timeoutMs?: number; sleep?: (ms: number) => Promise<unknown> } = {}): Promise<{ ok: true; attempts: number } | { ok: false; error: string }> {
+export async function pullImage(runtime: BoxRuntime, image: string, { run = runCommand, pauses = [2_000, 8_000], timeoutMs = 60 * 60_000, sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)), onLine }: { run?: RunCommand; pauses?: number[]; timeoutMs?: number; sleep?: (ms: number) => Promise<unknown>; onLine?: RunOptions["onLine"] } = {}): Promise<{ ok: true; attempts: number } | { ok: false; error: string }> {
let last = null;
for (let attempt = 0; attempt <= pauses.length; attempt += 1) {
- last = await rt(runtime, run)(["pull", image], { timeoutMs });
+ last = await rt(runtime, run)(["pull", image], { timeoutMs, ...(onLine ? { onLine } : {}) });
if (last.code === 0) return { ok: true, attempts: attempt + 1 };
if (attempt < pauses.length) await sleep(pauses[attempt]!);
}
@@ -181,7 +181,7 @@ export function parseSize(text: unknown): number | null {
/** Create (or start) the project's container; boxd answers on a published loopback port. */
async function open(ctx: OpenContext): Promise<Opened> {
- const { key, name, root, croot, runtime, run, runFolder, image, pull, shims, pkglog, env, platform, log, onPulling } = ctx;
+ const { key, name, root, croot, runtime, run, runFolder, image, pull, shims, pkglog, env, platform, log, onPulling, onLine } = ctx;
let info = await inspectContainer(runtime, name, run);
if (info && info.labels?.[`${LABEL}.root`] && info.labels[`${LABEL}.root`] !== root) {
return { ok: false, error: `container ${name} belongs to another folder` };
@@ -192,7 +192,7 @@ async function open(ctx: OpenContext): Promise<Opened> {
if (!present) {
if (!pull) return { ok: false, error: "the sandbox image is not downloaded yet" };
onPulling();
- const pulled = await pullImage(runtime, image.pull, { run });
+ const pulled = await pullImage(runtime, image.pull, { run, onLine });
if (!pulled.ok) return { ok: false, error: `could not download the sandbox image: ${pulled.error}` };
present = await inspectImage(runtime, image.pull, { run });
if (!present) return { ok: false, error: "the sandbox image is not there after the download" };
@@ -250,10 +250,10 @@ export const containerDriver: BoxDriver = {
execFallback: true,
async imagePresent(runtime, image, { run = runCommand } = {}) {
const found = await inspectImage(runtime, image.pull, { run });
- return found ? { id: found.id, digest: found.digest, arch: found.arch } : null;
+ return found ? { id: found.id, digest: found.digest, arch: found.arch, size: found.size || null } : null;
},
- pull(runtime, image, { run = runCommand } = {}) {
- return pullImage(runtime, image.pull, { run });
+ pull(runtime, image, { run = runCommand, onLine } = {}) {
+ return pullImage(runtime, image.pull, { run, onLine });
},
/** The detached download (the app keeps no handle on it). */
pullCommand(runtime, image) {
diff --git a/apps/server/src/box/backends/types.ts b/apps/server/src/box/backends/types.ts
index 45c17c25..4471394e 100644
--- a/apps/server/src/box/backends/types.ts
+++ b/apps/server/src/box/backends/types.ts
@@ -6,7 +6,7 @@ import type { ChildProcess, SpawnOptions } from "node:child_process";
import type { BoxEndpoint } from "../client.js";
import type { BoxInstallLog, BoxLog, BoxRuntime } from "../common.js";
import type { BoxImage } from "../images.js";
-import type { RunCommand, RunResult } from "../run.js";
+import type { RunCommand, RunOptions, RunResult } from "../run.js";
type Env = NodeJS.ProcessEnv;
@@ -34,6 +34,8 @@ export type OpenContext = {
platform: NodeJS.Platform;
log: BoxLog;
onPulling: () => void;
+ /** The download's output lines as they come (its progress). */
+ onLine?: RunOptions["onLine"];
spawnImpl?: SpawnLike;
};
@@ -53,10 +55,10 @@ export type Opened =
}
| { ok: false; error: string };
-export type PresentImage = { id: string; digest: string | null; arch: string; config?: string };
+export type PresentImage = { id: string; digest: string | null; arch: string; config?: string; size?: number | null };
export type ListedBox = { key: string; name: string; root: string; running: boolean; image: string; created: string };
export type Removed = { kind: string; name: string; reason: string };
-export type DriverOptions = { run?: RunCommand; env?: Env; home?: string; timeoutMs?: number; log?: BoxLog };
+export type DriverOptions = { run?: RunCommand; env?: Env; home?: string; timeoutMs?: number; log?: BoxLog; onLine?: RunOptions["onLine"] };
export type BoxDriver = {
kind: "container" | "bwrap" | "apple" | "wsl" | "wslc";
diff --git a/apps/server/src/box/box-server.test.ts b/apps/server/src/box/box-server.test.ts
index bf59dd97..b47b1539 100644
--- a/apps/server/src/box/box-server.test.ts
+++ b/apps/server/src/box/box-server.test.ts
@@ -93,6 +93,12 @@ describe("Linux sandbox through the server", () => {
const status = await on.json();
expect(status).toMatchObject({ mode: "on", on: true, source: "project", state: "unavailable", engine: { status: "unmanaged" } });
expect(status.runtime.ok).toBe(false);
+ expect(status).toMatchObject({ platform: process.platform, progress: null });
+ // Try again (the card's retry and Check again): a fresh look; still no runtime here.
+ const retried = await fetch(`${base}/workspace/${WORKSPACE_ID}/box/retry`, { method: "POST", headers, body: "{}" });
+ expect(retried.status).toBe(200);
+ expect(await retried.json()).toMatchObject({ mode: "on", on: true, state: "unavailable" });
+ expect(policyRequestActions("POST", `/workspace/${WORKSPACE_ID}/box/retry`)).toEqual(["settings"]);
expect(await readOmniRushWorkspaceConfig(config, WORKSPACE_ID)).toMatchObject({ localBox: { mode: "on", offered: true } });
const withBox = await engineConfig();
expect(withBox.shell).toBe(join(root, "box-home", "shell-desktop", "bash"));
diff --git a/apps/server/src/box/box.test.ts b/apps/server/src/box/box.test.ts
index 4be1368b..52593701 100644
--- a/apps/server/src/box/box.test.ts
+++ b/apps/server/src/box/box.test.ts
@@ -1,12 +1,14 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { writeSync } from "node:fs";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { boxKey, containerName, containerRoot, createArgs, credentialPath, filterChanges, helperPath, installShell, parseDiff, parseSize, rt, setToolsRoot, singleFileTar, wslPath } from "./box.js";
+import { Box, boxKey, containerName, containerRoot, createArgs, credentialPath, filterChanges, helperPath, installShell, parseDiff, parseSize, rt, setToolsRoot, singleFileTar, wslPath } from "./box.js";
import { readBoxSettings } from "./desktop.js";
import { detectStack, imageFor } from "./images.js";
-import { engineConfig, gcInBackground, mapToBox, rememberServerDefault, resolveMode, serverDefault } from "./launch.js";
+import { boxRun, engineConfig, gcInBackground, mapToBox, pullInBackground, pullLog, pullMarker, rememberServerDefault, resolveMode, serverDefault } from "./launch.js";
+import { clearLayerSizes, layerSizes, parseManifestSizes, parsePullLog, pullProgress } from "./pull-progress.js";
import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";
import { candidates, detectRuntime, explainFailure, probe, probeWsl, wslLauncher, type RunCommand } from "./runtime.js";
import { BoxService, type BoxWorkspace } from "./service.js";
@@ -262,6 +264,17 @@ describe("box service", () => {
expect(await none.engineBits()).toBeNull();
});
+ test("Try again with no runtime: a fresh look, still unavailable, with the OS for the card's next step", async () => {
+ const stateDir = await temp("state");
+ const root = await temp("project");
+ const workspace: BoxWorkspace = { id: "ws_t", path: root, workspaceType: "local" };
+ const settings: Settings = new Map([["ws_t", { mode: "on", offered: true }]]);
+ const boxes = service({ stateDir, workspaces: [workspace], settings, env: { OMNIRUSH_BOX_HOME: await temp("boxhome"), OMNIRUSH_BOX_BIN_DIR: await helpers(), PATH: "", OMNIRUSH_BOX_RUNTIME: "/nonexistent/docker" } });
+ const status = await boxes.retry(workspace);
+ expect(status).toMatchObject({ on: true, state: "unavailable", platform: process.platform, progress: null });
+ expect(settings.get("ws_t")).toEqual({ mode: "on", offered: true });
+ });
+
test("a remote workspace never gets a box", async () => {
const stateDir = await temp("state");
const workspace: BoxWorkspace = { id: "ws_r", path: "/remote", workspaceType: "remote" };
@@ -358,3 +371,116 @@ describe("box install log and upkeep", () => {
expect(system[0]).toContain(`${root} is /c/proj inside the container`);
});
});
+
+describe("box download progress (the Settings card's bar)", () => {
+ const DOCKER_LOG = [
+ "2026.10.2: Pulling from omnirush-ai/box-go",
+ "aaaaaaaaaaaa: Already exists",
+ "bbbbbbbbbbbb: Pulling fs layer",
+ "cccccccccccc: Pulling fs layer",
+ "bbbbbbbbbbbb: Waiting",
+ "cccccccccccc: Downloading",
+ "cccccccccccc: Verifying Checksum",
+ "cccccccccccc: Download complete",
+ "",
+ ].join("\n");
+
+ test("the runtime's piped output: layers named and downloaded (Docker and Podman)", () => {
+ expect(parsePullLog(DOCKER_LOG)).toEqual({ seen: ["aaaaaaaaaaaa", "bbbbbbbbbbbb", "cccccccccccc"], done: new Set(["aaaaaaaaaaaa", "cccccccccccc"]), bytes: null, layers: 3 });
+ const podman = parsePullLog("Trying to pull ghcr.io/x...\nCopying blob sha256:dddddddddddd1111 done |\nCopying blob eeeeeeeeeeee2222\nCopying blob ffffffffffff skipped: already exists\n");
+ expect(podman).toEqual({ seen: ["dddddddddddd", "eeeeeeeeeeee", "ffffffffffff"], done: new Set(["dddddddddddd", "ffffffffffff"]), bytes: null, layers: 3 });
+ // bubblewrap's boxrun: its byte count (the latest line wins), and whole layers as they land.
+ const boxrun = parsePullLog(`{"progress":{"bytes":0,"total":259000000}}\n{"progress":{"bytes":52000000,"total":259000000}}\nlayer 1/3 sha256:${"a".repeat(64)} 52000000 bytes\n{"progress":{"bytes":131000000,"total":259000000}}\n{"progress":{"by`);
+ expect(boxrun).toMatchObject({ bytes: { done: 131_000_000, total: 259_000_000 }, layers: 3, done: new Set(["aaaaaaaaaaaa"]) });
+ });
+
+ test("layer sizes for this platform from `manifest inspect -v` (a list or one manifest)", () => {
+ const list = JSON.stringify([
+ { Descriptor: { platform: { os: "linux", architecture: "arm64" } }, OCIManifest: { layers: [{ digest: `sha256:${"9".repeat(64)}`, size: 1 }] } },
+ { Descriptor: { platform: { os: "linux", architecture: "amd64" } }, OCIManifest: { layers: [{ digest: `sha256:${"a".repeat(64)}`, size: 1000 }, { digest: `sha256:${"b".repeat(64)}`, size: 5000 }] } },
+ ]);
+ expect(parseManifestSizes(list, "amd64")).toEqual(new Map([["aaaaaaaaaaaa", 1000], ["bbbbbbbbbbbb", 5000]]));
+ expect(parseManifestSizes(JSON.stringify({ SchemaV2Manifest: { layers: [{ digest: `sha256:${"c".repeat(64)}`, size: 7 }] } }), "arm64")).toEqual(new Map([["cccccccccccc", 7]]));
+ expect(parseManifestSizes("not json")).toBeNull();
+ expect(parseManifestSizes(list, "riscv64")).toBeNull();
+ });
+
+ test("progress: bytes of the downloaded layers out of the layers the runtime downloads; layers only without sizes", async () => {
+ const home = await temp("pulls");
+ const marker = join(home, "docker-img.pid");
+ await writeFile(marker, "123");
+ await writeFile(pullLog(marker), DOCKER_LOG);
+ const sizes = new Map([["aaaaaaaaaaaa", 100], ["bbbbbbbbbbbb", 300], ["cccccccccccc", 600], ["dddddddddddd", 9_999]]);
+ // dddd... is in the image but already here and never named: not part of this download.
+ expect(pullProgress(pullLog(marker), marker, sizes)).toMatchObject({ bytesDone: 700, bytesTotal: 1000, layersDone: 2, layersTotal: 3 });
+ expect(pullProgress(pullLog(marker), marker, null)).toMatchObject({ bytesDone: null, bytesTotal: null, layersDone: 2, layersTotal: 3 });
+ // Sizes that do not cover a named layer belong to something else: no bytes.
+ expect(pullProgress(pullLog(marker), marker, new Map([["aaaaaaaaaaaa", 1]]))).toMatchObject({ bytesDone: null, bytesTotal: null });
+ expect(pullProgress(pullLog(marker), marker, sizes)?.startedAt).toBeGreaterThan(0);
+ await writeFile(pullLog(marker), `{"progress":{"bytes":65000000,"total":259000000}}\n`);
+ expect(pullProgress(pullLog(marker), marker, null)).toMatchObject({ bytesDone: 65_000_000, bytesTotal: 259_000_000 });
+ // No log (a download in this process): no progress.
+ expect(pullProgress(join(home, "none.log"), marker, sizes)).toBeNull();
+ });
+
+ test("the sizes are asked once per image, in the background, and only of Docker", async () => {
+ clearLayerSizes();
+ const calls: string[][] = [];
+ const run: RunCommand = async (_bin, args) => {
+ calls.push(args);
+ return { code: 0, stdout: JSON.stringify({ SchemaV2Manifest: { layers: [{ digest: `sha256:${"a".repeat(64)}`, size: 42 }] } }), stderr: "" };
+ };
+ const image = { stack: "base", ref: "r", digest: null, pull: "r:1" };
+ expect(layerSizes({ name: "podman", bin: "podman" }, image, { run })).toBeNull();
+ expect(layerSizes({ name: "docker", bin: "docker" }, image, { run })).toBeNull();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(layerSizes({ name: "docker", bin: "docker" }, image, { run })).toEqual(new Map([["aaaaaaaaaaaa", 42]]));
+ expect(calls).toEqual([["manifest", "inspect", "-v", "r:1"]]);
+ clearLayerSizes();
+ });
+
+ test("the detached download writes its output next to its marker", async () => {
+ const home = await temp("boxhome");
+ const runtime = { name: "docker", bin: "docker", backend: "docker" };
+ const image = { stack: "base", ref: "img", digest: null, pull: "img:1" };
+ let seen: unknown = null;
+ const started = pullInBackground(runtime, image, home, {
+ spawnImpl: (_command, _args, options) => {
+ seen = options.stdio;
+ if (Array.isArray(options.stdio)) writeSync(options.stdio[1], "aaaaaaaaaaaa: Pulling fs layer\n");
+ return { pid: 999_999_999, unref: () => {} };
+ },
+ });
+ expect(started.started).toBe(true);
+ expect(Array.isArray(seen) && seen[0] === "ignore").toBe(true);
+ expect(await readFile(pullLog(pullMarker(home, runtime, image.pull)), "utf8")).toBe("aaaaaaaaaaaa: Pulling fs layer\n");
+ });
+});
+
+describe("box start limit", () => {
+ test("the start limit counts while the box starts, not while its image downloads", async () => {
+ const home = await temp("boxhome");
+ const root = await temp("project");
+ const box = new Box({ key: "k", name: "n", root, croot: root, runtime: { name: "docker", bin: "docker" }, home, runFolder: join(home, "run"), run: async () => ({ code: 0, stdout: "", stderr: "" }), log: () => {}, platform: "linux", env: {} });
+ let phase: string | null = "pulling";
+ let open: (value: Box) => void = () => {};
+ const opening = new Promise<Box>((resolve) => { open = resolve; });
+ const run = boxRun({ box: { key: "k", home, root, runtime: { name: "docker", bin: "docker" } }, notice: null, shell: "bash", start: () => opening, get phase() { return phase; } }, { readyWaitMs: 60 });
+ const waiting = run.ready();
+ // 200 ms of download: longer than the 60 ms limit, which does not run meanwhile.
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ phase = "starting";
+ box.setState("ready", null);
+ open(box);
+ expect(await waiting).toBe(box);
+ expect(run.native).toBe(false);
+ });
+
+ test("a start that takes longer than the limit (no download) goes on without the box", async () => {
+ const home = await temp("boxhome");
+ const root = await temp("project");
+ const run = boxRun({ box: { key: "k2", home, root, runtime: { name: "docker", bin: "docker" } }, notice: null, shell: "bash", start: () => new Promise<Box>(() => {}), get phase() { return "starting"; } }, { readyWaitMs: 40 });
+ expect(await run.ready()).toBeNull();
+ expect(run.native).toBe(true);
+ });
+});
diff --git a/apps/server/src/box/box.ts b/apps/server/src/box/box.ts
index 1bc080e9..4ce32b4c 100644
--- a/apps/server/src/box/box.ts
+++ b/apps/server/src/box/box.ts
@@ -35,7 +35,7 @@ import { DEPS_MAX_BYTES, FILE_MAX_BYTES, HOME_IN_BOX, RECORD_SCHEMA, RUN_DIR, SH
import { driverFor } from "./backends/index.js";
import type { ListedBox, SpawnLike } from "./backends/types.js";
import { detectStack, imageFor, type BoxImage, type ImagePins } from "./images.js";
-import { runCommand, type RunCommand } from "./run.js";
+import { runCommand, type RunCommand, type RunOptions } from "./run.js";
type Env = NodeJS.ProcessEnv;
@@ -197,7 +197,7 @@ type OnState = (state: BoxState, error: string | null) => void;
* (the record boxsh reads says the same). Throws only for programming
* errors; a box that cannot start is a Box with state "failed" and `error`.
*/
-export async function openBox({ root, runtime, env = process.env, platform = process.platform, home = boxHome(env), run = runCommand, log = () => {}, shims = null, pkglog = null, pull = true, image: asked = null, onState = () => {}, spawnImpl, readyMs = 15_000 }: { root: string; runtime: BoxRuntime; env?: Env; platform?: NodeJS.Platform; home?: string; run?: RunCommand; log?: BoxLog; shims?: string | null; pkglog?: BoxInstallLog | null; pull?: boolean; image?: BoxImage | null; onState?: OnState; spawnImpl?: SpawnLike; readyMs?: number }): Promise<Box> {
+export async function openBox({ root, runtime, env = process.env, platform = process.platform, home = boxHome(env), run = runCommand, log = () => {}, shims = null, pkglog = null, pull = true, image: asked = null, onState = () => {}, onLine, spawnImpl, readyMs = 15_000 }: { root: string; runtime: BoxRuntime; env?: Env; platform?: NodeJS.Platform; home?: string; run?: RunCommand; log?: BoxLog; shims?: string | null; pkglog?: BoxInstallLog | null; pull?: boolean; image?: BoxImage | null; onState?: OnState; onLine?: RunOptions["onLine"]; spawnImpl?: SpawnLike; readyMs?: number }): Promise<Box> {
const projectRoot = path.resolve(root);
const key = boxKey(projectRoot, { platform });
const name = containerName(key, env);
@@ -210,7 +210,7 @@ export async function openBox({ root, runtime, env = process.env, platform = pro
try {
box.setState("starting", null, onState);
const chosen = asked ?? imageFor(detectStack(projectRoot), { env });
- const opened = await driver.open({ key, name, root: projectRoot, croot, runtime, run, home, runFolder, image: chosen, pull, shims, pkglog, env, platform, log, ...(spawnImpl ? { spawnImpl } : {}), onPulling: () => box.setState("pulling", null, onState) });
+ const opened = await driver.open({ key, name, root: projectRoot, croot, runtime, run, home, runFolder, image: chosen, pull, shims, pkglog, env, platform, log, ...(spawnImpl ? { spawnImpl } : {}), ...(onLine ? { onLine } : {}), onPulling: () => box.setState("pulling", null, onState) });
if (!opened.ok) return box.fail(opened.error, onState);
if (opened.created) writeJson(path.join(home, "chains", key, "image.json"), { ...opened.created, backend: runtime.backend ?? runtime.name, created_at: new Date().toISOString() });
// The first address that answers: the published/loopback one, then the box's own (Apple, WSL any).
diff --git a/apps/server/src/box/launch.ts b/apps/server/src/box/launch.ts
index 1c5ae2c8..bf405f83 100644
--- a/apps/server/src/box/launch.ts
+++ b/apps/server/src/box/launch.ts
@@ -18,7 +18,7 @@
// background, and a shell call waits for it (boxsh).
import { spawn, type ChildProcess } from "node:child_process";
-import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import path from "node:path";
import { boxKey, containerName, gcBoxes, installShell, openBox, recordFile, savedTurns, type Box, type BoxInstallLog, type BoxLabel, type BoxLog, type BoxRuntime, type CheckpointSummary } from "./box.js";
@@ -133,10 +133,15 @@ export function resolveMode({ env = process.env, project, server, offered = fals
// --- background download ---------------------------------------------------------------
-function pullMarker(home: string, runtime: Pick<BoxRuntime, "backend" | "name">, image: string): string {
+export function pullMarker(home: string, runtime: Pick<BoxRuntime, "backend" | "name">, image: string): string {
return path.join(home, "pulls", `${runtime.backend ?? runtime.name}-${image.replace(/[^a-zA-Z0-9._-]+/g, "_")}.pid`);
}
+/** The detached download's output (Desktop: its progress, pull-progress.ts). */
+export function pullLog(marker: string): string {
+ return marker.replace(/\.pid$/, ".log");
+}
+
/** Downloads running in this process (a backend with no detached command: the WSL distro). */
const inProcess = new Set<string>();
@@ -159,7 +164,7 @@ export function pulling(home: string, runtime: Pick<BoxRuntime, "backend" | "nam
* per image. A backend without a detached command (the WSL distro, whose
* download imports the distro first) downloads in this process instead.
*/
-export function pullInBackground(runtime: BoxRuntime, image: BoxImage, home: string, { spawnImpl = spawn, env = process.env, log = () => {} }: { spawnImpl?: (command: string, args: string[], options: { detached: boolean; stdio: "ignore"; windowsHide: boolean }) => Pick<ChildProcess, "pid" | "unref">; env?: NodeJS.ProcessEnv; log?: BoxLog } = {}): { started: boolean; pid: number | undefined } {
+export function pullInBackground(runtime: BoxRuntime, image: BoxImage, home: string, { spawnImpl = spawn, env = process.env, log = () => {} }: { spawnImpl?: (command: string, args: string[], options: { detached: boolean; stdio: "ignore" | ["ignore", number, number]; windowsHide: boolean }) => Pick<ChildProcess, "pid" | "unref">; env?: NodeJS.ProcessEnv; log?: BoxLog } = {}): { started: boolean; pid: number | undefined } {
const marker = pullMarker(home, runtime, image.pull);
if (inProcess.has(marker)) return { started: false, pid: process.pid };
try {
@@ -177,7 +182,15 @@ export function pullInBackground(runtime: BoxRuntime, image: BoxImage, home: str
.finally(() => inProcess.delete(marker));
return { started: true, pid: process.pid };
}
- const child = spawnImpl(cmd.bin, cmd.args, { detached: true, stdio: "ignore", windowsHide: true });
+ // Its output goes to a log next to the marker (the Settings card reads its progress there).
+ let out: number | null = null;
+ try { out = openSync(pullLog(marker), "w", 0o600); } catch { /* no progress then */ }
+ let child: Pick<ChildProcess, "pid" | "unref">;
+ try {
+ child = spawnImpl(cmd.bin, cmd.args, { detached: true, stdio: out === null ? "ignore" : ["ignore", out, out], windowsHide: true });
+ } finally {
+ if (out !== null) closeSync(out);
+ }
child.unref?.();
try { writeFileSync(marker, String(child.pid ?? "")); } catch { /* best effort */ }
return { started: true, pid: child.pid };
@@ -195,6 +208,8 @@ export type ReadyPlan = {
* POSIX wrappers), mounted into a new box and put on its PATH.
*/
start: (options?: { pkglog?: BoxInstallLog | null }) => Promise<Box>;
+ /** What the box start is doing ("starting", "pulling", "ready", "failed"; null before it starts). */
+ readonly phase: string | null;
};
export type NativePlan = { box: null; notice: string | null; runtime: RuntimeResult | null; image?: BoxImage; downloading?: boolean };
export type BoxPlan = ReadyPlan | NativePlan;
@@ -231,14 +246,16 @@ export async function planBox({ env = process.env, home, root, log = () => {}, r
}
if (env.OMNIRUSH_BOX_GC !== "off") setTimeout(() => gcInBackground(runtime, home, { log }), 30_000).unref?.();
let opening: Promise<Box> | null = null;
+ let phase: string | null = null;
return {
box: { key, home, root, runtime },
notice: null,
shell,
start: ({ pkglog = null } = {}) => {
- opening ??= openBox({ root, runtime, env, home, log, pull: false, shims, pkglog });
+ opening ??= openBox({ root, runtime, env, home, log, pull: false, shims, pkglog, onState: (state) => { phase = state; } });
return opening;
},
+ get phase() { return phase; },
};
}
@@ -337,9 +354,24 @@ export function boxRun(plan: ReadyPlan, { log = () => {}, readyWaitMs = 30_000,
log("warn", "box off for this project", { reason });
onNative(reason);
};
+ // The time limit counts while the box starts, not while its image downloads (the CLI's
+ // first --sandbox run on a slow link; here a box opens only once its image is in, so
+ // this only matters if a start ever downloads).
+ let settled = false;
+ opening.finally(() => { settled = true; }).catch(() => {});
+ const limit = () => new Promise<null>((resolve) => {
+ let from = Date.now();
+ const tick = () => {
+ if (settled) return resolve(null);
+ if (plan.phase === "pulling") from = Date.now();
+ if (Date.now() - from >= readyWaitMs) return resolve(null);
+ setTimeout(tick, Math.min(250, readyWaitMs)).unref?.();
+ };
+ tick();
+ });
const ready = async (): Promise<Box | null> => {
if (native) return null;
- const opened = await Promise.race([opening, new Promise<null>((resolve) => setTimeout(() => resolve(null), readyWaitMs))]);
+ const opened = await Promise.race([opening, limit()]);
if (opened?.ready) return opened;
if ([...checkpoints.values()].every((count) => count === 0)) goNative(opened?.error || "the sandbox did not start in time");
return null;
diff --git a/apps/server/src/box/pull-progress.ts b/apps/server/src/box/pull-progress.ts
new file mode 100644
index 00000000..c329a726
--- /dev/null
+++ b/apps/server/src/box/pull-progress.ts
@@ -0,0 +1,153 @@
+// Desktop only (the CLI prints its own pull): how far the background image
+// download is, for the Settings card's progress bar.
+//
+// The detached `<runtime> pull` writes its output next to its pid marker
+// (launch.ts pullInBackground). bubblewrap's boxrun says its bytes
+// ({"progress":{"bytes","total"}}, the CLI's progress.js reads the same).
+// Piped, Docker prints one line per layer
+// state and no byte counts, so the bytes come from the image's manifest
+// (`docker manifest inspect -v`, asked once per image, in the background):
+// a layer counts once its download is complete. Only the layers the runtime
+// names count: one already here (shared with another box image) is not
+// downloaded and may not be named at all. Without the manifest (Podman, a
+// local image, no network) only the layer counts are known.
+
+import { readFileSync, statSync } from "node:fs";
+
+import type { BoxRuntime } from "./common.js";
+import type { BoxImage } from "./images.js";
+import { runCommand, type RunCommand } from "./run.js";
+
+export type PullProgress = {
+ /** Bytes of the layers already downloaded (null: the layer sizes are not known). */
+ bytesDone: number | null;
+ bytesTotal: number | null;
+ layersDone: number;
+ /** The layers the runtime downloads (0 until it has listed them). */
+ layersTotal: number;
+ /** When the download started (ms since the epoch), when known. */
+ startedAt: number | null;
+};
+
+const DOWNLOADED = /^(Download complete|Extracting|Pull complete|Already exists)\b/;
+/** At most this much of the log's end is read (a pull writes a few lines per layer). */
+const LOG_TAIL = 256 << 10;
+
+/**
+ * Layers seen and downloaded in a pull's output (Docker: `<id>: <state>`;
+ * Podman: `Copying blob <id> [done|skipped]`), and boxrun's own byte count
+ * (`{"progress":{"bytes":N,"total":M}}`, its older `layer i/n <digest> <size> bytes`).
+ */
+export function parsePullLog(text: string): { seen: string[]; done: Set<string>; bytes: { done: number; total: number | null } | null; layers: number } {
+ const seen: string[] = [];
+ const done = new Set<string>();
+ let bytesDone: number | null = null;
+ let bytesTotal: number | null = null;
+ // boxrun names a layer once it is in, with how many there are.
+ let layers = 0;
+ const see = (id: string) => { if (!seen.includes(id)) seen.push(id); };
+ for (const raw of text.split(/\r?\n|\r/)) {
+ const line = raw.trim();
+ if (line.startsWith("{\"progress\"")) {
+ try {
+ const parsed: { progress?: { bytes?: unknown; total?: unknown } } | null = JSON.parse(line);
+ const read = Number(parsed?.progress?.bytes);
+ const total = Number(parsed?.progress?.total);
+ if (Number.isFinite(read)) bytesDone = read;
+ if (total > 0) bytesTotal = total;
+ } catch { /* a torn line */ }
+ continue;
+ }
+ const layer = /^layer (\d+)\/(\d+) sha256:([0-9a-f]{12})\S* (\d+) bytes$/.exec(line);
+ if (layer) {
+ // An older boxrun says only whole layers: they count once done.
+ see(layer[3]!);
+ done.add(layer[3]!);
+ layers = Math.max(layers, Number(layer[2]));
+ continue;
+ }
+ const docker = /^([0-9a-f]{12}): (.+)$/.exec(line);
+ if (docker) {
+ see(docker[1]!);
+ if (DOWNLOADED.test(docker[2]!)) done.add(docker[1]!);
+ continue;
+ }
+ const podman = /^Copying blob (?:sha256:)?([0-9a-f]{12})[0-9a-f]*(.*)$/.exec(line);
+ if (podman) {
+ see(podman[1]!);
+ if (/\b(done|skipped)\b/.test(podman[2]!)) done.add(podman[1]!);
+ }
+ }
+ return { seen, done, bytes: bytesDone === null ? null : { done: bytesDone, total: bytesTotal }, layers: Math.max(layers, seen.length) };
+}
+
+type LayerSizes = Map<string, number>;
+
+const GOARCH: Record<string, string> = { x64: "amd64", arm64: "arm64" };
+
+/** Layer sizes by short id (the first 12 hex digits of the digest) for this machine's platform, from `manifest inspect -v`. */
+export function parseManifestSizes(stdout: string, arch: string = GOARCH[process.arch] ?? process.arch): LayerSizes | null {
+ let value: unknown;
+ try { value = JSON.parse(stdout); } catch { return null; }
+ const entries = Array.isArray(value) ? value : [value];
+ type Entry = { Descriptor?: { platform?: { os?: string; architecture?: string } }; SchemaV2Manifest?: { layers?: unknown }; OCIManifest?: { layers?: unknown } };
+ const isEntry = (entry: unknown): entry is Entry => typeof entry === "object" && entry !== null;
+ const pick = entries.filter(isEntry).find((entry) => {
+ const platform = entry.Descriptor?.platform;
+ return !platform || (platform.os === "linux" && platform.architecture === arch);
+ });
+ const layers = pick?.SchemaV2Manifest?.layers ?? pick?.OCIManifest?.layers;
+ if (!Array.isArray(layers) || !layers.length) return null;
+ const sizes: LayerSizes = new Map();
+ for (const layer of layers) {
+ const digest = typeof layer?.digest === "string" ? layer.digest : "";
+ const size = typeof layer?.size === "number" ? layer.size : NaN;
+ const id = /^sha256:([0-9a-f]{12})/.exec(digest)?.[1];
+ if (!id || !Number.isFinite(size)) return null;
+ sizes.set(id, size);
+ }
+ return sizes;
+}
+
+/** Per image: the sizes once known, or when the last ask failed (asked again a minute later). */
+const sizesCache = new Map<string, { sizes: LayerSizes | null; at: number; asking: boolean }>();
+const RETRY_MS = 60_000;
+
+/** The layer sizes of `image` if known now; starts asking in the background otherwise (Docker only). */
+export function layerSizes(runtime: BoxRuntime, image: BoxImage, { run = runCommand, now = Date.now() }: { run?: RunCommand; now?: number } = {}): LayerSizes | null {
+ if (runtime.name !== "docker") return null;
+ const cached = sizesCache.get(image.pull);
+ if (cached?.sizes) return cached.sizes;
+ if (cached && (cached.asking || now - cached.at < RETRY_MS)) return null;
+ const entry = { sizes: null, at: now, asking: true };
+ sizesCache.set(image.pull, entry);
+ void run(runtime.bin, [...(runtime.prefix ?? []), "manifest", "inspect", "-v", image.pull], { timeoutMs: 20_000 })
+ .then((res) => { if (res.code === 0) sizesCache.set(image.pull, { sizes: parseManifestSizes(res.stdout), at: Date.now(), asking: false }); else entry.asking = false; })
+ .catch(() => { entry.asking = false; });
+ return null;
+}
+
+/** Forget the sizes asked (tests). */
+export function clearLayerSizes(): void {
+ sizesCache.clear();
+}
+
+/** The progress of a background download from its log; null when there is no log (a download in this process: the WSL distro). */
+export function pullProgress(log: string, marker: string, sizes: LayerSizes | null): PullProgress | null {
+ let text: string;
+ try {
+ const buffer = readFileSync(log);
+ text = buffer.subarray(Math.max(0, buffer.length - LOG_TAIL)).toString("utf8");
+ } catch {
+ return null;
+ }
+ let startedAt: number | null = null;
+ try { startedAt = Math.round(statSync(marker).mtimeMs); } catch { /* unknown */ }
+ const { seen, done, bytes, layers } = parsePullLog(text);
+ if (bytes?.total) return { bytesDone: Math.min(bytes.done, bytes.total), bytesTotal: bytes.total, layersDone: done.size, layersTotal: layers, startedAt };
+ // Bytes only when every layer the runtime named has a size (else the sizes are another image's or platform's).
+ const sized = sizes && seen.length && seen.every((id) => sizes.has(id)) ? sizes : null;
+ const bytesTotal = sized ? seen.reduce((sum, id) => sum + (sized.get(id) ?? 0), 0) : null;
+ const bytesDone = sized ? [...done].reduce((sum, id) => sum + (sized.get(id) ?? 0), 0) : null;
+ return { bytesDone, bytesTotal, layersDone: done.size, layersTotal: layers, startedAt };
+}
diff --git a/apps/server/src/box/run.ts b/apps/server/src/box/run.ts
index d7649d4d..e4da5f71 100644
--- a/apps/server/src/box/run.ts
+++ b/apps/server/src/box/run.ts
@@ -8,7 +8,7 @@ import { spawn, type ChildProcess } from "node:child_process";
type Env = NodeJS.ProcessEnv;
export type RunResult = { code: number; stdout: string; stderr: string; error?: string };
-export type RunOptions = { env?: Env; timeoutMs?: number; input?: string | Buffer; maxBytes?: number; cwd?: string };
+export type RunOptions = { env?: Env; timeoutMs?: number; input?: string | Buffer; maxBytes?: number; cwd?: string; signal?: AbortSignal; onLine?: (stream: "stdout" | "stderr", line: string) => void };
export type RunCommand = (bin: string, args: string[], options?: RunOptions) => Promise<RunResult>;
function errorText(error: unknown): string {
@@ -20,9 +20,17 @@ function errorCode(error: unknown): string {
return typeof code === "string" ? code : "spawn";
}
-/** Run a program with a time limit; never throws. */
-export function runCommand(bin: string, args: string[], { env = process.env, timeoutMs = 8_000, input, maxBytes = 64 << 20, cwd }: RunOptions = {}): Promise<RunResult> {
+/**
+ * Run a program with a time limit; never throws. `signal` (an AbortSignal)
+ * stops it early (a probe nobody needs any more); `onLine` hears each line
+ * of its output as it comes ("stdout" | "stderr", line), for progress.
+ */
+export function runCommand(bin: string, args: string[], { env = process.env, timeoutMs = 8_000, input, maxBytes = 64 << 20, cwd, signal, onLine }: RunOptions = {}): Promise<RunResult> {
return new Promise((resolve) => {
+ if (signal?.aborted) {
+ resolve({ code: -1, stdout: "", stderr: "", error: "aborted" });
+ return;
+ }
let child: ChildProcess;
try {
child = spawn(bin, args, { env, cwd, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], windowsHide: true });
@@ -38,14 +46,30 @@ export function runCommand(bin: string, args: string[], { env = process.env, tim
if (done) return;
done = true;
clearTimeout(timer);
+ signal?.removeEventListener?.("abort", abort);
resolve(value);
};
- const timer = setTimeout(() => {
+ const stop = (error: string) => {
try { child.kill("SIGKILL"); } catch { /* gone */ }
- finish({ code: -1, stdout: Buffer.concat(out).toString("utf8"), stderr: Buffer.concat(err).toString("utf8"), error: "timeout" });
- }, timeoutMs);
- child.stdout?.on("data", (chunk: Buffer) => { outBytes += chunk.length; if (outBytes <= maxBytes) out.push(chunk); });
- child.stderr?.on("data", (chunk: Buffer) => { if (err.length < 64) err.push(chunk); });
+ finish({ code: -1, stdout: Buffer.concat(out).toString("utf8"), stderr: Buffer.concat(err).toString("utf8"), error });
+ };
+ const timer = setTimeout(() => stop("timeout"), timeoutMs);
+ const abort = () => stop("aborted");
+ signal?.addEventListener?.("abort", abort, { once: true });
+ const lines = (stream: "stdout" | "stderr", hear: NonNullable<RunOptions["onLine"]>) => {
+ let rest = "";
+ return (chunk: Buffer) => {
+ rest += chunk.toString("utf8");
+ const parts = rest.split(/\r?\n|\r/);
+ rest = parts.pop() ?? "";
+ for (const line of parts) if (line) { try { hear(stream, line); } catch { /* a listener's problem */ } }
+ };
+ };
+ const outLine = onLine ? lines("stdout", onLine) : null;
+ const errLine = onLine ? lines("stderr", onLine) : null;
+ child.stdout?.on("data", (chunk: Buffer) => { outBytes += chunk.length; if (outBytes <= maxBytes) out.push(chunk); outLine?.(chunk); });
+ // Progress lines can be many: keep the first 64 chunks for the error text, hear them all.
+ child.stderr?.on("data", (chunk: Buffer) => { if (err.length < 64) err.push(chunk); errLine?.(chunk); });
child.on("error", (error) => finish({ code: -1, stdout: "", stderr: errorText(error), error: errorCode(error) }));
child.on("close", (code) => finish({ code: code ?? -1, stdout: Buffer.concat(out).toString("utf8"), stderr: Buffer.concat(err).toString("utf8") }));
if (input !== undefined) child.stdin?.end(input);
diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.ts
index 8e26de8f..a4fc3edb 100644
--- a/apps/server/src/box/service.ts
+++ b/apps/server/src/box/service.ts
@@ -28,9 +28,10 @@ import { boxHome, boxKey, boxSnapshotsDir, containerName, installShell, listBoxe
import { LABELS, OPT_IN, backendsFor, driverFor } from "./backends/index.js";
import type { BoxExec } from "./backends/types.js";
import { detectStack, imageFor } from "./images.js";
-import { askedBackend, boxRun, planBox, pulling, pullInBackground, resolveMode, saveBackend, serverBackends, serverDefault, shimsDir, type BoxRun, type ProjectBoxMode, type ServerBoxDefault } from "./launch.js";
+import { askedBackend, boxRun, planBox, pullLog, pullMarker, pulling, pullInBackground, resolveMode, saveBackend, serverBackends, serverDefault, shimsDir, type BoxRun, type ProjectBoxMode, type ServerBoxDefault } from "./launch.js";
import type { BoxInstallLogPaths } from "./install-log.js";
import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";
+import { layerSizes, pullProgress, type PullProgress } from "./pull-progress.js";
import { detectRuntime, type BackendAlternative, type DetectOptions, type RuntimeResult } from "./runtime.js";
/** What the capture side needs of a chat's box (plain data: it crosses to the capture worker). */
@@ -68,7 +69,11 @@ export type BoxStatus = {
/** The machine's backend setting and the values it takes here. */
backendSetting: { value: string; source: "env" | "setting" | "auto"; choices: Array<{ id: string; label: string }> };
image: { ref: string; stack: string; present: boolean | null; downloading: boolean } | null;
+ /** How far the image download is (while it downloads, when the runtime's output says). */
+ progress: PullProgress | null;
container: { name: string; exists: boolean; running: boolean } | null;
+ /** The server's OS (the card's next step when no backend works). */
+ platform: NodeJS.Platform;
/** One line for the user (why it is off, that it is downloading). */
notice: string | null;
error: string | null;
@@ -106,7 +111,8 @@ export type BoxServiceOptions = {
env?: NodeJS.ProcessEnv;
};
-type Project = { run: BoxRun | null; notice: string | null; planning: Promise<BoxRun | null> | null; nextPlanAt: number };
+/** `waitingImage`: planned while its image was downloading (planned again as soon as the image is here). */
+type Project = { run: BoxRun | null; notice: string | null; planning: Promise<BoxRun | null> | null; nextPlanAt: number; waitingImage: boolean };
/** A project whose image is downloading is planned again at most this often. */
const REPLAN_MS = 15_000;
@@ -222,7 +228,7 @@ export class BoxService {
if (workspace.workspaceType !== "local") return Promise.resolve(null);
const root = boxRoot(workspace);
const key = boxKey(root);
- const project = this.projects.get(key) ?? { run: null, notice: null, planning: null, nextPlanAt: 0 };
+ const project = this.projects.get(key) ?? { run: null, notice: null, planning: null, nextPlanAt: 0, waitingImage: false };
this.projects.set(key, project);
if (project.planning) return project.planning;
project.planning = (async () => {
@@ -236,6 +242,7 @@ export class BoxService {
if (project.run && !project.run.native) return project.run;
if (Date.now() < project.nextPlanAt) return null;
const plan = await planBox({ env: this.env, home: this.home, root, log: this.log, shims: shimsDir(this.env), ...this.detectOptions() });
+ project.waitingImage = !plan.box && plan.downloading === true;
if (!plan.box) {
project.run = null;
project.notice = plan.notice;
@@ -314,7 +321,7 @@ export class BoxService {
const base = { mode: settings.mode, serverDefault: server, on, source, offer, error: null };
const backendSetting = { ...askedBackend({ env: this.env, stateDir: this.options.stateDir }), choices: backendChoices() };
const setting = { value: backendSetting.backend, source: backendSetting.source, choices: backendSetting.choices };
- if (workspace.workspaceType !== "local") return { ...base, on: false, offer: false, state: "off", runtime: null, backend: null, backendSetting: setting, image: null, container: null, notice: "The sandbox is for folders on this computer." };
+ if (workspace.workspaceType !== "local") return { ...base, on: false, offer: false, state: "off", runtime: null, backend: null, backendSetting: setting, image: null, progress: null, container: null, platform: process.platform, notice: "The sandbox is for folders on this computer." };
// The full check (every backend) on a fresh look or once a minute; the cached choice otherwise.
const { asked, allow } = this.detectOptions();
const altKey = JSON.stringify([asked, allow]);
@@ -349,6 +356,15 @@ export class BoxService {
container = { name, exists: Boolean(mine), running: Boolean(mine?.running) };
}
const downloading = runtime.ok && pulling(this.home, runtime, image.pull);
+ // The download finished: plan the project now (not at its next chat), so the card goes on to starting and ready.
+ if (on && runtime.ok && project?.waitingImage && !downloading && (present || container?.exists)) {
+ project.waitingImage = false;
+ project.notice = null;
+ project.nextPlanAt = 0;
+ void this.ensure(workspace).catch(() => null);
+ }
+ const marker = runtime.ok ? pullMarker(this.home, runtime, image.pull) : null;
+ const progress = downloading && marker && runtime.ok ? pullProgress(pullLog(marker), marker, layerSizes(runtime, image)) : null;
const record = readRecord(this.home, key);
const run = project?.run ?? null;
const state: BoxStatus["state"] = !on ? "off"
@@ -363,12 +379,34 @@ export class BoxService {
backend,
backendSetting: setting,
image: { ref: image.pull, stack: image.stack, present, downloading },
+ progress,
container,
+ platform: process.platform,
notice: on ? project?.notice ?? (runtime.ok ? null : `Sandbox off for now: ${runtime.reason}.`) : null,
error: run?.box?.error ?? (record?.state === "off" || record?.state === "failed" ? record.error || null : null),
};
}
+ /**
+ * Try again now (the card's retry): a box that failed to start, or a
+ * project that went on without it, is planned again; its container and
+ * installs stay. The status after a fresh check.
+ */
+ async retry(workspace: BoxWorkspace): Promise<BoxStatus> {
+ const project = this.projects.get(boxKey(boxRoot(workspace)));
+ if (project && (project.run?.native || project.run?.box?.state === "failed")) project.run = null;
+ if (project) {
+ project.notice = null;
+ project.nextPlanAt = 0;
+ }
+ this.alternatives = null;
+ // A runtime started or installed meanwhile: the cached answer (a failure is kept 2 minutes) is asked again.
+ await Promise.race([this.detect({ fresh: true }), new Promise((resolve) => setTimeout(resolve, 10_000).unref?.())]);
+ await this.writeProjects();
+ void this.ensure(workspace).catch(() => null);
+ return this.status(workspace, { fresh: true });
+ }
+
/** Remove the project's container (installs gone); the next chat starts a fresh one. */
async reset(workspace: BoxWorkspace): Promise<{ removed: boolean }> {
const root = boxRoot(workspace);
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 3adc7091..04278cde 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -3827,6 +3827,15 @@ function createRoutes(
return jsonResponse({ ...status, engine });
});
+ // Try again now: a box that failed to start (or a project that went on without it) is planned again.
+ addRoute(routes, "POST", "/workspace/:id/box/retry", "client", async (ctx) => {
+ ensureWritable(config);
+ requireClientScope(ctx, "collaborator");
+ const workspace = await resolveWorkspace(config, ctx.params.id);
+ if (workspace.workspaceType !== "local") throw new ApiError(400, "box_unsupported", "The sandbox is for folders on this computer");
+ return jsonResponse(await boxServiceFor(config).retry(workspace));
+ });
+
addRoute(routes, "POST", "/workspace/:id/box/reset", "client", async (ctx) => {
ensureWritable(config);
requireClientScope(ctx, "collaborator");