@@ -463,9 +466,14 @@ export function WorkingTimelineRow({ row }: { row: Extract
}) {
const ctx = use(TimelineRowCtx);
- const { isCompacting, isPreparingWorktree, liveAnswerPreview, providerStartingLabel } =
- use(TimelineRowActivityCtx);
- if (isPreparingWorktree || isCompacting) return ;
+ const {
+ isCompacting,
+ isPreparingWorktree,
+ boatCloudStart,
+ liveAnswerPreview,
+ providerStartingLabel,
+ } = use(TimelineRowActivityCtx);
+ if (isPreparingWorktree || isCompacting || boatCloudStart) return ;
// A failed group keeps this disclosure while an approval waits, but nothing is thinking then.
const live = ctx.pendingApprovals.size === 0;
const { groupId } = row;
@@ -947,6 +955,7 @@ function WorkingWindowView({
const {
isCompacting,
isPreparingWorktree,
+ boatCloudStart,
turnEnded,
pendingRequest,
liveAnswerPreview,
@@ -1038,6 +1047,7 @@ function WorkingWindowView({
!workingWindowItemIsLive(window.items.at(-1)) &&
!isCompacting &&
!isPreparingWorktree &&
+ !boatCloudStart &&
!workingWindowHasActiveCompaction(window);
if (shown.length === 0 && !showThinking && !leading) return null;
return (
diff --git a/apps/web/src/components/chat/WorktreeSetupCard.tsx b/apps/web/src/components/chat/WorktreeSetupCard.tsx
index 2ecc73f099a79..1923f68330d84 100644
--- a/apps/web/src/components/chat/WorktreeSetupCard.tsx
+++ b/apps/web/src/components/chat/WorktreeSetupCard.tsx
@@ -1,10 +1,18 @@
-import type { WorktreeSetupSnapshot, WorktreeSetupStage } from "@t3tools/contracts";
+import type {
+ BoatCloudStartStep,
+ BoatCloudStepProgress,
+ WorktreeSetupSnapshot,
+ WorktreeSetupStage,
+} from "@t3tools/contracts";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import {
BrainIcon,
+ CloudIcon,
FolderGit2Icon,
GitBranchIcon,
PackageIcon,
+ PlugIcon,
+ ServerIcon,
TerminalIcon,
XIcon,
} from "lucide-react";
@@ -333,3 +341,73 @@ export function WorktreeSetupRows({
);
}
+
+/** A Boat cloud start as the thread shows it while its first message waits. */
+export interface BoatCloudStartRowsState {
+ readonly steps: ReadonlyArray;
+ /** `owner/repo`, for the checkout step. */
+ readonly repository: string | null;
+ /** A stopped VM turning back on rather than a new start. */
+ readonly waking?: boolean;
+}
+
+const BOAT_CLOUD_STEP_ICONS = {
+ machine: CloudIcon,
+ server: ServerIcon,
+ repository: GitBranchIcon,
+ connect: PlugIcon,
+ project: FolderGit2Icon,
+ thread: BrainIcon,
+} satisfies Record;
+
+/** Running, done and failed labels per step. */
+const BOAT_CLOUD_STEP_LABELS = {
+ machine: ["Starting a VM", "Started a VM", "Couldn't start a VM"],
+ server: [
+ "Starting T3 Code on the VM",
+ "Started T3 Code on the VM",
+ "Couldn't start T3 Code on the VM",
+ ],
+ repository: ["Checking out", "Checked out", "Couldn't check out"],
+ connect: ["Connecting to the VM", "Connected to the VM", "Couldn't connect to the VM"],
+ project: ["Opening the project", "Opened the project", "Couldn't open the project"],
+ thread: ["Starting agent", "Started agent", "Couldn't start agent"],
+} satisfies Record;
+
+const WAKING_MACHINE_LABELS = ["Waking the VM", "Woke the VM", "Couldn't wake the VM"] as const;
+
+function boatCloudStepLabel(
+ entry: BoatCloudStepProgress,
+ repository: string | null,
+ waking: boolean,
+): string {
+ const [running, done, failed] =
+ waking && entry.step === "machine" ? WAKING_MACHINE_LABELS : BOAT_CLOUD_STEP_LABELS[entry.step];
+ const label = entry.state === "failed" ? failed : entry.state === "done" ? done : running;
+ return entry.step === "repository" ? `${label} ${repository ?? "the repository"}` : label;
+}
+
+/** The Boat cloud steps still left when the first message was sent, as setup rows that appear as they start. */
+export function BoatCloudStartRows({ steps, repository, waking = false }: BoatCloudStartRowsState) {
+ return (
+
+ {steps.map((entry) => {
+ const icon = BOAT_CLOUD_STEP_ICONS[entry.step];
+ const label = boatCloudStepLabel(entry, repository, waking);
+ return entry.state === "active" ? (
+
+
+
+ ) : (
+
+ );
+ })}
+
+ );
+}
diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts
index 788be2219ea0b..f926255fe6b0e 100644
--- a/apps/web/src/components/chat/timelineRowContext.ts
+++ b/apps/web/src/components/chat/timelineRowContext.ts
@@ -21,6 +21,7 @@ import { useEffect, useRef, createContext, type MouseEvent, type ReactNode } fro
import { type LegendListRef } from "@legendapp/list/react";
import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
import type { PendingApproval } from "../../session-logic";
+import type { BoatCloudStartRowsState } from "./WorktreeSetupCard";
import { type ChatFileAttachment } from "../../types";
import { ExpandedImagePreview } from "./ExpandedImagePreview";
import { type AssistantCitationTarget } from "./AssistantCitationSource";
@@ -120,6 +121,8 @@ export interface TimelineRowActivityState {
latestRunId: RunId | null;
/** The worktree setup of the live turn, drawn as the working row's first rows. */
worktreeSetup: WorktreeSetupSnapshot | null;
+ /** The Boat cloud steps a draft's first message still waits on, drawn the same way. */
+ boatCloudStart: BoatCloudStartRowsState | null;
liveAnswerPreview: string | null;
/** The approval or question the running turn waits on; it pauses the clock. */
pendingRequest: TimelinePendingRequest | null;
diff --git a/apps/web/src/components/chat/useBoatCloudStartBanner.tsx b/apps/web/src/components/chat/useBoatCloudStartBanner.tsx
new file mode 100644
index 0000000000000..d15ebe0aae112
--- /dev/null
+++ b/apps/web/src/components/chat/useBoatCloudStartBanner.tsx
@@ -0,0 +1,54 @@
+import { useAtomValue } from "@effect/atom-react";
+
+import { boatCloudStartProgressAtom, clearBoatCloudStartProgress } from "../../boatCloud";
+import { stepsLeftAtSend } from "../../boatCloudStart.logic";
+import {
+ type DraftId,
+ type DraftSessionState,
+ isCloudEnvironmentSelection,
+} from "../../composerDraftStore";
+import { BoatIcon, BoxdIcon } from "../Icons";
+import type { ComposerBannerStackItem } from "./ComposerBannerStack";
+import type { BoatCloudStartRowsState } from "./WorktreeSetupCard";
+
+/**
+ * A Boat cloud start runs quietly behind the composer. Once a message waits on it, the thread
+ * shows the steps still left, timed from the send; a failure shows as a banner until dismissed.
+ */
+export function useBoatCloudStartBanner(
+ draftId: DraftId | null,
+ draftThread: DraftSessionState | null,
+): {
+ bannerItem: ComposerBannerStackItem | null;
+ threadRows: BoatCloudStartRowsState | null;
+ sentAt: string | null;
+} {
+ const progress = useAtomValue(boatCloudStartProgressAtom(draftId ?? ""));
+ if (
+ draftId === null ||
+ progress === null ||
+ !isCloudEnvironmentSelection(draftThread?.environmentSelection) ||
+ draftThread?.promotedTo
+ ) {
+ return { bannerItem: null, threadRows: null, sentAt: null };
+ }
+ const steps = stepsLeftAtSend(progress);
+ const threadRows = steps ? { steps, repository: progress.repository } : null;
+ const sentAt = threadRows ? (progress.sent?.at ?? null) : null;
+ if (progress.error === null) return { bannerItem: null, threadRows, sentAt };
+ const boxd = draftThread?.environmentSelection === "boxd";
+ return {
+ bannerItem: {
+ id: `boat-cloud-start:${draftId}`,
+ group: "environment",
+ variant: "error",
+ icon: boxd ? : ,
+ title: boxd ? "Could not start on boxd cloud" : "Could not start on Boat cloud",
+ description: progress.error,
+ dismissLabel: "Dismiss",
+ onDismiss: () => clearBoatCloudStartProgress(draftId),
+ },
+ threadRows,
+ sentAt,
+ };
+}
diff --git a/apps/web/src/components/chat/useComposerResume.browser.test.tsx b/apps/web/src/components/chat/useComposerResume.browser.test.tsx
index adcca8da91c49..7ea2f07edc03e 100644
--- a/apps/web/src/components/chat/useComposerResume.browser.test.tsx
+++ b/apps/web/src/components/chat/useComposerResume.browser.test.tsx
@@ -5,8 +5,11 @@ import { expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
startedTurn: null as ReturnType> | null,
+ sleep: null as BoatCloudSleep | null,
}));
+vi.mock(import("../../boatCloud"), () => ({ useBoatCloudSleep: () => state.sleep }));
+
vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({
...(await importOriginal()),
useOrchestrationCommand: (() => async (value: { readonly input: unknown }) => {
@@ -16,6 +19,7 @@ vi.mock(import("../../state/use-orchestration-command"), async (importOriginal)
}));
import { render } from "../../../test/render";
+import type { BoatCloudSleep } from "../../boatCloud";
import type { ComposerHandleRef } from "../../composerHandleContext";
import { useComposerResume } from "./useComposerResume";
@@ -30,6 +34,7 @@ function deferred() {
function setup() {
const startedTurn = deferred();
state.startedTurn = startedTurn;
+ state.sleep = null;
return { startedTurn };
}
@@ -44,6 +49,7 @@ function composerShowing(selectedModelSelection: typeof threadAModel) {
function ResumeButton(props: {
readonly composerRef: ComposerHandleRef;
readonly persistSettings: () => Promise>;
+ readonly environmentUnavailable?: boolean;
}) {
const { onResume } = useComposerResume({
environmentId: EnvironmentId.make("environment:test"),
@@ -56,7 +62,7 @@ function ResumeButton(props: {
isSendBusy: false,
isRevertingCheckpoint: false,
threadDetailLoading: false,
- activeEnvironmentUnavailable: false,
+ activeEnvironmentUnavailable: props.environmentUnavailable ?? false,
runtimeMode: "full-access",
localCheckoutBranchMismatch: null,
composerRef: props.composerRef,
@@ -91,3 +97,33 @@ it("continues on the resumed thread's model after the composer moves to another
modelSelection: threadAModel,
});
});
+
+it("wakes a sleeping Boat VM before resuming on it", async () => {
+ const { startedTurn } = setup();
+ const woken = deferred();
+ const wake = vi.fn(() => woken.promise);
+ state.sleep = { state: "sleeping", wake };
+ const composerRef: ComposerHandleRef = { current: composerShowing(threadAModel) };
+ const persistSettings = async () => AsyncResult.success(undefined);
+ await using screen = await render(
+ ,
+ );
+
+ await screen.getByRole("button", { name: "Resume" }).click();
+ expect(wake).toHaveBeenCalledOnce();
+ // The wake resolves only after the VM is connected again.
+ state.sleep = null;
+ await screen.rerender(
+ ,
+ );
+ woken.resolve(true);
+
+ expect(await startedTurn.promise).toMatchObject({
+ threadId: threadA,
+ manualContinuationOfRunId: "run:interrupted",
+ });
+});
diff --git a/apps/web/src/components/chat/useComposerResume.ts b/apps/web/src/components/chat/useComposerResume.ts
index 7dac1a5d8e105..771ae9b89cbae 100644
--- a/apps/web/src/components/chat/useComposerResume.ts
+++ b/apps/web/src/components/chat/useComposerResume.ts
@@ -11,8 +11,12 @@ import {
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import { useState } from "react";
+import { flushSync } from "react-dom";
import { newMessageId } from "~/lib/utils";
+import { useBoatCloudSleep } from "../../boatCloud";
import type { ComposerHandleRef } from "../../composerHandleContext";
+import { useStableCallback } from "../../hooks/useStableCallback";
+import { useEnvironment } from "../../state/environments";
import { DEFAULT_INTERACTION_MODE } from "../../types";
import { threadEnvironment } from "../../state/threads";
import { useOrchestrationCommand } from "../../state/use-orchestration-command";
@@ -84,6 +88,10 @@ export function useComposerResume(input: ComposerResumeInput) {
);
const isResuming = resumingThreadKeys.has(routeThreadKey);
const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
+ const boatCloudSleep = useBoatCloudSleep(
+ environmentId,
+ useEnvironment(environmentId)?.connection.phase ?? null,
+ );
const onResume = async () => {
if (
@@ -163,5 +171,20 @@ export function useComposerResume(input: ComposerResumeInput) {
});
};
- return { onResume, isResuming };
+ // A sleeping Boat VM wakes first, as a send does, then the resume reads the connected state.
+ const onResumeLatest = useStableCallback(onResume);
+ const onResumeWithWake = async () => {
+ if (boatCloudSleep === null || !activeThread || !canResume || sendInFlightRef.current) {
+ return onResume();
+ }
+ sendInFlightRef.current = true;
+ const ready = await boatCloudSleep.wake().finally(() => {
+ sendInFlightRef.current = false;
+ });
+ if (!ready || currentRouteThreadKeyRef.current !== routeThreadKey) return;
+ flushSync(() => {});
+ await onResumeLatest();
+ };
+
+ return { onResume: onResumeWithWake, isResuming };
}
diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts
index cf15017f43ac9..3848f663f83b3 100644
--- a/apps/web/src/components/chat/useComposerSend.ts
+++ b/apps/web/src/components/chat/useComposerSend.ts
@@ -1,3 +1,4 @@
+import { markBoatCloudStartSent, unmarkBoatCloudStartSent } from "../../boatCloud";
import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger";
import { armFreshSession, disarmFreshSession, readFreshSessionArm } from "./freshSessionArms";
import {
@@ -23,6 +24,7 @@ import {
type MessageId,
type ModelSelection,
type PreviewAnnotationPayload,
+ type ResponseContextRecord,
type ScopedThreadRef,
type ThreadId,
type RunId,
@@ -48,6 +50,7 @@ import {
} from "@t3tools/client-runtime/environment";
import { createModelSelection } from "@t3tools/shared/model";
import { type SetStateAction, useLayoutEffect, useRef, useState } from "react";
+import { flushSync } from "react-dom";
import { useNavigate } from "@tanstack/react-router";
import {
isAtomCommandInterrupted,
@@ -77,6 +80,7 @@ import {
type ComposerFileAttachment,
type ComposerImageAttachment,
type DraftThreadEnvMode,
+ isCloudEnvironmentSelection,
useComposerDraftStore,
DraftId,
} from "../../composerDraftStore";
@@ -134,6 +138,7 @@ import {
prepareTurnAttachments,
restoreComposerDraft,
} from "./chatViewSend";
+import type { ChatComposerHandle } from "./ChatComposer";
import type {
EnvironmentProject,
EnvironmentThreadShell,
@@ -224,6 +229,9 @@ interface ComposerSendInput {
readonly needsLoadBalancing: boolean;
readonly loadBalancing: DraftEnvironmentRouting["loadBalancing"];
readonly refreshBeforeSend: DraftEnvironmentRouting["refreshBeforeSend"];
+ /** Turns the thread's sleeping Boat VM back on as the send goes out; null when it is not asleep. */
+ readonly wakeBeforeSend: (() => Promise) | null;
+ readonly onRoutedSendDispatched: DraftEnvironmentRouting["onRoutedSendDispatched"];
readonly readPendingEnvironmentChange: DraftEnvironmentRouting["readPendingEnvironmentChange"];
readonly pendingApprovals: PendingThreadRequests["pendingApprovals"];
readonly respondingRequestIds: PendingThreadRequests["respondingRequestIds"];
@@ -271,6 +279,25 @@ interface ComposerSendInput {
* thread, a feedback upload, and resuming an interrupted run. Each path restores the draft
* when it fails.
*/
+
+type ComposerSendContext = ReturnType;
+
+/** A message taken out of the composer before it could go out, already shown in the thread. */
+interface QueuedComposerSend {
+ readonly message: ChatMessage;
+ readonly content: Pick<
+ ComposerSendContext,
+ | "prompt"
+ | "images"
+ | "files"
+ | "terminalContexts"
+ | "previewAnnotations"
+ | "reviewComments"
+ | "threadContexts"
+ | "environmentContexts"
+ > & { readonly replyTo: ResponseContextRecord | null };
+}
+
export function useComposerSend(input: ComposerSendInput) {
const {
environmentId,
@@ -322,6 +349,8 @@ export function useComposerSend(input: ComposerSendInput) {
needsLoadBalancing,
loadBalancing,
refreshBeforeSend,
+ wakeBeforeSend,
+ onRoutedSendDispatched,
readPendingEnvironmentChange,
pendingApprovals,
respondingRequestIds,
@@ -395,12 +424,25 @@ export function useComposerSend(input: ComposerSendInput) {
annotation: PreviewAnnotationPayload;
image: ComposerImageAttachment | null;
},
+ /**
+ * A message that already left the composer: it sends from its own contents, replaces its
+ * shown copy, and calls `onAccepted` once on its way, after which a failure restores it.
+ */
+ queued?: { readonly send: QueuedComposerSend; readonly onAccepted: () => void },
) => {
e?.preventDefault();
// What the user pressed send on; uploads below can take a while, and a redirect must not
// decline approvals for a draft that changed meanwhile.
- const promptAtSend = promptRef.current;
+ const promptAtSend = queued?.send.content.prompt ?? promptRef.current;
+ // The composer of a queued message was cleared when it left, and may hold a newer draft.
+ const clearSentDraft = () => {
+ if (queued) return;
+ promptRef.current = "";
+ clearComposerDraftContent(composerDraftTarget);
+ composerRef.current?.resetCursorState();
+ };
if (
+ !queued &&
usageLimitsOffered &&
usageLimitsKey !== null &&
!directAnnotation &&
@@ -415,7 +457,16 @@ export function useComposerSend(input: ComposerSendInput) {
return;
}
- const sendCtx = composerRef.current?.getSendContext();
+ const liveSendCtx = composerRef.current?.getSendContext();
+ const sendCtx: ComposerSendContext | undefined =
+ queued && liveSendCtx
+ ? {
+ ...liveSendCtx,
+ ...queued.send.content,
+ answeringPendingUserInput: false,
+ shownPendingApprovalIds: [],
+ }
+ : liveSendCtx;
// `/side` beats an open question and a plan follow-up, which would send the text to main.
const sideChatCommand =
sendCtx && !directAnnotation && !queuedRunEdit.isEditing
@@ -618,9 +669,10 @@ export function useComposerSend(input: ComposerSendInput) {
? ensureInlineContextReferences(promptRef.current, [
previewAnnotationContextReference(directAnnotation.annotation),
])
- : promptRef.current;
- const replyTo =
- useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null;
+ : (queued?.send.content.prompt ?? promptRef.current);
+ const replyTo = queued
+ ? queued.send.content.replyTo
+ : (useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null);
// The reply leads the message, so its card sits above the text it is about. Text that
// already points at that response, from a pasted card, keeps its one reference.
const promptForSend =
@@ -709,11 +761,7 @@ export function useComposerSend(input: ComposerSendInput) {
command: trimmed,
createdAt: new Date().toISOString(),
},
- clearDraft: () => {
- promptRef.current = "";
- clearComposerDraftContent(composerDraftTarget);
- composerRef.current?.resetCursorState();
- },
+ clearDraft: clearSentDraft,
onUpdate: (submission) => {
setFeedbackSubmissionsByThreadKey((current) => {
const existing = current[routeThreadKey] ?? [];
@@ -748,9 +796,7 @@ export function useComposerSend(input: ComposerSendInput) {
replyTo === null;
if (freshSessionAvailable && composerHoldsOnlyText && isClearComposerCommand(trimmed)) {
armFreshSession(routeThreadKey);
- promptRef.current = "";
- clearComposerDraftContent(composerDraftTarget);
- composerRef.current?.resetCursorState();
+ clearSentDraft();
return;
}
// Read once: an arm made while this send is in flight belongs to the next message.
@@ -847,7 +893,7 @@ export function useComposerSend(input: ComposerSendInput) {
const outgoingMessageContext = buildOutgoingMessageContext(
composerAttachmentsSnapshot.map((attachment) => attachment.id),
);
- const messageIdForSend = newMessageId();
+ const messageIdForSend = queued?.send.message.id ?? newMessageId();
const messageCreatedAt = new Date().toISOString();
const outgoingMessageText = formatOutgoingPrompt({
provider: ctxSelectedProvider,
@@ -983,6 +1029,7 @@ export function useComposerSend(input: ComposerSendInput) {
// the user sent. A direct annotation send writes its image and reference into the draft
// as it sends, so the live draft may still lack them.
const draftChangedSinceSend = () => {
+ if (queued) return false;
const sendContext = composerRef.current?.getSendContext();
// The reply is not in the prompt, so cancelling or changing it is checked on its own.
const liveReply =
@@ -1041,9 +1088,7 @@ export function useComposerSend(input: ComposerSendInput) {
useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
draftBeforeDecline
) {
- promptRef.current = "";
- clearComposerDraftContent(composerDraftTarget);
- composerRef.current?.resetCursorState();
+ clearSentDraft();
}
return;
}
@@ -1123,6 +1168,7 @@ export function useComposerSend(input: ComposerSendInput) {
usesAttachmentUploads: turnUsesAttachmentUploads,
});
if (multipleModelSelections !== null) {
+ queued?.onAccepted();
await sendToMultipleModels({
threadId: threadIdForSend,
project: activeProject,
@@ -1169,7 +1215,11 @@ export function useComposerSend(input: ComposerSendInput) {
} else {
optimisticBlobPreviews.release(optimisticMessage);
}
- setOptimisticUserMessages((existing) => [...existing, optimisticMessage]);
+ setOptimisticUserMessages((existing) => [
+ ...existing.filter((message) => message.id !== messageIdForSend),
+ optimisticMessage,
+ ]);
+ queued?.onAccepted();
if (shouldQueueBehindActiveRun) {
undispatchedQueuedSendsRef.current.set(messageIdForSend, optimisticMessage);
}
@@ -1192,9 +1242,7 @@ export function useComposerSend(input: ComposerSendInput) {
: null;
// Keep new-thread flows from reusing this draft while attachments and worktree setup settle.
if (sentDraftThreadRef) markPromotedDraftThreadByRef(sentDraftThreadRef);
- promptRef.current = "";
- clearComposerDraftContent(composerDraftTarget);
- composerRef.current?.resetCursorState();
+ clearSentDraft();
const title = deriveThreadTitleSeed({
text: messageTextForSend,
@@ -1609,18 +1657,182 @@ export function useComposerSend(input: ComposerSendInput) {
};
const onSendLatest = useStableCallback(onSend);
+
+ // The sends waiting on a Boat VM that starts or wakes, chained in the order they were sent.
+ const boatCloudSendsRef = useRef | null>(null);
+ // Open once the thread takes another message: idle, or queueing behind its starting run.
+ const sendGateRef = useRef({ open: true, waiters: [] as Array<() => void> });
+ const sendGateOpen = !isSendBusy || sendQueuesBehindSetup;
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases sends queued behind a Boat VM once the thread takes another message
+ useLayoutEffect(() => {
+ const gate = sendGateRef.current;
+ gate.open = sendGateOpen;
+ if (sendGateOpen) for (const release of gate.waiters.splice(0)) release();
+ }, [sendGateOpen]);
+ const whenThreadTakesMessages = () =>
+ sendGateRef.current.open
+ ? Promise.resolve()
+ : new Promise((resolve) => sendGateRef.current.waiters.push(resolve));
+
+ /** Takes the composer's message out for a send that goes out later, and shows it now. */
+ const takeComposerSend = (queuedBehind: boolean): QueuedComposerSend | null => {
+ const context = composerRef.current?.getSendContext();
+ if (!context) return null;
+ const content: QueuedComposerSend["content"] = {
+ prompt: promptRef.current,
+ images: context.images,
+ files: context.files,
+ terminalContexts: context.terminalContexts,
+ previewAnnotations: context.previewAnnotations,
+ reviewComments: context.reviewComments,
+ threadContexts: context.threadContexts,
+ environmentContexts: context.environmentContexts,
+ replyTo:
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null,
+ };
+ const { trimmedPrompt, hasSendableContent } = deriveComposerSendState({
+ prompt: content.prompt,
+ imageCount: content.images.length + content.files.length,
+ terminalContexts: content.terminalContexts,
+ elementContextCount:
+ content.previewAnnotations.length +
+ content.reviewComments.length +
+ content.threadContexts.length +
+ content.environmentContexts.length,
+ });
+ if (!hasSendableContent) return null;
+ const createdAt = new Date().toISOString();
+ const attachments = optimisticMessageAttachments([...content.images, ...content.files]);
+ const message: ChatMessage = {
+ id: newMessageId(),
+ role: "user",
+ text: trimmedPrompt,
+ ...(attachments.length > 0 ? { attachments } : {}),
+ runId: null,
+ createdAt,
+ updatedAt: createdAt,
+ streaming: false,
+ ...(queuedBehind ? { inputIntent: "queued_turn" as const } : {}),
+ };
+ setOptimisticUserMessages((existing) => [...existing, message]);
+ promptRef.current = "";
+ clearComposerDraftContent(composerDraftTarget);
+ composerRef.current?.resetCursorState();
+ return { message, content };
+ };
+
+ /** A queued message that never went out goes back to the composer, or to a toast when it holds a newer draft. */
+ const putBackComposerSend = useStableCallback((queued: QueuedComposerSend) => {
+ setOptimisticUserMessages((existing) =>
+ existing.filter((message) => message.id !== queued.message.id),
+ );
+ const draft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget);
+ const composerHoldsDraft =
+ promptRef.current.trim().length > 0 ||
+ (draft?.images.length ?? 0) > 0 ||
+ (draft?.files.length ?? 0) > 0;
+ if (composerHoldsDraft) {
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Message not sent",
+ description: "Your new draft was kept. Copy the failed message to send it again.",
+ timeout: 0,
+ data: { hideCopyButton: true },
+ actionProps: {
+ children: "Copy message",
+ onClick: () => {
+ void writeTextToClipboard(queued.message.text, "failed message").catch(
+ () => undefined,
+ );
+ },
+ },
+ }),
+ );
+ return;
+ }
+ const snapshot = snapshotComposerSend({
+ ...queued.content,
+ sendableTerminalContexts: queued.content.terminalContexts,
+ });
+ composerImagesRef.current = restoreComposerDraft(composerDraftTarget, snapshot);
+ composerFilesRef.current = snapshot.files;
+ composerTerminalContextsRef.current = snapshot.terminalContexts;
+ promptRef.current = snapshot.draftText;
+ composerRef.current?.resetCursorState({
+ cursor: collapseExpandedComposerCursor(snapshot.draftText, snapshot.draftText.length),
+ prompt: snapshot.draftText,
+ detectTrigger: true,
+ });
+ });
+
+ const sendQueued = async (args: Parameters, send: QueuedComposerSend) => {
+ let accepted = false;
+ await onSendLatest(args[0], args[1], args[2], undefined, {
+ send,
+ onAccepted: () => {
+ accepted = true;
+ },
+ });
+ if (!accepted) putBackComposerSend(send);
+ };
+
+ const trackBoatCloudSend = (send: Promise) => {
+ const settled = send.then(
+ () => undefined,
+ () => undefined,
+ );
+ boatCloudSendsRef.current = settled;
+ return send.finally(() => {
+ if (boatCloudSendsRef.current === settled) boatCloudSendsRef.current = null;
+ });
+ };
+
const onSendWithRouting = async (...args: Parameters) => {
args[0]?.preventDefault();
- const refresh =
- args[3] || sendInFlightRef.current || readPendingEnvironmentChange() !== null
- ? null
- : refreshBeforeSend();
+ const ahead = boatCloudSendsRef.current;
+ if (ahead !== null && !args[3]) {
+ // Behind a send that waits on a Boat VM, a message queues as it would behind a running turn.
+ const queued = takeComposerSend(true);
+ if (queued === null) return;
+ return trackBoatCloudSend(
+ ahead.then(whenThreadTakesMessages).then(() => sendQueued(args, queued)),
+ );
+ }
+ const routable =
+ !args[3] && !sendInFlightRef.current && readPendingEnvironmentChange() === null;
+ if (routable && wakeBeforeSend !== null) {
+ // The send goes out now and its commands wait on this wake.
+ void wakeBeforeSend();
+ return trackBoatCloudSend(onSend(...args));
+ }
+ const refresh = routable ? refreshBeforeSend() : null;
if (refresh === null) return onSend(...args);
+ // A Boat cloud start takes a while, so the message moves to the thread now and goes out
+ // once the VM is ready. The composer stays free for the next one, which queues behind it.
+ const waitsOnBoatCloud =
+ isCloudEnvironmentSelection(draftThread?.environmentSelection) && !draftThread?.promotedTo;
+ const queued = waitsOnBoatCloud ? takeComposerSend(false) : null;
+ if (queued !== null) markBoatCloudStartSent(draftId);
+ const sendWhenReady = async () => {
+ const ready = await refresh.finally(() => {
+ sendInFlightRef.current = false;
+ });
+ // A draft's instance is keyed by its draft, so a route change there is the same draft moving
+ // or promoting. A server thread's instance is reused across threads, so it must still be here.
+ if (!ready || (draftId === null && currentRouteThreadKeyRef.current !== routeThreadKey)) {
+ if (queued !== null) putBackComposerSend(queued);
+ return;
+ }
+ // A woken VM's connection lands in a store update; commit it so the send reads it.
+ flushSync(() => {});
+ if (queued === null) await onSendLatest(...args);
+ else await sendQueued(args, queued);
+ onRoutedSendDispatched();
+ };
sendInFlightRef.current = true;
- const ready = await refresh.finally(() => {
- sendInFlightRef.current = false;
- });
- if (ready) return onSendLatest(...args);
+ if (queued === null) return sendWhenReady();
+ return trackBoatCloudSend(sendWhenReady().finally(() => unmarkBoatCloudStartSent(draftId)));
};
return {
onSend: onSendWithRouting,
diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx
index 0dafee8167119..2a863047262bb 100644
--- a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx
+++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx
@@ -85,6 +85,8 @@ function setup() {
label: id,
displayUrl: null,
relayManaged: false,
+ boatCloud: false,
+ boxdCloud: false,
entry: {
target: new PrimaryConnectionTarget({
environmentId: id,
diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts
index 3f67e8c9c7987..86a608c48e989 100644
--- a/apps/web/src/components/chat/useDraftEnvironmentRouting.ts
+++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.ts
@@ -26,16 +26,36 @@ import {
deriveLogicalProjectKeyFromSettings,
selectProjectGroupingSettings,
} from "@t3tools/client-runtime/state/project-grouping";
-import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
+import {
+ type CloudEnvironmentSelection,
+ isCloudEnvironmentSelection,
+ useComposerDraftStore,
+ DraftId,
+} from "../../composerDraftStore";
import { type EnvironmentPresentation, useEnvironmentProviders } from "../../state/environments";
import { currentClientMetadata } from "../../connection/platform";
import { useProjects } from "../../state/entities";
+import { rememberOpenedBoatCloudThread } from "../../state/boatCloudThreads";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import type { DraftSessionState } from "../../composerDraftStore";
import { loadBalancingSendWarning } from "./composerSend.logic";
import { appAtomRegistry } from "../../rpc/atomRegistry";
import { draftFanoutSelectionsAtom } from "./chatViewSend";
+import {
+ boatCloudReady,
+ clearBoatCloudStartProgress,
+ prepareBoatCloudProject,
+ prewarmBoatCloudProject,
+ usePrimaryBoatCloudStatus,
+} from "../../boatCloud";
+import {
+ boxdCloudReady,
+ clearBoxdCloudStartProgress,
+ prepareBoxdCloudProject,
+ prewarmBoxdCloudProject,
+ usePrimaryBoxdCloudStatus,
+} from "../../boxdCloud";
interface DraftEnvironmentRoutingInput {
readonly draftId: DraftId | null;
@@ -132,7 +152,146 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
loadBalancingSettings.loadBalancingWeights,
);
const readRouting = useStableCallback(() => ({ input, loadBalancingCandidates }));
+ const boatCloud = usePrimaryBoatCloudStatus();
+ const boxdCloud = usePrimaryBoxdCloudStatus();
+ const clouds = {
+ cloud: {
+ name: "Boat cloud",
+ holderEnvironmentId: boatCloud.holderEnvironmentId,
+ ready: boatCloudReady(boatCloud.status),
+ prepare: prepareBoatCloudProject,
+ prewarm: prewarmBoatCloudProject,
+ clear: clearBoatCloudStartProgress,
+ },
+ boxd: {
+ name: "boxd cloud",
+ holderEnvironmentId: boxdCloud.holderEnvironmentId,
+ ready: boxdCloudReady(boxdCloud.status),
+ prepare: prepareBoxdCloudProject,
+ prewarm: prewarmBoxdCloudProject,
+ clear: clearBoxdCloudStartProgress,
+ },
+ } satisfies Record;
+ const carryFanoutSelections = (
+ from: {
+ readonly environmentId: EnvironmentId;
+ readonly threadId: DraftSessionState["threadId"];
+ },
+ toEnvironmentId: EnvironmentId,
+ ) => {
+ if (toEnvironmentId === from.environmentId) return;
+ appAtomRegistry.set(
+ draftFanoutSelectionsAtom(scopedThreadKey(scopeThreadRef(toEnvironmentId, from.threadId))),
+ appAtomRegistry.get(
+ draftFanoutSelectionsAtom(
+ scopedThreadKey(scopeThreadRef(from.environmentId, from.threadId)),
+ ),
+ ),
+ );
+ };
+ /**
+ * Moves the draft onto a Boat cloud VM's checkout of the same repository,
+ * keeping its model, base branch, attachments and access settings. Cloud
+ * threads always start in a new worktree.
+ */
+ /** What starting this draft on a cloud needs, or why it cannot start. */
+ const boatCloudStart = (
+ draft: NonNullable>,
+ selection: CloudEnvironmentSelection,
+ ) => {
+ const cloud = clouds[selection];
+ if (cloud.holderEnvironmentId === null || !cloud.ready) {
+ return {
+ title: `${cloud.name} is not set up`,
+ description: "Finish setup in Settings, Cloud.",
+ };
+ }
+ const project = allProjects.find(
+ (candidate) =>
+ candidate.environmentId === draft.environmentId && candidate.id === draft.projectId,
+ );
+ // A fork's own remote, where the agent can push, rather than the upstream it groups under.
+ const identity = project?.repositoryIdentity;
+ const repositoryUrl = identity?.origin?.remoteUrl ?? identity?.locator.remoteUrl;
+ if (!repositoryUrl) {
+ return {
+ title: `${cloud.name} needs a git remote`,
+ description: "Push this project to a remote the VM can clone.",
+ };
+ }
+ if (!draft.branch) {
+ return {
+ title: "Choose a base branch",
+ description: `${cloud.name} starts a new worktree from it.`,
+ };
+ }
+ return {
+ holderEnvironmentId: cloud.holderEnvironmentId,
+ repositoryUrl,
+ baseBranch: draft.branch,
+ };
+ };
+ const moveToBoatCloud = async (selection: CloudEnvironmentSelection) => {
+ if (!draftId) return false;
+ const originalDraft = getDraftSession(draftId);
+ if (!originalDraft) return false;
+ const start = boatCloudStart(originalDraft, selection);
+ if ("title" in start) {
+ toastManager.add({ type: "warning", id: "boat-cloud-send", ...start });
+ return false;
+ }
+ const target = await clouds[selection].prepare({ draftId, ...start });
+ if (!target) return false;
+ const currentDraft = getDraftSession(draftId);
+ if (
+ !currentDraft ||
+ currentDraft.promotedTo ||
+ currentDraft.environmentSelection !== selection ||
+ currentDraft.environmentId !== originalDraft.environmentId ||
+ currentDraft.projectId !== originalDraft.projectId
+ ) {
+ // The draft moved on while the VM started; the VM stays ready for the next send.
+ clouds[selection].clear(draftId);
+ return false;
+ }
+ const { project, worktree } = target;
+ const baseBranch = currentDraft.branch ?? originalDraft.branch;
+ // The VM cut the worktree from the base the start asked for; a base picked since needs a new one.
+ const readyWorktree = worktree?.baseBranch === baseBranch ? worktree : null;
+ carryFanoutSelections(originalDraft, project.environmentId);
+ // The send must read the VM project's composer and provider context after retargeting.
+ // Attachments stay on the draft; the send uploads them to the VM it now targets.
+ flushSync(() =>
+ setDraftThreadContext(draftId, {
+ projectRef: scopeProjectRef(project.environmentId, project.id),
+ environmentSelection: selection,
+ loadBalancedEnvironmentId: null,
+ envMode: "worktree",
+ // The thread takes the VM's worktree, or the VM cuts one from the remote base, since its
+ // clone has none of this machine's local branches. A path on this machine means nothing there.
+ ...(readyWorktree === null
+ ? { branch: baseBranch, startFromOrigin: true, worktreePath: null }
+ : { branch: readyWorktree.branch, worktreePath: readyWorktree.path }),
+ }),
+ );
+ // The thread is listed from its first event, before the route moves to it.
+ rememberOpenedBoatCloudThread({
+ environmentId: project.environmentId,
+ threadId: currentDraft.threadId,
+ });
+ return true;
+ };
+ /** The send that followed a move to a cloud went out, so its start is over. */
+ const onRoutedSendDispatched = () => {
+ if (!draftId) return;
+ clearBoatCloudStartProgress(draftId);
+ clearBoxdCloudStartProgress(draftId);
+ };
const refreshBeforeSend = () => {
+ const selection = draftThread?.environmentSelection;
+ if (draftId && isCloudEnvironmentSelection(selection) && !draftThread?.promotedTo) {
+ return moveToBoatCloud(selection);
+ }
if (
!automaticEnvironment ||
!draftId ||
@@ -174,18 +333,7 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
return false;
}
const projectRef = scopeProjectRef(target.environmentId, target.projectId);
- if (originalDraft && target.environmentId !== originalDraft.environmentId) {
- appAtomRegistry.set(
- draftFanoutSelectionsAtom(
- scopedThreadKey(scopeThreadRef(target.environmentId, originalDraft.threadId)),
- ),
- appAtomRegistry.get(
- draftFanoutSelectionsAtom(
- scopedThreadKey(scopeThreadRef(originalDraft.environmentId, originalDraft.threadId)),
- ),
- ),
- );
- }
+ if (originalDraft) carryFanoutSelections(originalDraft, target.environmentId);
// The send must read the target project's composer and provider context after retargeting.
flushSync(() =>
setDraftThreadContext(draftId, {
@@ -242,6 +390,67 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
});
};
const onAutoEnvironmentStable = useStableCallback(onAutoEnvironment);
+ const onCloudEnvironment = () => {
+ if (envLocked || !draftId || sendInFlightRef.current) return;
+ setDraftThreadContext(draftId, {
+ environmentSelection: "cloud",
+ loadBalancedEnvironmentId: null,
+ envMode: "worktree",
+ worktreePath: null,
+ });
+ // The VM starts while the message is written; the send reuses this start.
+ const draft = getDraftSession(draftId);
+ const start = draft ? boatCloudStart(draft, "cloud") : null;
+ if (start && !("title" in start)) prewarmBoatCloudProject({ draftId, ...start });
+ };
+ const onCloudEnvironmentStable = useStableCallback(onCloudEnvironment);
+ const onBoxdEnvironment = () => {
+ if (envLocked || !draftId || sendInFlightRef.current) return;
+ setDraftThreadContext(draftId, {
+ environmentSelection: "boxd",
+ loadBalancedEnvironmentId: null,
+ envMode: "worktree",
+ worktreePath: null,
+ });
+ const draft = getDraftSession(draftId);
+ const start = draft ? boatCloudStart(draft, "boxd") : null;
+ if (start && !("title" in start)) prewarmBoxdCloudProject({ draftId, ...start });
+ };
+ const onBoxdEnvironmentStable = useStableCallback(onBoxdEnvironment);
+ const onLeaveBoxdEnvironment = () => {
+ if (!draftId || sendInFlightRef.current) return;
+ clearBoxdCloudStartProgress(draftId);
+ setDraftThreadContext(draftId, { environmentSelection: "manual" });
+ };
+ const onLeaveBoxdEnvironmentStable = useStableCallback(onLeaveBoxdEnvironment);
+ const onLeaveCloudEnvironment = () => {
+ if (!draftId || sendInFlightRef.current) return;
+ clearBoatCloudStartProgress(draftId);
+ setDraftThreadContext(draftId, { environmentSelection: "manual" });
+ };
+ const onLeaveCloudEnvironmentStable = useStableCallback(onLeaveCloudEnvironment);
+ const cloudSelected = draftThread?.environmentSelection === "cloud";
+ // Offered on a new draft once this machine has Boat cloud ready; kept visible while chosen.
+ const cloudEnvironment =
+ draftId &&
+ !envLocked &&
+ !draftThread?.promotedTo &&
+ (cloudSelected || boatCloudReady(boatCloud.status))
+ ? {
+ selected: cloudSelected,
+ onSelect: onCloudEnvironmentStable,
+ onLeave: onLeaveCloudEnvironmentStable,
+ }
+ : undefined;
+ const boxdSelected = draftThread?.environmentSelection === "boxd";
+ const boxdEnvironment =
+ draftId && !envLocked && !draftThread?.promotedTo && (boxdSelected || clouds.boxd.ready)
+ ? {
+ selected: boxdSelected,
+ onSelect: onBoxdEnvironmentStable,
+ onLeave: onLeaveBoxdEnvironmentStable,
+ }
+ : undefined;
const autoEnvironmentLabel = automaticEnvironment
? draftThread?.loadBalancedEnvironmentId
? "Auto balance"
@@ -381,8 +590,11 @@ export function useDraftEnvironmentRouting(input: DraftEnvironmentRoutingInput)
needsLoadBalancing,
loadBalancing,
refreshBeforeSend,
+ onRoutedSendDispatched,
onAutoEnvironmentStable,
autoEnvironmentLabel,
+ cloudEnvironment,
+ boxdEnvironment,
isEnvironmentChanging,
readPendingEnvironmentChange,
onEnvironmentChangeStable,
diff --git a/apps/web/src/components/chat/useSystemComposerBanners.tsx b/apps/web/src/components/chat/useSystemComposerBanners.tsx
index 65885a931795e..fc2aa3e58661f 100644
--- a/apps/web/src/components/chat/useSystemComposerBanners.tsx
+++ b/apps/web/src/components/chat/useSystemComposerBanners.tsx
@@ -8,7 +8,8 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
-import { WifiOffIcon } from "lucide-react";
+import { MoonIcon, WifiOffIcon } from "lucide-react";
+import type { BoatCloudSleep } from "../../boatCloud";
import { secondTick } from "@t3tools/client-runtime/clock";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { environmentCatalog } from "../../connection/catalog";
@@ -45,6 +46,7 @@ interface SystemComposerBannersInput {
readonly activeEnvironment: EnvironmentPresentation | null;
readonly activeEnvironmentUnavailable: boolean;
readonly activeEnvironmentUnavailableState: EnvironmentUnavailableState | null;
+ readonly boatCloudSleep: BoatCloudSleep | null;
readonly activeThreadEnvironmentId: EnvironmentId | null;
readonly serverConfig: EnvironmentPresentation["serverConfig"] | null;
readonly hasMultipleRegisteredEnvironments: boolean;
@@ -61,6 +63,7 @@ export function useSystemComposerBanners(input: SystemComposerBannersInput) {
activeEnvironment,
activeEnvironmentUnavailable,
activeEnvironmentUnavailableState,
+ boatCloudSleep,
activeThreadEnvironmentId,
serverConfig,
hasMultipleRegisteredEnvironments,
@@ -187,6 +190,17 @@ export function useSystemComposerBanners(input: SystemComposerBannersInput) {
activeEnvironmentUnavailableState !== null &&
unavailableConnection !== null &&
!suppressUnavailableBanner;
+ // A wake lists its steps in the thread, so the banner only marks a VM that is asleep.
+ if (boatCloudSleep?.state === "sleeping" && activeEnvironment !== null) {
+ items.push({
+ id: `boat-cloud-sleep:${activeEnvironment.environmentId}`,
+ variant: "info",
+ group: "environment",
+ icon: ,
+ title: `${activeEnvironment.label} is sleeping`,
+ description: "Send a message to wake it.",
+ });
+ }
if (showUnavailableBanner) {
items.push({
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
diff --git a/apps/web/src/components/settings/BoatCloudSettings.tsx b/apps/web/src/components/settings/BoatCloudSettings.tsx
new file mode 100644
index 0000000000000..1b6d4fd210050
--- /dev/null
+++ b/apps/web/src/components/settings/BoatCloudSettings.tsx
@@ -0,0 +1,428 @@
+import {
+ BOAT_CLOUD_REQUIRED_SCOPES,
+ BOAT_CLOUD_SETUP_STEPS,
+ type BoatCloudEnvironmentAccess,
+ type BoatCloudMachine,
+ type BoatCloudSetup,
+ type BoatCloudSetupStep,
+ type BoatCloudStatus,
+ type EnvironmentId,
+} from "@t3tools/contracts";
+import { CheckIcon, CircleDotIcon, CircleIcon, XIcon } from "lucide-react";
+import { type FormEvent, useState } from "react";
+
+import {
+ boatCloudSnapshotRepositories,
+ useBoatCloudKeyHolderStates,
+ usePrimaryBoatCloudStatus,
+} from "../../boatCloud";
+import { type EnvironmentPresentation, useEnvironments } from "../../state/environments";
+import { serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { BoatIcon } from "../Icons";
+import { BoxdCloudSettingsSections } from "./BoxdCloudSettings";
+import { Badge } from "../ui/badge";
+import { Button } from "../ui/button";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { Switch } from "../ui/switch";
+import { Text } from "../ui/text";
+import { SecretInput } from "./SecretInput";
+import {
+ SettingsNote,
+ SettingsPageContainer,
+ SettingsRow,
+ SettingsRowTile,
+ SettingsSection,
+} from "./settingsLayout";
+import { searchableSetting } from "./settingsSearch";
+
+const STEP_LABELS: Record = {
+ "create-vm": "Create a VM",
+ "install-server": "Install T3 Code and clone repositories",
+ "copy-skills": "Copy this machine's skills",
+ "save-snapshot": "Save the T3 Code snapshot",
+};
+
+const MACHINE_STATE: Record<
+ BoatCloudMachine["state"],
+ { readonly label: string; readonly variant: "success" | "info" | "unavailable" | "warning" }
+> = {
+ running: { label: "Running", variant: "success" },
+ starting: { label: "Starting", variant: "info" },
+ stopped: { label: "Stopped", variant: "unavailable" },
+ gone: { label: "Saved copy", variant: "warning" },
+};
+
+const ACCESS_LABELS: Record = {
+ passGithub: "GitHub access",
+ passSandboxCredentials: "Boat credentials",
+ passSecrets: "Secrets",
+ passAgentsCredentials: "Agent sign-ins",
+};
+const ACCESS_KEYS = Object.keys(ACCESS_LABELS) as ReadonlyArray;
+
+type StepState = "done" | "active" | "failed" | "pending";
+
+function stepState(setup: BoatCloudSetup, index: number): StepState {
+ if (setup.status === "ready") return "done";
+ if (setup.step === null || setup.status === "idle") return "pending";
+ const current = BOAT_CLOUD_SETUP_STEPS.indexOf(setup.step);
+ if (index < current) return "done";
+ if (index > current) return "pending";
+ return setup.status === "failed" ? "failed" : "active";
+}
+
+// Static glyphs: setup takes minutes, and a spinner would repaint the whole time.
+function StepIcon({ state }: { readonly state: StepState }) {
+ if (state === "done") return ;
+ if (state === "failed") return ;
+ if (state === "active")
+ return ;
+ return ;
+}
+
+/** Machines that hand out VMs: every connected one except the VMs themselves. */
+function useKeyHolders(vmEnvironmentIds: ReadonlySet) {
+ const { environments } = useEnvironments();
+ return environments.filter(
+ (environment) =>
+ environment.connection.phase === "connected" &&
+ !environment.boatCloud &&
+ !environment.boxdCloud &&
+ !vmEnvironmentIds.has(environment.environmentId),
+ );
+}
+
+function KeyHolderRow({
+ environment,
+ state,
+}: {
+ readonly environment: EnvironmentPresentation;
+ readonly state: BoatCloudStatus | "unsupported" | null | undefined;
+}) {
+ return (
+ Needs update
+ ) : state?.connected ? (
+ Enabled
+ ) : (
+ Not enabled
+ )
+ }
+ />
+ );
+}
+
+function ApiKeyForm({
+ holders,
+ setupEnvironmentId,
+}: {
+ readonly holders: ReadonlyArray;
+ readonly setupEnvironmentId: EnvironmentId | null;
+}) {
+ const [apiKey, setApiKey] = useState("");
+ const [busy, setBusy] = useState(false);
+ const connect = useAtomCommand(serverEnvironment.connectBoatCloud, "Connect Boat");
+ const runSetup = useAtomCommand(serverEnvironment.runBoatCloudSetup, "Set up Boat cloud");
+ const onSubmit = async (event: FormEvent) => {
+ event.preventDefault();
+ const key = apiKey.trim();
+ if (!key || busy) return;
+ setBusy(true);
+ // Every machine gets the key, so a thread started on any of them can use Boat cloud.
+ const results = await Promise.all(
+ holders.map(async (holder) => ({
+ environmentId: holder.environmentId,
+ result: await connect({ environmentId: holder.environmentId, input: { apiKey: key } }),
+ })),
+ );
+ setBusy(false);
+ if (results.some(({ result }) => result._tag === "Success")) setApiKey("");
+ // Only this machine builds the snapshot, so connected machines never race to save it.
+ const own = results.find(({ environmentId }) => environmentId === setupEnvironmentId);
+ if (own?.result._tag === "Success" && own.result.value.setup.status === "idle") {
+ void runSetup({
+ environmentId: own.environmentId,
+ input: { repositories: boatCloudSnapshotRepositories() },
+ });
+ }
+ };
+ return (
+
+ );
+}
+
+/** The Boat environment new VMs start on, and what it passes to them. Every key holder gets the same choice. */
+function EnvironmentSection({
+ status,
+ holders,
+}: {
+ readonly status: BoatCloudStatus;
+ readonly holders: ReadonlyArray;
+}) {
+ const configure = useAtomCommand(
+ serverEnvironment.configureBoatCloudEnvironment,
+ "Change the Boat environment",
+ );
+ const [busy, setBusy] = useState(false);
+ const selected = status.environments.find(
+ (environment) => environment.name === status.environment,
+ );
+ const apply = async (environmentId: string, access?: BoatCloudEnvironmentAccess) => {
+ setBusy(true);
+ await Promise.all(
+ holders.map((holder) =>
+ configure({
+ environmentId: holder.environmentId,
+ input: { environmentId, ...(access ? { access } : {}) },
+ }),
+ ),
+ );
+ setBusy(false);
+ };
+ return (
+
+ {status.environmentsError !== null ? (
+ {status.environmentsError}
+ ) : (
+ <>
+ {
+ if (typeof value === "string" && value !== selected?.id) void apply(value);
+ }}
+ >
+
+ {selected?.name ?? "Choose"}
+
+
+ {status.environments.map((environment) => (
+
+ {environment.name}
+ {environment.isDefault ? " (default)" : ""}
+
+ ))}
+
+
+ }
+ />
+ {selected
+ ? ACCESS_KEYS.map((key) => (
+
+ void apply(selected.id, {
+ passGithub: selected.passGithub,
+ passSandboxCredentials: selected.passSandboxCredentials,
+ passSecrets: selected.passSecrets,
+ passAgentsCredentials: selected.passAgentsCredentials,
+ [key]: Boolean(checked),
+ })
+ }
+ />
+ }
+ />
+ ))
+ : null}
+
+ New VMs start on this environment and keep it. Running VMs keep theirs.
+
+ >
+ )}
+
+ );
+}
+
+export function BoatCloudSettingsPanel() {
+ const { holderEnvironmentId, status } = usePrimaryBoatCloudStatus();
+ const vmEnvironmentIds = new Set(
+ (status?.machines ?? []).flatMap((machine) =>
+ machine.environmentId === null ? [] : [machine.environmentId],
+ ),
+ );
+ const holderStates = useBoatCloudKeyHolderStates();
+ const machines = useKeyHolders(vmEnvironmentIds);
+ // A machine whose T3 Code predates Boat cloud cannot take the key until it updates.
+ const holders = machines.filter((machine) => {
+ const state = holderStates.get(machine.environmentId);
+ return state !== undefined && state !== "unsupported";
+ });
+ const missingKey = holders.filter((holder) => {
+ const state = holderStates.get(holder.environmentId);
+ return state !== "unsupported" && state?.connected === false;
+ });
+ const runSetup = useAtomCommand(serverEnvironment.runBoatCloudSetup, "Set up Boat cloud");
+ const disconnect = useAtomCommand(serverEnvironment.disconnectBoatCloud, "Disconnect Boat");
+ const connected = status?.connected === true;
+ const setup = status?.setup;
+
+ return (
+
+ }
+ >
+ {status.account ?? "Connected"}
+ ) : (
+ "API key"
+ )
+ }
+ description={connected ? "Connected" : undefined}
+ leading={
+
+
+
+ }
+ control={
+ connected && holderEnvironmentId !== null ? (
+
+ ) : status ? (
+
+ ) : null
+ }
+ />
+ {status && !connected ? (
+
+ The key needs{" "}
+ {BOAT_CLOUD_REQUIRED_SCOPES.map((scope, index) => (
+
+
+ {scope}
+
+ {index < BOAT_CLOUD_REQUIRED_SCOPES.length - 1 ? ", " : "."}
+
+ ))}
+
+ ) : null}
+
+
+ {connected ? : null}
+
+ {connected && setup ? (
+ {
+ if (holderEnvironmentId === null) return;
+ void runSetup({
+ environmentId: holderEnvironmentId,
+ input: { repositories: boatCloudSnapshotRepositories() },
+ });
+ }}
+ >
+ {setup.status === "running"
+ ? "Setting up"
+ : setup.status === "ready"
+ ? "Rebuild snapshot"
+ : setup.status === "failed"
+ ? "Retry"
+ : "Set up"}
+
+ }
+ >
+ {BOAT_CLOUD_SETUP_STEPS.map((step, index) => {
+ const state = stepState(setup, index);
+ return (
+ }
+ description={state === "failed" ? (setup.error ?? undefined) : undefined}
+ />
+ );
+ })}
+
+ ) : null}
+
+ {connected ? (
+
+ {machines.map((machine) => (
+
+ ))}
+ {missingKey.length > 0 ? (
+ }
+ />
+ ) : null}
+
+ ) : null}
+
+ {connected && status.machines.length > 0 ? (
+
+ {status.machines.map((machine) => {
+ const state = MACHINE_STATE[machine.state];
+ return (
+ 0
+ ? machine.repositories
+ .map((repository) => repository.split("/").slice(1).join("/"))
+ .join(", ")
+ : undefined
+ }
+ control={{state.label}}
+ />
+ );
+ })}
+
+ ) : null}
+
+
+
+ );
+}
diff --git a/apps/web/src/components/settings/BoxdCloudSettings.tsx b/apps/web/src/components/settings/BoxdCloudSettings.tsx
new file mode 100644
index 0000000000000..d146b2c247f94
--- /dev/null
+++ b/apps/web/src/components/settings/BoxdCloudSettings.tsx
@@ -0,0 +1,199 @@
+import type { BoatCloudSetup, BoatCloudSetupStep, BoxdCloudMachine } from "@t3tools/contracts";
+import { CheckIcon, CircleDotIcon, CircleIcon, XIcon } from "lucide-react";
+import { type FormEvent, useState } from "react";
+
+import { boatCloudSnapshotRepositories } from "../../boatCloud";
+import { usePrimaryBoxdCloudStatus } from "../../boxdCloud";
+import { serverEnvironment } from "../../state/server";
+import { useAtomCommand } from "../../state/use-atom-command";
+import { BoxdIcon } from "../Icons";
+import { Badge } from "../ui/badge";
+import { Button, InlineButton } from "../ui/button";
+import { SecretInput } from "./SecretInput";
+import { SettingsNote, SettingsRow, SettingsRowTile, SettingsSection } from "./settingsLayout";
+import { searchableSetting } from "./settingsSearch";
+
+const SETUP_STEPS = ["create-vm", "install-server", "save-snapshot"] as const;
+
+const STEP_LABELS: Record<(typeof SETUP_STEPS)[number], string> = {
+ "create-vm": "Create a machine",
+ "install-server": "Install T3 Code and clone repositories",
+ "save-snapshot": "Save the T3 Code snapshot",
+};
+
+const MACHINE_STATE: Record<
+ BoxdCloudMachine["state"],
+ { readonly label: string; readonly variant: "success" | "info" | "unavailable" }
+> = {
+ running: { label: "Running", variant: "success" },
+ asleep: { label: "Asleep", variant: "info" },
+ stopped: { label: "Stopped", variant: "unavailable" },
+};
+
+type StepState = "done" | "active" | "failed" | "pending";
+
+function stepState(setup: BoatCloudSetup, step: BoatCloudSetupStep): StepState {
+ if (setup.status === "ready") return "done";
+ if (setup.step === null || setup.status === "idle") return "pending";
+ const current = SETUP_STEPS.findIndex((candidate) => candidate === setup.step);
+ const index = SETUP_STEPS.findIndex((candidate) => candidate === step);
+ if (index < current) return "done";
+ if (index > current) return "pending";
+ return setup.status === "failed" ? "failed" : "active";
+}
+
+// Static glyphs: setup takes minutes, and a spinner would repaint the whole time.
+function StepIcon({ state }: { readonly state: StepState }) {
+ if (state === "done") return ;
+ if (state === "failed") return ;
+ if (state === "active")
+ return ;
+ return ;
+}
+
+/** boxd cloud on the Cloud settings page. This machine holds the key and hands out machines. */
+export function BoxdCloudSettingsSections() {
+ const { holderEnvironmentId, status } = usePrimaryBoxdCloudStatus();
+ const [apiKey, setApiKey] = useState("");
+ const [busy, setBusy] = useState(false);
+ const connect = useAtomCommand(serverEnvironment.connectBoxdCloud, "Connect boxd");
+ const disconnect = useAtomCommand(serverEnvironment.disconnectBoxdCloud, "Disconnect boxd");
+ const runSetup = useAtomCommand(serverEnvironment.runBoxdCloudSetup, "Set up boxd cloud");
+ if (holderEnvironmentId === null || status === null) return null;
+ const setUp = () =>
+ runSetup({
+ environmentId: holderEnvironmentId,
+ input: { repositories: boatCloudSnapshotRepositories() },
+ });
+ const onSubmit = async (event: FormEvent) => {
+ event.preventDefault();
+ const key = apiKey.trim();
+ if (!key || busy) return;
+ setBusy(true);
+ const result = await connect({ environmentId: holderEnvironmentId, input: { apiKey: key } });
+ setBusy(false);
+ if (result._tag !== "Success") return;
+ setApiKey("");
+ if (result.value.setup.status === "idle") void setUp();
+ };
+ const { connected, setup } = status;
+
+ return (
+ <>
+ }
+ >
+ {status.account ?? "Connected"}
+ ) : (
+ "API key"
+ )
+ }
+ description={connected ? "Connected" : undefined}
+ leading={
+
+
+
+ }
+ control={
+ connected ? (
+
+ ) : (
+
+ )
+ }
+ />
+ {connected ? null : (
+
+ Create a key at{" "}
+ }
+ >
+ app.boxd.sh/keys
+
+ .
+
+ )}
+
+
+ {connected ? (
+ void setUp()}
+ >
+ {setup.status === "running"
+ ? "Setting up"
+ : setup.status === "ready"
+ ? "Rebuild snapshot"
+ : setup.status === "failed"
+ ? "Retry"
+ : "Set up"}
+
+ }
+ >
+ {SETUP_STEPS.map((step) => {
+ const state = stepState(setup, step);
+ return (
+ }
+ description={state === "failed" ? (setup.error ?? undefined) : undefined}
+ />
+ );
+ })}
+
+ ) : null}
+
+ {connected && status.machines.length > 0 ? (
+
+ {status.machines.map((machine) => {
+ const state = MACHINE_STATE[machine.state];
+ return (
+ 0
+ ? machine.repositories
+ .map((repository) => repository.split("/").slice(1).join("/"))
+ .join(", ")
+ : undefined
+ }
+ control={{state.label}}
+ />
+ );
+ })}
+
+ ) : null}
+ >
+ );
+}
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index 31d402813984e..2d831f091133f 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -270,8 +270,12 @@ function ConnectionsSettingsContent({
? (accessSessionState.data.permissions ?? accessSessionState.data.scopes ?? null)
: null;
const currentAuthPolicy = desktopBridge ? null : (accessSessionState.data?.auth.policy ?? null);
+ // Boat cloud VMs come and go with their threads; Settings, Cloud manages them.
const savedEnvironments = environments.filter(
- (environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",
+ (environment) =>
+ environment.entry.target._tag !== "PrimaryConnectionTarget" &&
+ !environment.boatCloud &&
+ !environment.boxdCloud,
);
const listedEnvironments = savedEnvironments.filter(
(environment) => !isDesktopLocalConnectionTarget(environment.entry.target),
diff --git a/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx b/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx
index 78a96ba4ebab4..71aab7b79e95a 100644
--- a/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx
+++ b/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx
@@ -61,6 +61,8 @@ function routesList(routes: ReadonlyArray) {
label: "Desk",
displayUrl: null,
relayManaged: false,
+ boatCloud: false,
+ boxdCloud: false,
entry,
connection: { phase: "available", error: null, traceId: null },
serverConfig: null,
diff --git a/apps/web/src/components/settings/SettingsScopePicker.tsx b/apps/web/src/components/settings/SettingsScopePicker.tsx
index b4dad229e28f7..22c2cdd567cff 100644
--- a/apps/web/src/components/settings/SettingsScopePicker.tsx
+++ b/apps/web/src/components/settings/SettingsScopePicker.tsx
@@ -165,7 +165,9 @@ function ScopePopover({
const visibleEnvironments = environments
.filter(
(environment) =>
- memberEnvironmentIds === null || memberEnvironmentIds.has(environment.environmentId),
+ (memberEnvironmentIds === null || memberEnvironmentIds.has(environment.environmentId)) &&
+ ((!environment.boatCloud && !environment.boxdCloud) ||
+ environment.environmentId === environmentValue),
)
.map((environment) => {
const { primary, secondary } = settingsScopeEnvironmentLabels(environment, environments);
diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx
index fb5fae700d416..337ccee63786f 100644
--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx
+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx
@@ -14,6 +14,7 @@ import {
BotIcon,
ScanIcon,
CalendarClockIcon,
+ CloudIcon,
FileDiffIcon,
FolderTreeIcon,
GitBranchIcon,
@@ -93,6 +94,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/browser": GlobeIcon,
"/settings/devices": SmartphoneIcon,
"/settings/scheduled-tasks": CalendarClockIcon,
+ "/settings/cloud": CloudIcon,
"/settings/source-control": GitBranchIcon,
"/settings/worktrees": FolderTreeIcon,
"/settings/connections": ServerIcon,
diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx
index ad28be78141a1..1c78e348cddd7 100644
--- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx
+++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx
@@ -1248,11 +1248,15 @@ export function VoiceSettingsPanel() {
const order = microphoneOrder(settings);
const selectedMicrophone = preferredMicrophoneId(order, microphones);
- const environmentChoices = environments.map((environment) => ({
+ // Boat VMs are per-thread and stop themselves when idle, so dictation sent to one would fail.
+ const choosableEnvironments = environments.filter(
+ (environment) => !environment.boatCloud && !environment.boxdCloud,
+ );
+ const environmentChoices = choosableEnvironments.map((environment) => ({
environment,
value: JSON.stringify(["environment", environment.environmentId]),
}));
- const cloudGroups = environments
+ const cloudGroups = choosableEnvironments
.filter(
(environment) => environment.serverConfig?.environment.capabilities.cloudVoiceTranscription,
)
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 8af4635fb9da7..9f7c74e3f8631 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -33,6 +33,7 @@ export type SettingsPath =
| "/settings/browser"
| "/settings/devices"
| "/settings/scheduled-tasks"
+ | "/settings/cloud"
| "/settings/source-control"
| "/settings/worktrees"
| "/settings/connections"
@@ -112,6 +113,7 @@ export const SETTINGS_SECTION_LABELS: Readonly> = {
"/settings/browser": msg("Browser"),
"/settings/devices": msg("Devices"),
"/settings/scheduled-tasks": msg("Scheduled tasks"),
+ "/settings/cloud": msg("Cloud"),
"/settings/source-control": msg("Source control"),
"/settings/worktrees": msg("Worktrees"),
"/settings/connections": msg("Environments"),
@@ -152,6 +154,7 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{
"/settings/browser",
"/settings/devices",
"/settings/scheduled-tasks",
+ "/settings/cloud",
],
},
{
@@ -1092,6 +1095,18 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Scheduled tasks",
to: "/settings/scheduled-tasks",
},
+ {
+ id: "boat-cloud",
+ title: "Boat cloud",
+ to: "/settings/cloud",
+ searchTerms: ["cloud agents remote vm sandbox boat.dev api key snapshot"],
+ },
+ {
+ id: "boxd-cloud",
+ title: "boxd cloud",
+ to: "/settings/cloud",
+ searchTerms: ["cloud agents remote vm sandbox boxd.sh api key snapshot"],
+ },
{
id: "agent-browser-access",
title: "Agent browser access",
@@ -1490,6 +1505,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly
environment.environmentId === primaryEnvironmentId ||
environment.environmentId === requested ||
- (environment.entry.enabled && !isDesktopLocalConnectionTarget(environment.entry.target)),
+ (environment.entry.enabled &&
+ !environment.boatCloud &&
+ !environment.boxdCloud &&
+ !isDesktopLocalConnectionTarget(environment.entry.target)),
);
const environmentId = resolveAccessEnvironmentId({
primaryEnvironmentId,
diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts
index d71e523720ea4..ac0b3082e144f 100644
--- a/apps/web/src/composerDraftStore.ts
+++ b/apps/web/src/composerDraftStore.ts
@@ -410,12 +410,24 @@ type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState &
LegacyStickyModelFields &
LegacyV2StoreFields;
+/** "cloud" runs the draft on a Boat cloud VM and "boxd" on a boxd one, picked when it sends. */
+const DRAFT_ENVIRONMENT_SELECTIONS = ["auto", "manual", "cloud", "boxd"] as const;
+export type DraftEnvironmentSelection = (typeof DRAFT_ENVIRONMENT_SELECTIONS)[number];
+export type CloudEnvironmentSelection = Extract;
+
+export function isCloudEnvironmentSelection(
+ selection: DraftEnvironmentSelection | null | undefined,
+): selection is CloudEnvironmentSelection {
+ return selection === "cloud" || selection === "boxd";
+}
+const isDraftEnvironmentSelection = Schema.is(Schema.Literals(DRAFT_ENVIRONMENT_SELECTIONS));
+
const PersistedDraftThreadState = Schema.Struct({
threadId: ThreadId,
environmentId: Schema.String,
projectId: ProjectId,
logicalProjectKey: Schema.optionalKey(Schema.String),
- environmentSelection: Schema.optionalKey(Schema.Literals(["auto", "manual"])),
+ environmentSelection: Schema.optionalKey(Schema.Literals(DRAFT_ENVIRONMENT_SELECTIONS)),
loadBalancedEnvironmentId: Schema.optionalKey(Schema.NullOr(Schema.String)),
createdAt: Schema.String,
runtimeMode: RuntimeMode,
@@ -514,7 +526,7 @@ export interface DraftSessionState {
environmentId: EnvironmentId;
projectId: ProjectId;
logicalProjectKey: string;
- environmentSelection?: "auto" | "manual";
+ environmentSelection?: DraftEnvironmentSelection;
loadBalancedEnvironmentId?: EnvironmentId | null;
createdAt: string;
runtimeMode: RuntimeMode;
@@ -595,7 +607,7 @@ interface ComposerDraftStoreState {
startFromOrigin?: boolean;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
- environmentSelection?: "auto" | "manual";
+ environmentSelection?: DraftEnvironmentSelection;
loadBalancedEnvironmentId?: EnvironmentId | null;
checkoutPullRequest?: DraftCheckoutPullRequest | null;
},
@@ -612,7 +624,7 @@ interface ComposerDraftStoreState {
startFromOrigin?: boolean;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
- environmentSelection?: "auto" | "manual";
+ environmentSelection?: DraftEnvironmentSelection;
loadBalancedEnvironmentId?: EnvironmentId | null;
checkoutPullRequest?: DraftCheckoutPullRequest | null;
},
@@ -628,7 +640,7 @@ interface ComposerDraftStoreState {
startFromOrigin?: boolean;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
- environmentSelection?: "auto" | "manual";
+ environmentSelection?: DraftEnvironmentSelection;
loadBalancedEnvironmentId?: EnvironmentId | null;
checkoutPullRequest?: DraftCheckoutPullRequest | null;
},
@@ -1668,7 +1680,7 @@ function createDraftThreadState(
startFromOrigin?: boolean;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
- environmentSelection?: "auto" | "manual";
+ environmentSelection?: DraftEnvironmentSelection;
loadBalancedEnvironmentId?: EnvironmentId | null;
checkoutPullRequest?: DraftCheckoutPullRequest | null;
},
@@ -1939,8 +1951,7 @@ function normalizePersistedDraftThreads(
worktreePath: normalizedWorktreePath,
envMode: normalizeDraftThreadEnvMode(candidateDraftThread.envMode, normalizedWorktreePath),
startFromOrigin,
- ...(candidateDraftThread.environmentSelection === "manual" ||
- candidateDraftThread.environmentSelection === "auto"
+ ...(isDraftEnvironmentSelection(candidateDraftThread.environmentSelection)
? { environmentSelection: candidateDraftThread.environmentSelection }
: {}),
...(typeof candidateDraftThread.loadBalancedEnvironmentId === "string" &&
@@ -2987,7 +2998,9 @@ const composerDraftStore = create()(
: options.startFromOrigin;
const environmentSelection =
options.environmentSelection ??
- (options.branch != null || options.worktreePath != null
+ // Boat cloud carries the branch over to the VM, so picking one keeps it.
+ ((options.branch != null || options.worktreePath != null) &&
+ !isCloudEnvironmentSelection(existing.environmentSelection)
? "manual"
: existing.environmentSelection);
const checkoutPullRequest = resolveCheckoutPullRequest(
diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts
index 78e4aa19f82fb..6807982405b9c 100644
--- a/apps/web/src/connection/platform.ts
+++ b/apps/web/src/connection/platform.ts
@@ -22,7 +22,11 @@ import {
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
-import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
+import {
+ EnvironmentRpcRequestObserver,
+ EnvironmentRpcUnavailableError,
+ EnvironmentWaker,
+} from "@t3tools/client-runtime/rpc";
import {
AuthStandardClientScopes,
type DesktopBridge,
@@ -836,6 +840,24 @@ const layerRpcRequestObserver = Layer.succeed(
}),
);
+const layerEnvironmentWaker = Layer.succeed(
+ EnvironmentWaker,
+ EnvironmentWaker.of({
+ wakeIfAsleep: Effect.fn("web.connectionPlatform.wakeIfAsleep")(function* (environmentId) {
+ // Imported on use: the Boat cloud module reaches back into the connection runtime.
+ const woken = yield* Effect.promise(() =>
+ import("../boatCloud").then((boatCloud) => boatCloud.wakeBoatCloudIfAsleep(environmentId)),
+ );
+ if (!woken) {
+ return yield* new EnvironmentRpcUnavailableError({
+ environmentId,
+ message: "The Boat cloud machine did not wake up.",
+ });
+ }
+ }),
+ }),
+);
+
type ConnectionPlatformLayerSource =
| typeof ConnectionStorage.layer
| typeof layerConnectivity
@@ -843,7 +865,8 @@ type ConnectionPlatformLayerSource =
| typeof layerCapabilities
| typeof layerPlatformConnectionSource
| typeof layerEnvironmentOwnedDataCleanup
- | typeof layerRpcRequestObserver;
+ | typeof layerRpcRequestObserver
+ | typeof layerEnvironmentWaker;
export const layer: Layer.Layer<
Layer.Success,
@@ -857,4 +880,5 @@ export const layer: Layer.Layer<
layerPlatformConnectionSource,
layerEnvironmentOwnedDataCleanup,
layerRpcRequestObserver,
+ layerEnvironmentWaker,
);
diff --git a/apps/web/src/hooks/useAddProjectTargets.ts b/apps/web/src/hooks/useAddProjectTargets.ts
index 4c63a554e0267..7253936aec66d 100644
--- a/apps/web/src/hooks/useAddProjectTargets.ts
+++ b/apps/web/src/hooks/useAddProjectTargets.ts
@@ -28,6 +28,8 @@ export function useAddProjectTargets(
.filter(
(environment) =>
!hasProject.has(environment.environmentId) &&
+ !environment.boatCloud &&
+ !environment.boxdCloud &&
canClone.has(environment.environmentId) &&
canCreateProjectInEnvironment(environment.connection.phase) &&
environment.serverConfig !== null,
diff --git a/apps/web/src/hooks/useLogicalProjectEnvironments.ts b/apps/web/src/hooks/useLogicalProjectEnvironments.ts
index ebf5fe7a4d2fe..1f83a7a22a79b 100644
--- a/apps/web/src/hooks/useLogicalProjectEnvironments.ts
+++ b/apps/web/src/hooks/useLogicalProjectEnvironments.ts
@@ -32,6 +32,12 @@ export function useLogicalProjectEnvironments(
const envs: EnvironmentOption[] = [];
const pushEnvironment = (environmentId: EnvironmentId, projectId: ProjectId | null) => {
const environment = environmentById.get(environmentId) ?? null;
+ // The Boat and boxd cloud entries stand for every machine; only the one this draft is on shows itself.
+ if (
+ (environment?.boatCloud || environment?.boxdCloud) &&
+ environmentId !== activeProject.environmentId
+ )
+ return;
envs.push({
environmentId,
projectId,
diff --git a/apps/web/src/lib/attachmentUploadQueue.test.ts b/apps/web/src/lib/attachmentUploadQueue.test.ts
index 1b9902336e027..8a831b1e28129 100644
--- a/apps/web/src/lib/attachmentUploadQueue.test.ts
+++ b/apps/web/src/lib/attachmentUploadQueue.test.ts
@@ -689,6 +689,57 @@ describe("attachmentUploadQueue", () => {
},
);
+ it("sends the new machine's copy after a draft moves, and drops the old one", async () => {
+ const draftId = DraftId.make("draft-environment-move");
+ const store = useComposerDraftStore.getState();
+ const file = makeFile("moved");
+ store.addFiles(draftId, [file]);
+ try {
+ store.setProjectDraftThreadId(
+ { environmentId: firstEnvironment, projectId: ProjectId.make("project") },
+ draftId,
+ );
+ startAttachmentUpload({ environmentId: firstEnvironment, image: file, draftTarget: draftId });
+ await Promise.resolve();
+ let settled = awaitAttachmentUploads([file.id]);
+ TestXmlHttpRequest.requests[0]!.complete();
+ await settled;
+
+ // A Boat cloud send retargets the draft, then uploads to the machine it now runs on.
+ store.setProjectDraftThreadId(
+ { environmentId: secondEnvironment, projectId: ProjectId.make("vm-project") },
+ draftId,
+ );
+ startAttachmentUpload({
+ environmentId: secondEnvironment,
+ image: file,
+ draftTarget: draftId,
+ });
+ await Promise.resolve();
+ settled = awaitAttachmentUploads([file.id]);
+ TestXmlHttpRequest.requests[1]!.complete();
+ await settled;
+
+ expect(getUploadedAttachments({ environmentId: secondEnvironment, images: [file] })).toEqual([
+ expect.objectContaining({ id: "pending-environment-2-moved.pdf" }),
+ ]);
+ expect(
+ getUploadedAttachments({ environmentId: firstEnvironment, images: [file] }),
+ ).toBeNull();
+ expect(mocks.runAtomCommand).toHaveBeenCalledWith(
+ expect.anything(),
+ mocks.removeUpload,
+ {
+ environmentId: firstEnvironment,
+ input: { attachmentId: "pending-environment-1-moved.pdf" },
+ },
+ expect.anything(),
+ );
+ } finally {
+ store.clearDraftThread(draftId);
+ }
+ });
+
it("does not let stalled uploads block another environment", async () => {
const images = ["image-a", "image-b", "image-c", "image-d"].map(makeImage);
for (const image of images) {
diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts
index a29eb93ead1d4..a2e2720b57986 100644
--- a/apps/web/src/routeTree.gen.ts
+++ b/apps/web/src/routeTree.gen.ts
@@ -47,6 +47,7 @@ import { Route as ChatSettingsDiffsRouteImport } from './routes/_chat.settings.d
import { Route as ChatSettingsDiagnosticsRouteImport } from './routes/_chat.settings.diagnostics'
import { Route as ChatSettingsDevicesRouteImport } from './routes/_chat.settings.devices'
import { Route as ChatSettingsConnectionsRouteImport } from './routes/_chat.settings.connections'
+import { Route as ChatSettingsCloudRouteImport } from './routes/_chat.settings.cloud'
import { Route as ChatSettingsChatRouteImport } from './routes/_chat.settings.chat'
import { Route as ChatSettingsBrowserRouteImport } from './routes/_chat.settings.browser'
import { Route as ChatSettingsBetaRouteImport } from './routes/_chat.settings.beta'
@@ -251,6 +252,11 @@ const ChatSettingsConnectionsRoute = ChatSettingsConnectionsRouteImport.update({
path: '/connections',
getParentRoute: () => ChatSettingsRoute,
} as any)
+const ChatSettingsCloudRoute = ChatSettingsCloudRouteImport.update({
+ id: '/cloud',
+ path: '/cloud',
+ getParentRoute: () => ChatSettingsRoute,
+} as any)
const ChatSettingsChatRoute = ChatSettingsChatRouteImport.update({
id: '/chat',
path: '/chat',
@@ -323,6 +329,7 @@ export interface FileRoutesByFullPath {
'/settings/beta': typeof ChatSettingsBetaRoute
'/settings/browser': typeof ChatSettingsBrowserRoute
'/settings/chat': typeof ChatSettingsChatRoute
+ '/settings/cloud': typeof ChatSettingsCloudRoute
'/settings/connections': typeof ChatSettingsConnectionsRoute
'/settings/devices': typeof ChatSettingsDevicesRoute
'/settings/diagnostics': typeof ChatSettingsDiagnosticsRoute
@@ -370,6 +377,7 @@ export interface FileRoutesByTo {
'/settings/beta': typeof ChatSettingsBetaRoute
'/settings/browser': typeof ChatSettingsBrowserRoute
'/settings/chat': typeof ChatSettingsChatRoute
+ '/settings/cloud': typeof ChatSettingsCloudRoute
'/settings/connections': typeof ChatSettingsConnectionsRoute
'/settings/devices': typeof ChatSettingsDevicesRoute
'/settings/diagnostics': typeof ChatSettingsDiagnosticsRoute
@@ -420,6 +428,7 @@ export interface FileRoutesById {
'/_chat/settings/beta': typeof ChatSettingsBetaRoute
'/_chat/settings/browser': typeof ChatSettingsBrowserRoute
'/_chat/settings/chat': typeof ChatSettingsChatRoute
+ '/_chat/settings/cloud': typeof ChatSettingsCloudRoute
'/_chat/settings/connections': typeof ChatSettingsConnectionsRoute
'/_chat/settings/devices': typeof ChatSettingsDevicesRoute
'/_chat/settings/diagnostics': typeof ChatSettingsDiagnosticsRoute
@@ -470,6 +479,7 @@ export interface FileRouteTypes {
| '/settings/beta'
| '/settings/browser'
| '/settings/chat'
+ | '/settings/cloud'
| '/settings/connections'
| '/settings/devices'
| '/settings/diagnostics'
@@ -517,6 +527,7 @@ export interface FileRouteTypes {
| '/settings/beta'
| '/settings/browser'
| '/settings/chat'
+ | '/settings/cloud'
| '/settings/connections'
| '/settings/devices'
| '/settings/diagnostics'
@@ -566,6 +577,7 @@ export interface FileRouteTypes {
| '/_chat/settings/beta'
| '/_chat/settings/browser'
| '/_chat/settings/chat'
+ | '/_chat/settings/cloud'
| '/_chat/settings/connections'
| '/_chat/settings/devices'
| '/_chat/settings/diagnostics'
@@ -871,6 +883,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ChatSettingsConnectionsRouteImport
parentRoute: typeof ChatSettingsRoute
}
+ '/_chat/settings/cloud': {
+ id: '/_chat/settings/cloud'
+ path: '/cloud'
+ fullPath: '/settings/cloud'
+ preLoaderRoute: typeof ChatSettingsCloudRouteImport
+ parentRoute: typeof ChatSettingsRoute
+ }
'/_chat/settings/chat': {
id: '/_chat/settings/chat'
path: '/chat'
@@ -945,6 +964,7 @@ interface ChatSettingsRouteChildren {
ChatSettingsBetaRoute: typeof ChatSettingsBetaRoute
ChatSettingsBrowserRoute: typeof ChatSettingsBrowserRoute
ChatSettingsChatRoute: typeof ChatSettingsChatRoute
+ ChatSettingsCloudRoute: typeof ChatSettingsCloudRoute
ChatSettingsConnectionsRoute: typeof ChatSettingsConnectionsRoute
ChatSettingsDevicesRoute: typeof ChatSettingsDevicesRoute
ChatSettingsDiagnosticsRoute: typeof ChatSettingsDiagnosticsRoute
@@ -976,6 +996,7 @@ const ChatSettingsRouteChildren: ChatSettingsRouteChildren = {
ChatSettingsBetaRoute: ChatSettingsBetaRoute,
ChatSettingsBrowserRoute: ChatSettingsBrowserRoute,
ChatSettingsChatRoute: ChatSettingsChatRoute,
+ ChatSettingsCloudRoute: ChatSettingsCloudRoute,
ChatSettingsConnectionsRoute: ChatSettingsConnectionsRoute,
ChatSettingsDevicesRoute: ChatSettingsDevicesRoute,
ChatSettingsDiagnosticsRoute: ChatSettingsDiagnosticsRoute,
diff --git a/apps/web/src/routes/_chat.settings.cloud.tsx b/apps/web/src/routes/_chat.settings.cloud.tsx
new file mode 100644
index 0000000000000..6044245800399
--- /dev/null
+++ b/apps/web/src/routes/_chat.settings.cloud.tsx
@@ -0,0 +1,6 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { BoatCloudSettingsPanel } from "../components/settings/BoatCloudSettings";
+
+export const Route = createFileRoute("/_chat/settings/cloud")({
+ component: BoatCloudSettingsPanel,
+});
diff --git a/apps/web/src/state/boatCloudThreads.ts b/apps/web/src/state/boatCloudThreads.ts
new file mode 100644
index 0000000000000..087297d5b3d13
--- /dev/null
+++ b/apps/web/src/state/boatCloudThreads.ts
@@ -0,0 +1,74 @@
+import { useAtomValue } from "@effect/atom-react";
+import { createBoatCloudThreadListAtoms } from "@t3tools/client-runtime/state/threads";
+import { ScopedThreadRef, type ThreadId } from "@t3tools/contracts";
+import * as Schema from "effect/Schema";
+import { Atom } from "effect/reactivity";
+import { useEffect } from "react";
+
+import { environmentCatalog } from "../connection/catalog";
+import { getLocalStorageItem, setLocalStorageItem } from "../hooks/useLocalStorage";
+import { appAtomRegistry } from "../rpc/atomRegistry";
+
+const STORAGE_KEY = "t3code:boat-cloud-opened-threads";
+const MAX_REMEMBERED = 500;
+const OpenedThreads = Schema.Array(ScopedThreadRef);
+
+function readStored(): ReadonlyArray {
+ try {
+ return getLocalStorageItem(STORAGE_KEY, OpenedThreads) ?? [];
+ } catch {
+ return [];
+ }
+}
+
+/** Boat cloud VM threads this browser started or opened, the only VM threads its lists show. */
+const openedThreadsAtom = Atom.make(readStored()).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("boat-cloud-opened-threads"),
+);
+
+export const boatCloudThreadList = createBoatCloudThreadListAtoms({
+ catalogValueAtom: environmentCatalog.catalogValueAtom,
+ openedThreadsAtom,
+});
+
+/** Call only with a thread on a Boat cloud VM. */
+export function rememberOpenedBoatCloudThread(ref: ScopedThreadRef): void {
+ const same = (other: ScopedThreadRef) =>
+ other.environmentId === ref.environmentId && other.threadId === ref.threadId;
+ if (appAtomRegistry.get(openedThreadsAtom).some(same)) return;
+ // Re-read storage so another tab's threads survive this write.
+ const next = [...readStored().filter((other) => !same(other)), ref].slice(-MAX_REMEMBERED);
+ appAtomRegistry.set(openedThreadsAtom, next);
+ try {
+ setLocalStorageItem(STORAGE_KEY, next, OpenedThreads);
+ } catch {
+ // The list still holds for this session.
+ }
+}
+
+const NO_LISTED_THREADS_ATOM = Atom.make | null>(null).pipe(
+ Atom.withLabel("boat-cloud-listed-thread-ids:none"),
+);
+
+/**
+ * Lists a VM thread here once a route opens it. True until then: the thread reads as hidden
+ * for that render, and the route must not send the visit home for it.
+ */
+export function useOpenBoatCloudThread(ref: ScopedThreadRef | null): boolean {
+ const environmentId = ref?.environmentId ?? null;
+ const threadId = ref?.threadId ?? null;
+ const listed = useAtomValue(
+ environmentId === null
+ ? NO_LISTED_THREADS_ATOM
+ : boatCloudThreadList.listedThreadIdsAtom(environmentId),
+ );
+ const unlisted = listed !== null && threadId !== null && !listed.has(threadId);
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records the visit in browser storage, outside React
+ useEffect(() => {
+ if (unlisted && environmentId !== null && threadId !== null) {
+ rememberOpenedBoatCloudThread({ environmentId, threadId });
+ }
+ }, [unlisted, environmentId, threadId]);
+ return unlisted;
+}
diff --git a/apps/web/src/state/environments.ts b/apps/web/src/state/environments.ts
index 0b2cab287d223..2140ac362a502 100644
--- a/apps/web/src/state/environments.ts
+++ b/apps/web/src/state/environments.ts
@@ -5,7 +5,11 @@ import {
type EnvironmentPresentation as BaseEnvironmentPresentation,
} from "@t3tools/client-runtime/connection";
import { Discovery } from "@t3tools/client-runtime/relay";
-import type { EnvironmentId } from "@t3tools/contracts";
+import {
+ type EnvironmentId,
+ isBoatCloudHttpBaseUrl,
+ isBoxdCloudHttpBaseUrl,
+} from "@t3tools/contracts";
import * as Option from "effect/Option";
import { environmentCatalog } from "../connection/catalog";
@@ -24,18 +28,37 @@ export interface EnvironmentPresentation extends BaseEnvironmentPresentation {
readonly label: string;
readonly displayUrl: string | null;
readonly relayManaged: boolean;
+ /**
+ * A Boat cloud VM. Lists of machines leave these out, since the one Boat
+ * cloud entry stands for all of them, and they all go by that name.
+ */
+ readonly boatCloud: boolean;
+ /** A boxd cloud machine, listed the same way as a Boat cloud VM. */
+ readonly boxdCloud: boolean;
}
+export const BOAT_CLOUD_LABEL = "Boat cloud";
+export const BOXD_CLOUD_LABEL = "boxd cloud";
+
function projectEnvironmentPresentation(
environmentId: EnvironmentId,
presentation: BaseEnvironmentPresentation,
): EnvironmentPresentation {
+ const displayUrl = connectionCatalogDisplayUrl(presentation.entry);
+ const boatCloud = isBoatCloudHttpBaseUrl(displayUrl);
+ const boxdCloud = isBoxdCloudHttpBaseUrl(displayUrl);
return {
...presentation,
environmentId,
- label: presentation.entry.target.label,
- displayUrl: connectionCatalogDisplayUrl(presentation.entry),
+ label: boatCloud
+ ? BOAT_CLOUD_LABEL
+ : boxdCloud
+ ? BOXD_CLOUD_LABEL
+ : presentation.entry.target.label,
+ displayUrl,
relayManaged: hasRelayRoute(presentation.entry),
+ boatCloud,
+ boxdCloud,
};
}
diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts
index 53f26accd44be..5ec7f6d998ba6 100644
--- a/apps/web/src/state/threads.ts
+++ b/apps/web/src/state/threads.ts
@@ -18,6 +18,7 @@ import { AsyncResult, Atom } from "effect/reactivity";
import { environmentCatalog } from "../connection/catalog";
import { connectionAtomRuntime } from "../connection/runtime";
+import { boatCloudThreadList } from "./boatCloudThreads";
import { serverEnvironment } from "./server";
import { environmentShell } from "./shell";
@@ -40,6 +41,7 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({
catalogValueAtom: environmentCatalog.catalogValueAtom,
snapshotAtom: threadEnvironment.snapshotAtom,
hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
+ listedThreadIdsAtom: boatCloudThreadList.listedThreadIdsAtom,
});
export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({
childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
diff --git a/docs/README.md b/docs/README.md
index 264d509d97642..c4aad341bab0a 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -23,6 +23,8 @@
- [Product usage data](./user/telemetry.md)
- [Remote access](./user/remote-access.md)
- [Guest links](./user/guest-links.md)
+- [Boat cloud](./user/boat-cloud.md)
+- [boxd cloud](./user/boxd-cloud.md)
- [T3 Connect troubleshooting](./user/t3-connect-troubleshooting.md)
- [Outside agents (MCP)](./user/outside-agents.md)
- [Running in the background](./user/background-service.md)
diff --git a/docs/user/boat-cloud.md b/docs/user/boat-cloud.md
new file mode 100644
index 0000000000000..de3294b8cb693
--- /dev/null
+++ b/docs/user/boat-cloud.md
@@ -0,0 +1,53 @@
+# Boat cloud
+
+Boat cloud runs threads on [Boat](https://boat.dev) VMs instead of your machine. Each VM runs its own
+T3 Code server, so a cloud thread works like any other thread: it streams, keeps its history, and
+you can follow it from any client.
+
+## Set it up
+
+1. Create a Boat API key with these scopes: `sandbox.create`, `sandbox.read`, `sandbox.update`,
+ `sandbox.stop`, `sandbox.resume`, `sandbox.delete`, `exec`, `file.read`, `file.write`, `host`,
+ `ssh`, `snapshot.read`, `snapshot.write`, `account.read`, `account.admin`, `environment.read`,
+ `environment.write`. `account.admin` lets T3 Code see which agent sign-ins you added, never
+ their values.
+2. Open **Settings → Cloud**, paste the key, and choose **Connect**. The key is saved on every
+ connected machine. The mobile app also keeps it on the phone, so the phone can start cloud
+ threads with no machine connected.
+3. Choose **Set up**. T3 Code creates a VM, installs the T3 Code server so it starts on boot,
+ copies your machine's skills, and saves a Boat snapshot named `t3-code`. Every cloud VM starts
+ from it. Choose **Rebuild snapshot** after you change your skills or update T3 Code. A phone
+ with no machine connected installs the latest T3 Code release and copies no skills.
+4. Under **Environment**, choose the Boat environment new VMs start on. It starts on Boat's default.
+ Its switches choose what VMs get: GitHub access, Boat credentials, secrets, and agent sign-ins.
+ Connect GitHub and add agent sign-ins in the Boat dashboard. Without GitHub access, private
+ repositories fail to clone. A VM keeps the environment it started on, even after it stops, so a
+ new choice only applies to new VMs.
+
+## Start a cloud thread
+
+In a new thread, open the machine picker and choose **Boat cloud**, or use the command palette:
+**New Boat cloud thread** on web and desktop, **Run on Boat cloud** on mobile. Nothing starts until
+you send the first message. Then the app lists each step as it runs: finding a VM, starting T3 Code,
+cloning or updating the repository, connecting, opening the project, and starting the thread, which
+lives on the VM from then on. T3 Code reuses a running VM that is under half its CPU
+and memory, preferring one that already has the repository, or starts a new VM from the snapshot. A
+VM from the snapshot is usually ready in under 10 seconds.
+
+A cloud thread always works in a new worktree, so several threads can share a VM. You choose only
+the base branch. The thread keeps your model and access settings, and its attachments go with it.
+
+The project needs a pushed Git remote: the VM clones it, so local-only branches and commits are not
+there. When an agent finishes, it commits and pushes its branch. It opens a pull request only when
+you ask. Providers on a VM use the agent sign-ins from its Boat environment, so a cloud thread
+only offers the providers those sign-ins cover.
+
+## When VMs stop
+
+A VM turns off once none of its threads has run a turn for 10 minutes. A connected machine
+holding the key stops it a minute early and first saves a copy of the VM's threads, provider sessions, and checkouts. A thread on a stopped
+VM shows it as sleeping. Your next message turns the same VM back on and the thread continues. If
+Boat deleted the VM, a new one starts from the saved copy. A phone keeps no copy, so it can only
+turn back on a VM that Boat still has. **Settings → Cloud** lists each VM, its
+repositories, and whether it is running. Cloud VMs are not listed under **Settings →
+Environments**.
diff --git a/docs/user/boxd-cloud.md b/docs/user/boxd-cloud.md
new file mode 100644
index 0000000000000..b4194b20372a0
--- /dev/null
+++ b/docs/user/boxd-cloud.md
@@ -0,0 +1,33 @@
+# boxd cloud
+
+boxd cloud runs threads on [boxd](https://boxd.sh) machines instead of your machine. It works like
+[Boat cloud](boat-cloud.md): each machine runs its own T3 Code server, and a cloud thread streams,
+keeps its history, and can be followed from any client. You can turn on Boat, boxd, both, or
+neither.
+
+## Set it up
+
+1. Create an API key at [app.boxd.sh/keys](https://app.boxd.sh/keys).
+2. Open **Settings → Cloud**, paste the key under **boxd**, and choose **Connect**. The key stays
+ on the machine you are connected to. The mobile app gives it to a connected machine and never
+ keeps it on the phone.
+3. Setup then starts by itself. T3 Code creates a machine, installs the T3 Code server, clones your
+ most used repositories, and saves a boxd snapshot named `t3-code-`. Choose **Rebuild
+ snapshot** after you update T3 Code.
+
+## Start a cloud thread
+
+In a new thread, open the machine picker and choose **boxd cloud**, or use the command palette:
+**New boxd cloud thread** on web and desktop, **Run on boxd cloud** on mobile. On web and desktop,
+picking it starts a machine right away, so it is usually ready before you send. On mobile it starts
+when you send.
+
+T3 Code keeps one spare machine asleep with T3 Code already running. A start takes it and your
+client connects in about a second. A new spare is prepared in the background for the next start.
+Machines go to sleep after 15 minutes without traffic and wake when a client connects.
+
+## Things to know
+
+- boxd machines come with Claude Code and Codex installed, but T3 Code does not sign them in yet.
+ A machine's agents need signing in before a thread on it can run.
+- Private repositories need GitHub access on the machine. Public ones clone as is.
diff --git a/packages/client-runtime/src/connection/onboarding.test.ts b/packages/client-runtime/src/connection/onboarding.test.ts
index 2131507e547f7..8dcf713ce9cd2 100644
--- a/packages/client-runtime/src/connection/onboarding.test.ts
+++ b/packages/client-runtime/src/connection/onboarding.test.ts
@@ -25,6 +25,7 @@ import {
import * as Connectivity from "./connectivity.ts";
import * as ConnectionCredentialStore from "./credentialStore.ts";
import * as ConnectionDriver from "./driver.ts";
+import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
import {
BearerConnectionTarget,
ConnectionBlockedError,
@@ -61,10 +62,15 @@ function layerPairingHttp(
readonly selfUpdate?: boolean;
readonly grantScopes?: ReadonlyArray;
readonly exchangeGate?: { readonly reached: () => void; readonly release: Promise };
+ readonly descriptorAnswersAfterExchange?: boolean;
},
) {
const grantScopes = options?.grantScopes ?? AuthStandardClientScopes;
let sessionScopes: ReadonlyArray = [];
+ let exchangeRequested: () => void = () => undefined;
+ const exchangeSeen = new Promise((resolve) => {
+ exchangeRequested = resolve;
+ });
const fetchFn = ((input, init = {}) => {
const url = String(input);
calls.push({ url, init });
@@ -75,7 +81,8 @@ function layerPairingHttp(
Response.json({ message: "descriptor unavailable" }, { status: 503 }),
);
}
- return Promise.resolve(
+ const answered = options?.descriptorAnswersAfterExchange === true ? exchangeSeen : undefined;
+ return Promise.resolve(answered).then(() =>
Response.json({
environmentId: "environment-paired",
label: "Paired environment",
@@ -94,6 +101,7 @@ function layerPairingHttp(
}
if (url.endsWith("/oauth/token")) {
+ exchangeRequested();
if (options?.failExchange === true) {
return Promise.resolve(
Response.json(
@@ -162,8 +170,24 @@ function layerPairingHttp(
function layerPairingOnboarding(
options?: Parameters[1],
calls: Array<{ readonly url: string; readonly init: RequestInit }> = [],
+ rememberedDescriptors: Array<{
+ readonly httpBaseUrl: string;
+ readonly environmentId?: string;
+ }> = [],
) {
const dependencies = Layer.mergeAll(
+ Layer.mock(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization)({
+ rememberCheckedDescriptor: (httpBaseUrl, descriptor) =>
+ Effect.sync(() => {
+ rememberedDescriptors.push({
+ httpBaseUrl,
+ ...Option.match(descriptor, {
+ onNone: () => ({}),
+ onSome: (value) => ({ environmentId: value.environmentId }),
+ }),
+ });
+ }),
+ }),
layerClientPresentation,
layerPairingHttp(calls, options),
Layer.mock(Persistence.ConnectionTargetStore)({
@@ -238,10 +262,12 @@ describe("connection onboarding", () => {
it.effect("prepares a persisted bearer registration from pairing details", () =>
Effect.gen(function* () {
const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
+ const remembered: Array<{ readonly httpBaseUrl: string; readonly environmentId?: string }> =
+ [];
const registration = yield* preparePairingRegistration({
host: "remote.example.test",
pairingCode: "pairing-token",
- }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls)));
+ }).pipe(Effect.provide(layerPairingOnboarding(undefined, calls, remembered)));
expect(registration).toMatchObject({
_tag: "BearerConnectionRegistration",
@@ -265,6 +291,10 @@ describe("connection onboarding", () => {
"https://remote.example.test/.well-known/t3/environment",
"https://remote.example.test/oauth/token",
]);
+ // The first connect reuses this read instead of fetching the descriptor again.
+ expect(remembered).toEqual([
+ { httpBaseUrl: "https://remote.example.test/", environmentId: "environment-paired" },
+ ]);
const tokenRequest = calls.find((call) => call.url.endsWith("/oauth/token"));
const tokenBody =
@@ -536,6 +566,24 @@ describe("connection onboarding", () => {
}),
);
+ it.effect("redeems a code minted for the expected machine while its descriptor is read", () =>
+ Effect.gen(function* () {
+ const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
+ const registration = yield* preparePairingRegistration({
+ ...PAIRING_INPUT,
+ expectedEnvironmentId: PAIRED_ENVIRONMENT_ID,
+ codeIsForExpectedEnvironment: true,
+ }).pipe(
+ Effect.provide(layerPairingOnboarding({ descriptorAnswersAfterExchange: true }, calls)),
+ );
+ expect(registration.credential).toMatchObject({ token: "bearer-token" });
+ expect(calls.map((call) => call.url)).toEqual([
+ "https://remote.example.test/.well-known/t3/environment",
+ "https://remote.example.test/oauth/token",
+ ]);
+ }),
+ );
+
it.effect("refuses an outdated server that cannot update itself", () =>
Effect.gen(function* () {
const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
diff --git a/packages/client-runtime/src/connection/onboarding.ts b/packages/client-runtime/src/connection/onboarding.ts
index 48e8b614c67c8..b008c5d894fc9 100644
--- a/packages/client-runtime/src/connection/onboarding.ts
+++ b/packages/client-runtime/src/connection/onboarding.ts
@@ -9,6 +9,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef";
import * as HttpClient from "effect/http/HttpClient";
import { bootstrapRemoteBearerSession } from "../authorization/remote.ts";
+import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
import { deriveWsBaseUrl, normalizeHttpBaseUrl } from "../environment/endpoint.ts";
import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
import * as ClientCapabilities from "../platform/capabilities.ts";
@@ -32,13 +33,18 @@ import {
import * as Persistence from "../platform/persistence.ts";
import * as EnvironmentRegistry from "./registry.ts";
import { orchestrationProtocolCompatibilityError } from "./compatibility.ts";
-import { connectionRoutes, routeEntry, sshTargetKey } from "./routes.ts";
+import { connectionRoutes, routeEntry, routeKeepsItsHost, sshTargetKey } from "./routes.ts";
export interface PairingConnectionInput {
readonly pairingUrl?: string;
readonly host?: string;
readonly pairingCode?: string;
readonly expectedEnvironmentId?: EnvironmentId;
+ /**
+ * The code was minted on the expected machine for this client, as a Boat holder does,
+ * so it is redeemed while the descriptor is read instead of after.
+ */
+ readonly codeIsForExpectedEnvironment?: boolean;
}
export interface SshConnectionInput {
@@ -103,10 +109,20 @@ export const preparePairingRegistration = Effect.fn(
)(function* (input: PairingConnectionInput) {
const target = yield* resolvePairingTarget(input);
const presentation = yield* ClientCapabilities.ClientPresentation;
- const descriptor = yield* fetchRemoteEnvironmentDescriptor({
+ const redeem = bootstrapRemoteBearerSession({
+ httpBaseUrl: target.httpBaseUrl,
+ credential: target.credential,
+ clientMetadata: presentation.metadata,
+ }).pipe(Effect.mapError(mapRemoteEnvironmentError));
+ const readDescriptor = fetchRemoteEnvironmentDescriptor({
httpBaseUrl: target.httpBaseUrl,
}).pipe(Effect.mapError(mapRemoteEnvironmentError));
- // Checked before redeeming the one-time code, so a wrong link is not spent.
+ const early =
+ input.codeIsForExpectedEnvironment === true && input.expectedEnvironmentId !== undefined
+ ? yield* Effect.all([readDescriptor, redeem], { concurrency: 2 })
+ : null;
+ const descriptor = early?.[0] ?? (yield* readDescriptor);
+ // Otherwise checked before redeeming the one-time code, so a wrong link is not spent.
if (
input.expectedEnvironmentId !== undefined &&
descriptor.environmentId !== input.expectedEnvironmentId
@@ -138,11 +154,14 @@ export const preparePairingRegistration = Effect.fn(
if (compatibilityError !== null && compatibilityError.serverUpdateRequired !== true) {
return yield* compatibilityError;
}
- const access = yield* bootstrapRemoteBearerSession({
- httpBaseUrl: target.httpBaseUrl,
- credential: target.credential,
- clientMetadata: presentation.metadata,
- }).pipe(Effect.mapError(mapRemoteEnvironmentError));
+ const access = early?.[1] ?? (yield* redeem);
+ // The connect that follows registration skips its own descriptor read.
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
+ yield* remote.rememberCheckedDescriptor(
+ target.httpBaseUrl,
+ Option.some(descriptor),
+ routeKeepsItsHost({ target: route.target, profile: Option.some(route.profile) }),
+ );
return new BearerConnectionRegistration({
...route,
@@ -304,6 +323,7 @@ export const make = Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
+ const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
// Provisioning retains the delegated onboarding operation spans.
return ConnectionOnboarding.of({
@@ -314,6 +334,7 @@ export const make = Effect.gen(function* () {
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, registry),
Effect.provideService(ClientCapabilities.ClientPresentation, presentation),
Effect.provideService(HttpClient.HttpClient, httpClient),
+ Effect.provideService(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
),
registerSsh: Effect.fnUntraced(
function* (input) {
diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts
index fc07c357b448f..7b172d856696b 100644
--- a/packages/client-runtime/src/rpc/client.ts
+++ b/packages/client-runtime/src/rpc/client.ts
@@ -45,6 +45,20 @@ export class EnvironmentRpcRequestObserver extends Context.Reference<{
}),
}) {}
+/**
+ * Turns an environment that stopped by itself back on before a command runs there, so an
+ * action on a sleeping Boat cloud VM wakes it rather than failing. Reads never wake one.
+ */
+export class EnvironmentWaker extends Context.Reference<{
+ readonly wakeIfAsleep: (
+ environmentId: EnvironmentId,
+ ) => Effect.Effect;
+}>("@t3tools/client-runtime/rpc/EnvironmentWaker", {
+ defaultValue: () => ({
+ wakeIfAsleep: () => Effect.void,
+ }),
+}) {}
+
export type EnvironmentRpcTag = keyof WsRpcProtocolClient & string;
type RpcMethod = WsRpcProtocolClient[TTag];
@@ -60,6 +74,8 @@ export type EnvironmentSubscriptionRpcTag =
| typeof WS_METHODS.subscribeServerConfig
| typeof WS_METHODS.subscribeServerLifecycle
| typeof WS_METHODS.scheduledTasksSubscribe
+ | typeof WS_METHODS.boatCloudSubscribe
+ | typeof WS_METHODS.boxdCloudSubscribe
| typeof WS_METHODS.serverGetStorageCleanupReport
| typeof WS_METHODS.serverGetDatabaseStorage
| typeof WS_METHODS.subscribeTerminalMetadata
diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts
index 63f00b28fb173..4925d6e510515 100644
--- a/packages/client-runtime/src/state/runtime.test.ts
+++ b/packages/client-runtime/src/state/runtime.test.ts
@@ -44,7 +44,7 @@ import {
} from "../connection/model.ts";
import * as EnvironmentRegistry from "../connection/registry.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
-import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
+import { EnvironmentRpcUnavailableError, EnvironmentWaker } from "../rpc/client.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import type * as RpcSession from "../rpc/session.ts";
import { createOrchestrationEnvironmentAtoms } from "./orchestration.ts";
@@ -56,6 +56,7 @@ import type { EnvironmentShellState } from "./shell.ts";
import { createTerminalEnvironmentAtoms } from "./terminal.ts";
import {
createAtomCommandScheduler,
+ createEnvironmentCommand,
createEnvironmentQueryAtomFamily,
createEnvironmentRpcSubscriptionAtomFamily,
selectEnvironmentQueryData,
@@ -1410,6 +1411,58 @@ describe("executeAtomQuery", () => {
});
describe("runtime command runner", () => {
+ it("wakes the environment before an environment command runs, and stops if it stays asleep", async () => {
+ const events: string[] = [];
+ const asleep = EnvironmentId.make("asleep-environment");
+ const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
+ _environmentId,
+ effect,
+ ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, {} as never);
+ const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
+ run,
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
+ const runtime = Atom.runtime(
+ Layer.mergeAll(
+ Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
+ Layer.succeed(EnvironmentWaker, {
+ wakeIfAsleep: (environmentId) =>
+ Effect.sync(() => events.push(`wake:${environmentId}`)).pipe(
+ Effect.andThen(
+ environmentId === asleep
+ ? Effect.fail(
+ new EnvironmentRpcUnavailableError({
+ environmentId,
+ message: "Still asleep.",
+ }),
+ )
+ : Effect.void,
+ ),
+ ),
+ }),
+ ),
+ );
+ const command = createEnvironmentCommand(runtime, {
+ label: "test.environment-command",
+ execute: (_input: undefined, _registry, environmentId) =>
+ Effect.sync(() => events.push(`run:${environmentId}`)),
+ });
+ const registry = AtomRegistry.make();
+
+ const woken = await command.run(registry, {
+ environmentId: QUERY_ENVIRONMENT.environmentId,
+ input: undefined,
+ });
+ expect(woken._tag).toBe("Success");
+ const stillAsleep = await command.run(registry, { environmentId: asleep, input: undefined });
+ expect(stillAsleep._tag).toBe("Failure");
+ expect(events).toEqual([
+ "wake:query-environment",
+ "run:query-environment",
+ "wake:asleep-environment",
+ ]);
+ registry.dispose();
+ });
+
it("settles generated command scheduler defects from direct callers", async () => {
const defect = new Error("invalid command key");
const runtime = Atom.runtime(Layer.empty);
diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts
index 736b10fdeeaca..3585df25f04ad 100644
--- a/packages/client-runtime/src/state/runtime.ts
+++ b/packages/client-runtime/src/state/runtime.ts
@@ -28,6 +28,7 @@ import {
type EnvironmentSubscriptionRpcTag,
type EnvironmentUnaryRpcTag,
EnvironmentRpcUnavailableError,
+ EnvironmentWaker,
request,
requestGuarded,
RpcPermissionGuard,
@@ -933,9 +934,14 @@ export function createEnvironmentCommand(
...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
execute: (target, registry) =>
- runInEnvironment(
- target.environmentId,
- options.execute(target.input, registry, target.environmentId),
+ EnvironmentWaker.pipe(
+ Effect.flatMap((waker) => waker.wakeIfAsleep(target.environmentId)),
+ Effect.andThen(
+ runInEnvironment(
+ target.environmentId,
+ options.execute(target.input, registry, target.environmentId),
+ ),
+ ),
),
});
}
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index 4de38cd5a4543..8b8d168548627 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -1499,6 +1499,14 @@ export function createServerEnvironmentAtoms(
label: "environment-data:server:scheduled-tasks:live",
tag: WS_METHODS.scheduledTasksSubscribe,
}),
+ boatCloudStatus: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
+ label: "environment-data:server:boat-cloud:status",
+ tag: WS_METHODS.boatCloudSubscribe,
+ }),
+ boxdCloudStatus: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
+ label: "environment-data:server:boxd-cloud:status",
+ tag: WS_METHODS.boxdCloudSubscribe,
+ }),
// A cold transcript scan is measured in seconds, so keep the result around
// long enough that switching windows or re-rendering does not rescan. With
// nothing to show yet, the server's last scan answers first, then a plain
@@ -1758,6 +1766,54 @@ export function createServerEnvironmentAtoms(
label: "environment-data:server:signal-process",
tag: WS_METHODS.serverSignalProcess,
}),
+ connectBoatCloud: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boat-cloud:connect",
+ tag: WS_METHODS.boatCloudConnect,
+ }),
+ disconnectBoatCloud: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boat-cloud:disconnect",
+ tag: WS_METHODS.boatCloudDisconnect,
+ }),
+ runBoatCloudSetup: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boat-cloud:run-setup",
+ tag: WS_METHODS.boatCloudRunSetup,
+ concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
+ }),
+ configureBoatCloudEnvironment: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boat-cloud:configure-environment",
+ tag: WS_METHODS.boatCloudConfigureEnvironment,
+ }),
+ acquireBoatCloud: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boat-cloud:acquire",
+ tag: WS_METHODS.boatCloudAcquire,
+ }),
+ connectBoxdCloud: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boxd-cloud:connect",
+ tag: WS_METHODS.boxdCloudConnect,
+ }),
+ disconnectBoxdCloud: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boxd-cloud:disconnect",
+ tag: WS_METHODS.boxdCloudDisconnect,
+ }),
+ runBoxdCloudSetup: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boxd-cloud:run-setup",
+ tag: WS_METHODS.boxdCloudRunSetup,
+ concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
+ }),
+ acquireBoxdCloud: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boxd-cloud:acquire",
+ tag: WS_METHODS.boxdCloudAcquire,
+ }),
+ // Opening a thread and reconnecting can both ask to wake the same VM.
+ wakeBoatCloud: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:server:boat-cloud:wake",
+ tag: WS_METHODS.boatCloudWake,
+ concurrency: {
+ mode: "singleFlight",
+ key: ({ environmentId, input }) =>
+ `${environmentId}:${input.environmentId}:${input.httpBaseUrl ?? ""}`,
+ },
+ }),
createBot: createEnvironmentRpcCommand(runtime, {
label: "environment-data:server:bot:create",
tag: WS_METHODS.botsCreate,
diff --git a/packages/client-runtime/src/state/threadCommands.test.ts b/packages/client-runtime/src/state/threadCommands.test.ts
index 031ef68a14502..40bcde656667c 100644
--- a/packages/client-runtime/src/state/threadCommands.test.ts
+++ b/packages/client-runtime/src/state/threadCommands.test.ts
@@ -382,6 +382,8 @@ describe("remote thread lifecycle commands", () => {
["setAutoSettle", { enabled: false }, { autoSettleDisabledAt: expect.any(Object) }],
["reorderPin", { orderKey: "b" }, { pinOrderKey: "b" }],
["reorderActive", { orderKey: "b" }, { activeOrderKey: "b" }],
+ ["archive", {}, { archivedAt: expect.anything() }],
+ ["unarchive", {}, { archivedAt: null }],
] as const;
it.effect.each(actions)(
@@ -404,6 +406,7 @@ describe("remote thread lifecycle commands", () => {
...(action === "unpin" || action === "settle"
? { pinnedAt: NOW, pinOrderKey: "a" }
: {}),
+ ...(action === "unarchive" ? { archivedAt: NOW } : {}),
},
],
};
diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts
index 1b5b77d450eac..61e724c9d13e8 100644
--- a/packages/client-runtime/src/state/threadCommands.ts
+++ b/packages/client-runtime/src/state/threadCommands.ts
@@ -478,6 +478,11 @@ export function createThreadEnvironmentAtoms(
rowActionsAtom,
snapshotAtom: optimistic.snapshotAtom,
pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom,
+ archive: optimistic.wrap(commands.archive, (thread, _input, now) => ({
+ ...thread,
+ archivedAt: thread.archivedAt ?? now,
+ })),
+ unarchive: optimistic.wrap(commands.unarchive, (thread) => ({ ...thread, archivedAt: null })),
settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
!accepted &&
(thread.pendingRuntimeRequest !== null ||
diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts
index d18a3e3adae1c..7d0d100fe49a2 100644
--- a/packages/client-runtime/src/state/threadShell.test.ts
+++ b/packages/client-runtime/src/state/threadShell.test.ts
@@ -13,10 +13,14 @@ import { Atom, AtomRegistry } from "effect/reactivity";
import { describe, expect, it } from "vite-plus/test";
import { PrimaryConnectionTarget } from "../connection/model.ts";
-import { v2Now, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
+import { v2Now, v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
import { applyShellStreamEvent } from "./shellReducer.ts";
import { isThreadWorking } from "./threadInbox.ts";
-import { childThreadInputsTitle, createEnvironmentThreadShellAtoms } from "./threadShell.ts";
+import {
+ childThreadInputsTitle,
+ createEnvironmentThreadShellAtoms,
+ mostWorkedRepositories,
+} from "./threadShell.ts";
const environmentId = EnvironmentId.make("environment-v2");
const remoteEnvironmentId = EnvironmentId.make("remote-environment-v2");
@@ -679,3 +683,67 @@ describe("v2 thread shell lists", () => {
}
});
});
+
+describe("mostWorkedRepositories", () => {
+ const project = (id: string, remoteUrl: string | null, extra: object = {}) => ({
+ ...v2Project,
+ id: ProjectId.make(id),
+ repositoryIdentity:
+ remoteUrl === null
+ ? null
+ : {
+ canonicalKey: remoteUrl,
+ locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl },
+ },
+ ...extra,
+ });
+ const threads = (projectId: string, count: number) =>
+ Array.from({ length: count }, (_, index) => ({
+ ...v2ThreadShell,
+ id: ThreadId.make(`${projectId}-${index}`),
+ projectId: ProjectId.make(projectId),
+ }));
+
+ it("sums each repository's threads across machines and remote forms, most first", () => {
+ const laptop: OrchestrationV2ShellSnapshot = {
+ ...v2ShellSnapshot,
+ projects: [
+ project("app", "git@github.com:acme/app.git"),
+ project("site", "https://github.com/acme/site"),
+ project("local", null),
+ project("old", "https://github.com/acme/old", { archivedAt: v2Now.toString() }),
+ project("fork", "https://github.com/upstream/tool", {
+ repositoryIdentity: {
+ canonicalKey: "github.com/upstream/tool",
+ locator: {
+ source: "git-remote" as const,
+ remoteName: "upstream",
+ remoteUrl: "https://github.com/upstream/tool",
+ },
+ origin: { canonicalKey: "github.com/me/tool", remoteUrl: "https://github.com/me/tool" },
+ },
+ }),
+ ],
+ threads: [...threads("app", 2), ...threads("site", 3), ...threads("local", 9)],
+ archivedThreads: [...threads("old", 9), ...threads("fork", 1)],
+ };
+ const desktop: OrchestrationV2ShellSnapshot = {
+ ...v2ShellSnapshot,
+ projects: [project("app-2", "https://github.com/ACME/app")],
+ threads: threads("app-2", 1),
+ archivedThreads: [],
+ olderSettled: {
+ before: v2Now.toString(),
+ asOfSequence: 0,
+ counts: [{ projectId: ProjectId.make("app-2"), count: 4 }],
+ },
+ };
+
+ expect(mostWorkedRepositories([laptop, null, desktop], 10)).toEqual([
+ "git@github.com:acme/app.git",
+ "https://github.com/acme/site",
+ "https://github.com/me/tool",
+ ]);
+ expect(mostWorkedRepositories([laptop, desktop], 1)).toEqual(["git@github.com:acme/app.git"]);
+ });
+});
diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts
index 77429c9450b65..886e814f16a72 100644
--- a/packages/client-runtime/src/state/threadShell.ts
+++ b/packages/client-runtime/src/state/threadShell.ts
@@ -7,13 +7,16 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import {
+ isBoatCloudHttpBaseUrl,
isListedThreadLineage,
isProviderNativeSubagentThread,
OrchestrationV2ThreadShell,
} from "@t3tools/contracts";
+import { parseRepository } from "@t3tools/shared/boatCloudVm";
import * as Schema from "effect/Schema";
import { Atom } from "effect/reactivity";
+import { connectionCatalogDisplayUrl } from "../connection/presentation.ts";
import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
import { presentThreadShell, threadRuntimeIsActive } from "./models.ts";
import { hiddenThreadKeys, NO_HIDDEN_THREADS } from "./threadTagFilter.ts";
@@ -208,6 +211,74 @@ function sameApartFromStreaming(
);
}
+/**
+ * A Boat cloud VM keeps the threads of every device and repository that used it, so a
+ * client lists only the VM threads it started or opened, from `openedThreadsAtom`.
+ */
+export function createBoatCloudThreadListAtoms(input: {
+ readonly catalogValueAtom: Atom.Atom;
+ readonly openedThreadsAtom: Atom.Atom>;
+}) {
+ const onBoatCloudAtom = Atom.family((environmentId: EnvironmentId) =>
+ Atom.make((get) => {
+ const entry = get(input.catalogValueAtom).entries.get(environmentId);
+ return entry !== undefined && isBoatCloudHttpBaseUrl(connectionCatalogDisplayUrl(entry));
+ }).pipe(Atom.withLabel(`boat-cloud-environment:${environmentId}`)),
+ );
+ const listedThreadIdsAtom = Atom.family((environmentId: EnvironmentId) =>
+ Atom.make((get): ReadonlySet | null =>
+ get(onBoatCloudAtom(environmentId))
+ ? new Set(
+ get(input.openedThreadsAtom)
+ .filter((ref) => ref.environmentId === environmentId)
+ .map((ref) => ref.threadId),
+ )
+ : null,
+ ).pipe(Atom.withLabel(`boat-cloud-listed-thread-ids:${environmentId}`)),
+ );
+ return { onBoatCloudAtom, listedThreadIdsAtom };
+}
+
+/**
+ * Git remotes with the most threads across these environments' snapshots, most first and one
+ * per repository, for the Boat cloud snapshot to check out. Archived and older settled threads
+ * count; archived projects do not.
+ */
+export function mostWorkedRepositories(
+ snapshots: Iterable,
+ limit: number,
+): Array {
+ const byRepository = new Map();
+ for (const snapshot of snapshots) {
+ if (snapshot === null) continue;
+ const threadsByProject = new Map();
+ const add = (projectId: ProjectId, count: number) =>
+ threadsByProject.set(projectId, (threadsByProject.get(projectId) ?? 0) + count);
+ for (const thread of snapshot.threads) add(thread.projectId, 1);
+ for (const thread of snapshot.archivedThreads) add(thread.projectId, 1);
+ for (const older of snapshot.olderSettled?.counts ?? []) add(older.projectId, older.count);
+ for (const project of snapshot.projects) {
+ const threads = threadsByProject.get(project.id) ?? 0;
+ // A fork's own remote, where the agent can push, as a Boat cloud start clones it.
+ const identity = project.repositoryIdentity;
+ const remoteUrl = identity?.origin?.remoteUrl ?? identity?.locator.remoteUrl;
+ const repository = remoteUrl === undefined ? null : parseRepository(remoteUrl);
+ if (threads === 0 || project.archivedAt || remoteUrl === undefined || repository === null) {
+ continue;
+ }
+ const known = byRepository.get(repository.key);
+ byRepository.set(repository.key, {
+ remoteUrl: known?.remoteUrl ?? remoteUrl,
+ threads: (known?.threads ?? 0) + threads,
+ });
+ }
+ }
+ return [...byRepository.values()]
+ .sort((left, right) => right.threads - left.threads)
+ .slice(0, limit)
+ .map((repository) => repository.remoteUrl);
+}
+
export function createEnvironmentThreadShellAtoms(input: {
readonly catalogValueAtom: Atom.Atom;
readonly snapshotAtom: (
@@ -217,6 +288,10 @@ export function createEnvironmentThreadShellAtoms(input: {
readonly hiddenThreadTagsAtom: (
environmentId: EnvironmentId,
) => Atom.Atom | null>;
+ /** The only top-level threads display lists show for an environment; null shows them all. */
+ readonly listedThreadIdsAtom?: (
+ environmentId: EnvironmentId,
+ ) => Atom.Atom | null>;
}) {
// Point reads and aggregate lists share values without keeping an atom alive
// for every listed thread. Replaced source objects can be collected.
@@ -624,10 +699,18 @@ export function createEnvironmentThreadShellAtoms(input: {
(environmentId) => ({
environmentId,
hiddenTags: get(input.hiddenThreadTagsAtom(environmentId)),
+ listedThreadIds:
+ input.listedThreadIdsAtom === undefined
+ ? null
+ : get(input.listedThreadIdsAtom(environmentId)),
}),
);
- // Read shells only while some environment hides tags, so streaming ticks cost nothing otherwise.
- if (!environments.some((environment) => environment.hiddenTags !== null)) {
+ // Read shells only while some environment filters, so streaming ticks cost nothing otherwise.
+ if (
+ !environments.some(
+ (environment) => environment.hiddenTags !== null || environment.listedThreadIds !== null,
+ )
+ ) {
previousHiddenThreadKeys = NO_HIDDEN_THREADS;
return NO_HIDDEN_THREADS;
}
diff --git a/packages/client-runtime/src/state/threadTagFilter.test.ts b/packages/client-runtime/src/state/threadTagFilter.test.ts
index d38e5386d5243..b8463a28d1829 100644
--- a/packages/client-runtime/src/state/threadTagFilter.test.ts
+++ b/packages/client-runtime/src/state/threadTagFilter.test.ts
@@ -91,6 +91,26 @@ describe("hiddenThreadKeys", () => {
expect(keys(null, null)).toEqual([]);
});
+ it("lists only an environment's chosen threads, with their subagents and linked tasks", () => {
+ const hidden = hiddenThreadKeys([
+ {
+ environmentId: local,
+ threads: localThreads,
+ hiddenTags: null,
+ listedThreadIds: new Set([ThreadId.make("plain")]),
+ },
+ { environmentId: linked, threads: linkedThreads, hiddenTags: null },
+ ]);
+ expect([...hidden].toSorted()).toEqual(
+ [
+ key(local, "private"),
+ key(local, "private-subagent"),
+ key(local, "private-fork"),
+ key(linked, "delegated-from-private"),
+ ].toSorted(),
+ );
+ });
+
it("applies each environment's own tags", () => {
expect(hiddenIds(null, ["client", "private"])).toEqual([key(linked, "linked-client")]);
});
diff --git a/packages/client-runtime/src/state/threadTagFilter.ts b/packages/client-runtime/src/state/threadTagFilter.ts
index 78e314445bfb5..ed7ae4d5c0573 100644
--- a/packages/client-runtime/src/state/threadTagFilter.ts
+++ b/packages/client-runtime/src/state/threadTagFilter.ts
@@ -18,6 +18,8 @@ export interface TagFilteredEnvironment {
readonly threads: ReadonlyArray;
/** Tags this environment hides, or null while its filter is off. */
readonly hiddenTags: ReadonlyArray | null;
+ /** The only top-level threads this environment lists, or null to list them all. */
+ readonly listedThreadIds?: ReadonlySet | null;
}
export const NO_HIDDEN_THREADS: ReadonlySet = new Set();
@@ -74,7 +76,13 @@ export function hiddenThreadKeys(
loadedElsewhere: ReadonlySet = NO_HIDDEN_THREADS,
hidingAnywhere: boolean = environments.some((environment) => environment.hiddenTags !== null),
): ReadonlySet {
- if (alreadyHidden.size === 0 && !hidingAnywhere) return NO_HIDDEN_THREADS;
+ if (
+ alreadyHidden.size === 0 &&
+ !hidingAnywhere &&
+ !environments.some((environment) => environment.listedThreadIds != null)
+ ) {
+ return NO_HIDDEN_THREADS;
+ }
const byKey = new Map<
string,
{ thread: FilterableThread; environment: TagFilteredEnvironment }
@@ -107,7 +115,9 @@ export function hiddenThreadKeys(
return true;
}
if (!followsParent) {
- const hidden = hasHiddenTag(thread.tags, environment.hiddenTags);
+ const hidden =
+ hasHiddenTag(thread.tags, environment.hiddenTags) ||
+ environment.listedThreadIds?.has(thread.id) === false;
hiddenByKey.set(key, hidden);
return hidden;
}
diff --git a/packages/contracts/src/boatCloud.ts b/packages/contracts/src/boatCloud.ts
new file mode 100644
index 0000000000000..572dcad9ea71c
--- /dev/null
+++ b/packages/contracts/src/boatCloud.ts
@@ -0,0 +1,237 @@
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts";
+
+/**
+ * Boat cloud runs agents on Boat (boat.dev) VMs. Each VM runs its own T3 server,
+ * so it is an ordinary environment that clients pair with over its public URL.
+ * The environment holding the Boat API key creates, wakes and stops the VMs.
+ */
+
+/** Boat serves every VM's ports under this domain, so its URL marks an environment as a VM. */
+const BOAT_HOST_SUFFIX = ".on.boat.dev";
+
+export function isBoatCloudHttpBaseUrl(httpBaseUrl: string | null | undefined): boolean {
+ if (!httpBaseUrl) return false;
+ try {
+ return new URL(httpBaseUrl).hostname.endsWith(BOAT_HOST_SUFFIX);
+ } catch {
+ return false;
+ }
+}
+
+/** The API key scopes Boat cloud uses, in Boat's own scope names. */
+export const BOAT_CLOUD_REQUIRED_SCOPES = [
+ "sandbox.create",
+ "sandbox.read",
+ "sandbox.update",
+ "sandbox.stop",
+ "sandbox.resume",
+ "sandbox.delete",
+ "exec",
+ "file.read",
+ "file.write",
+ "host",
+ "ssh",
+ "snapshot.read",
+ "snapshot.write",
+ "environment.read",
+ "environment.write",
+ "account.read",
+ // Reading which AI credentials a profile holds needs it; Boat never returns their values.
+ "account.admin",
+] as const;
+
+export const BOAT_CLOUD_SETUP_STEPS = [
+ "create-vm",
+ "install-server",
+ "copy-skills",
+ "save-snapshot",
+] as const;
+export const BoatCloudSetupStep = Schema.Literals(BOAT_CLOUD_SETUP_STEPS);
+export type BoatCloudSetupStep = typeof BoatCloudSetupStep.Type;
+
+export const BoatCloudSetup = Schema.Struct({
+ status: Schema.Literals(["idle", "running", "ready", "failed"]),
+ /** The step running, or the one that failed. */
+ step: Schema.NullOr(BoatCloudSetupStep),
+ error: Schema.NullOr(Schema.String),
+});
+export type BoatCloudSetup = typeof BoatCloudSetup.Type;
+
+export const BoatCloudMachineState = Schema.Literals(["running", "starting", "stopped", "gone"]);
+export type BoatCloudMachineState = typeof BoatCloudMachineState.Type;
+
+export const BoatCloudMachine = Schema.Struct({
+ sandboxId: TrimmedNonEmptyString,
+ environmentId: Schema.NullOr(EnvironmentId),
+ label: Schema.String,
+ httpBaseUrl: Schema.NullOr(Schema.String),
+ state: BoatCloudMachineState,
+ repositories: Schema.Array(Schema.String),
+ /** When this machine last copied the VM's sessions and workspaces, before stopping it. */
+ backedUpAt: Schema.NullOr(Schema.String),
+ /** The Boat environment the VM started on. Boat keeps it across stops and resumes. */
+ environment: Schema.NullOr(Schema.String),
+});
+export type BoatCloudMachine = typeof BoatCloudMachine.Type;
+
+/**
+ * Starting a thread on Boat cloud, in order. `server` and `repository` run at
+ * the same time; the holder reports the first three and the client the rest.
+ * Acquire returns once the server is up, so `repository` can still be running.
+ */
+export const BOAT_CLOUD_START_STEPS = [
+ "machine",
+ "server",
+ "repository",
+ "connect",
+ "project",
+ "thread",
+] as const;
+export const BoatCloudStartStep = Schema.Literals(BOAT_CLOUD_START_STEPS);
+export type BoatCloudStartStep = typeof BoatCloudStartStep.Type;
+
+export const BoatCloudStepProgress = Schema.Struct({
+ step: BoatCloudStartStep,
+ state: Schema.Literals(["pending", "active", "done", "failed"]),
+ /** What the step is doing, such as which VM it reuses or which repository it clones. */
+ detail: Schema.NullOr(Schema.String),
+});
+export type BoatCloudStepProgress = typeof BoatCloudStepProgress.Type;
+
+/** One acquire in flight on the holder, so the client that asked can show its steps. */
+export const BoatCloudStart = Schema.Struct({
+ requestId: TrimmedNonEmptyString,
+ steps: Schema.Array(BoatCloudStepProgress),
+});
+export type BoatCloudStart = typeof BoatCloudStart.Type;
+
+/** What a Boat environment passes to its VMs, in Boat's own field names. */
+export const BoatCloudEnvironmentAccess = Schema.Struct({
+ passGithub: Schema.Boolean,
+ passSandboxCredentials: Schema.Boolean,
+ passSecrets: Schema.Boolean,
+ passAgentsCredentials: Schema.Boolean,
+});
+export type BoatCloudEnvironmentAccess = typeof BoatCloudEnvironmentAccess.Type;
+
+export const BoatCloudEnvironment = Schema.Struct({
+ id: TrimmedNonEmptyString,
+ name: TrimmedNonEmptyString,
+ isDefault: Schema.Boolean,
+ ...BoatCloudEnvironmentAccess.fields,
+ /** Boat's ids of the AI credentials its VMs get, such as `anthropic-api-key`. Null when unknown. */
+ agentCredentials: Schema.NullOr(Schema.Array(Schema.String)),
+});
+export type BoatCloudEnvironment = typeof BoatCloudEnvironment.Type;
+
+export const BoatCloudStatus = Schema.Struct({
+ connected: Schema.Boolean,
+ /** The Boat account the key belongs to. */
+ account: Schema.NullOr(Schema.String),
+ setup: BoatCloudSetup,
+ /** VMs can start from the saved snapshot, even while setup rebuilds it. */
+ snapshotReady: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
+ machines: Schema.Array(BoatCloudMachine),
+ starts: Schema.Array(BoatCloudStart),
+ /** The Boat environment new VMs start on, by name. */
+ environment: Schema.NullOr(Schema.String),
+ environments: Schema.Array(BoatCloudEnvironment),
+ /** Why the environments could not be listed, such as a key without `environment.read`. */
+ environmentsError: Schema.NullOr(Schema.String),
+});
+export type BoatCloudStatus = typeof BoatCloudStatus.Type;
+
+export const BoatCloudSubscribeInput = Schema.Struct({});
+export type BoatCloudSubscribeInput = typeof BoatCloudSubscribeInput.Type;
+
+export const BoatCloudConnectInput = Schema.Struct({
+ apiKey: TrimmedNonEmptyString.check(Schema.isMaxLength(512)),
+});
+export type BoatCloudConnectInput = typeof BoatCloudConnectInput.Type;
+
+/** Picks the environment for new VMs, and optionally changes what it passes to them. */
+export const BoatCloudConfigureEnvironmentInput = Schema.Struct({
+ environmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(128)),
+ access: Schema.optional(BoatCloudEnvironmentAccess),
+});
+export type BoatCloudConfigureEnvironmentInput = typeof BoatCloudConfigureEnvironmentInput.Type;
+
+export const BoatCloudEmptyInput = Schema.Struct({});
+export type BoatCloudEmptyInput = typeof BoatCloudEmptyInput.Type;
+
+/** How many repositories the snapshot checks out. */
+export const BOAT_CLOUD_SNAPSHOT_REPOSITORIES = 10;
+
+export const BoatCloudRunSetupInput = Schema.Struct({
+ /**
+ * Git remotes the snapshot checks out, most worked first. The holder keeps them for later
+ * rebuilds; absent keeps the ones it has.
+ */
+ repositories: Schema.optional(
+ Schema.Array(TrimmedNonEmptyString.check(Schema.isMaxLength(2048))).check(
+ Schema.isMaxLength(BOAT_CLOUD_SNAPSHOT_REPOSITORIES),
+ ),
+ ),
+});
+export type BoatCloudRunSetupInput = typeof BoatCloudRunSetupInput.Type;
+
+export const BoatCloudAcquireInput = Schema.Struct({
+ /** The project's git remote; the VM clones it when it does not have it yet. */
+ repositoryUrl: TrimmedNonEmptyString.check(Schema.isMaxLength(2048)),
+ /** The thread's base branch; the start fails early when the remote does not have it. */
+ baseBranch: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(512))),
+ /** Names this start in `BoatCloudStatus.starts`. */
+ requestId: TrimmedNonEmptyString.check(Schema.isMaxLength(128)),
+ /** Boat cloud VMs the client already paired with; picking one of them skips the pairing code. */
+ paired: Schema.optional(
+ Schema.Array(
+ Schema.Struct({
+ environmentId: EnvironmentId,
+ httpBaseUrl: TrimmedNonEmptyString.check(Schema.isMaxLength(2048)),
+ }),
+ ).check(Schema.isMaxLength(64)),
+ ),
+});
+export type BoatCloudAcquireInput = typeof BoatCloudAcquireInput.Type;
+
+export const BoatCloudWakeInput = Schema.Struct({
+ environmentId: EnvironmentId,
+ /** Finds a VM this holder did not start, such as one another holder made with the same key. */
+ httpBaseUrl: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(2048))),
+ /** The holder reports the wake's machine and server steps under this id in its status. */
+ requestId: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(128))),
+});
+export type BoatCloudWakeInput = typeof BoatCloudWakeInput.Type;
+
+/** What a client needs to reach a VM's T3 server: a one-time pairing code for its URL. */
+export const BoatCloudSession = Schema.Struct({
+ sandboxId: TrimmedNonEmptyString,
+ environmentId: EnvironmentId,
+ httpBaseUrl: TrimmedNonEmptyString,
+ /** Null when the client is already paired with this environment and reconnects instead. */
+ pairingCode: Schema.NullOr(TrimmedNonEmptyString),
+ /** Repository checkout on the VM; null for a wake. */
+ workspaceRoot: Schema.NullOr(TrimmedNonEmptyString),
+ /**
+ * The thread's worktree, which the VM cuts while its server starts. Ready once the start's
+ * `repository` step is done. Absent from older holders and for a start with no base branch.
+ */
+ worktree: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ path: TrimmedNonEmptyString,
+ branch: TrimmedNonEmptyString,
+ baseBranch: TrimmedNonEmptyString,
+ }),
+ ),
+ ),
+});
+export type BoatCloudSession = typeof BoatCloudSession.Type;
+
+export class BoatCloudError extends Schema.TaggedError()("BoatCloudError", {
+ message: Schema.String,
+ cause: Schema.optional(Schema.Defect()),
+}) {}
diff --git a/packages/contracts/src/boxdCloud.ts b/packages/contracts/src/boxdCloud.ts
new file mode 100644
index 0000000000000..7025b81f948ba
--- /dev/null
+++ b/packages/contracts/src/boxdCloud.ts
@@ -0,0 +1,57 @@
+import * as Schema from "effect/Schema";
+
+import { EnvironmentId, TrimmedNonEmptyString } from "./baseSchemas.ts";
+import { BoatCloudSetup, BoatCloudStart } from "./boatCloud.ts";
+
+/**
+ * boxd cloud runs agents on boxd (boxd.sh) machines, the same way Boat cloud runs them on
+ * Boat VMs: each machine runs its own T3 server and clients pair with it over its public URL.
+ * Starts, setup progress and sessions use Boat cloud's shapes, so clients show them the same way.
+ */
+
+const BOXD_HOST_SUFFIX = ".boxd.sh";
+
+export function isBoxdCloudHttpBaseUrl(httpBaseUrl: string | null | undefined): boolean {
+ if (!httpBaseUrl) return false;
+ try {
+ return new URL(httpBaseUrl).hostname.endsWith(BOXD_HOST_SUFFIX);
+ } catch {
+ return false;
+ }
+}
+
+/** boxd wakes an asleep machine on its own when a client connects to its URL. */
+export const BoxdCloudMachineState = Schema.Literals(["running", "asleep", "stopped"]);
+export type BoxdCloudMachineState = typeof BoxdCloudMachineState.Type;
+
+export const BoxdCloudMachine = Schema.Struct({
+ vmId: TrimmedNonEmptyString,
+ environmentId: Schema.NullOr(EnvironmentId),
+ label: Schema.String,
+ httpBaseUrl: Schema.NullOr(Schema.String),
+ state: BoxdCloudMachineState,
+ repositories: Schema.Array(Schema.String),
+});
+export type BoxdCloudMachine = typeof BoxdCloudMachine.Type;
+
+export const BoxdCloudStatus = Schema.Struct({
+ connected: Schema.Boolean,
+ /** The boxd account the key belongs to. */
+ account: Schema.NullOr(Schema.String),
+ setup: BoatCloudSetup,
+ /** Machines can start from the saved snapshot, even while setup rebuilds it. */
+ snapshotReady: Schema.Boolean,
+ machines: Schema.Array(BoxdCloudMachine),
+ starts: Schema.Array(BoatCloudStart),
+});
+export type BoxdCloudStatus = typeof BoxdCloudStatus.Type;
+
+export const BoxdCloudConnectInput = Schema.Struct({
+ apiKey: TrimmedNonEmptyString.check(Schema.isMaxLength(512)),
+});
+export type BoxdCloudConnectInput = typeof BoxdCloudConnectInput.Type;
+
+export class BoxdCloudError extends Schema.TaggedError()("BoxdCloudError", {
+ message: Schema.String,
+ cause: Schema.optional(Schema.Defect()),
+}) {}
diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts
index 0b41e92846de3..37a263969fb4f 100644
--- a/packages/contracts/src/clientRpcPermissions.ts
+++ b/packages/contracts/src/clientRpcPermissions.ts
@@ -75,6 +75,17 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
[WS_METHODS.botsUpdate]: AuthOrchestrationOperateScope,
[WS_METHODS.botsDelete]: AuthOrchestrationOperateScope,
[WS_METHODS.botsGenerateAvatar]: AuthOrchestrationOperateScope,
+ // The Boat key spends money on VMs, as a provider API key does.
+ [WS_METHODS.boatCloudConnect]: AuthSettingsWriteScope,
+ [WS_METHODS.boatCloudDisconnect]: AuthSettingsWriteScope,
+ [WS_METHODS.boatCloudRunSetup]: AuthSettingsWriteScope,
+ [WS_METHODS.boatCloudConfigureEnvironment]: AuthSettingsWriteScope,
+ [WS_METHODS.boatCloudAcquire]: AuthOrchestrationOperateScope,
+ [WS_METHODS.boatCloudWake]: AuthOrchestrationOperateScope,
+ [WS_METHODS.boxdCloudConnect]: AuthSettingsWriteScope,
+ [WS_METHODS.boxdCloudDisconnect]: AuthSettingsWriteScope,
+ [WS_METHODS.boxdCloudRunSetup]: AuthSettingsWriteScope,
+ [WS_METHODS.boxdCloudAcquire]: AuthOrchestrationOperateScope,
[ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,
// Force stop kills agent processes, as Stop on a terminal does.
[ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope,
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index a4a991a6fbb9a..32c6b891c7ed7 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -149,6 +149,10 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
serverSelfUpdate: Schema.optionalKey(ServerSelfUpdateCapability),
/** Server answers server.getNpmRelease using its configured npm registry. */
npmReleaseLookup: Schema.optionalKey(Schema.Boolean),
+ /** Server can hold a Boat key and start Boat cloud VMs. */
+ boatCloud: Schema.optionalKey(Schema.Boolean),
+ /** Server can hold a boxd key and start boxd cloud machines. */
+ boxdCloud: Schema.optionalKey(Schema.Boolean),
/** Manual commands must update this install, not the host's default global prefix. */
serverInstallation: ForwardCompatibleOptional(ServerInstallation),
serverSelfUpdateProgress: Schema.optionalKey(Schema.Boolean),
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index 0b075706b6256..7a67bc353df08 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -66,6 +66,8 @@ export * from "./previewCapture.ts";
export * from "./usage.ts";
export * from "./scheduledTask.ts";
export * from "./bot.ts";
+export * from "./boatCloud.ts";
+export * from "./boxdCloud.ts";
export * from "./worktreeMcp.ts";
export * from "./resourceTelemetry.ts";
export * from "./rpc.ts";
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 9cccea9d98cfc..743b50f113308 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -399,6 +399,19 @@ import {
BotPreviewsResult,
BotUpdateInput,
} from "./bot.ts";
+import {
+ BoatCloudAcquireInput,
+ BoatCloudConfigureEnvironmentInput,
+ BoatCloudConnectInput,
+ BoatCloudEmptyInput,
+ BoatCloudError,
+ BoatCloudRunSetupInput,
+ BoatCloudSession,
+ BoatCloudStatus,
+ BoatCloudSubscribeInput,
+ BoatCloudWakeInput,
+} from "./boatCloud.ts";
+import { BoxdCloudConnectInput, BoxdCloudError, BoxdCloudStatus } from "./boxdCloud.ts";
import {
ProjectCloneActionInput,
ProjectCloneActionResult,
@@ -582,6 +595,19 @@ export const WS_METHODS = {
botsGenerateAvatar: "bots.generateAvatar",
botsPreviews: "bots.previews",
+ boatCloudSubscribe: "boatCloud.subscribe",
+ boatCloudConnect: "boatCloud.connect",
+ boatCloudDisconnect: "boatCloud.disconnect",
+ boatCloudRunSetup: "boatCloud.runSetup",
+ boatCloudConfigureEnvironment: "boatCloud.configureEnvironment",
+ boatCloudAcquire: "boatCloud.acquire",
+ boatCloudWake: "boatCloud.wake",
+ boxdCloudSubscribe: "boxdCloud.subscribe",
+ boxdCloudConnect: "boxdCloud.connect",
+ boxdCloudDisconnect: "boxdCloud.disconnect",
+ boxdCloudRunSetup: "boxdCloud.runSetup",
+ boxdCloudAcquire: "boxdCloud.acquire",
+
cloudGetRelayClientStatus: "cloud.getRelayClientStatus",
cloudInstallRelayClient: "cloud.installRelayClient",
@@ -2116,6 +2142,84 @@ const WsBotsPreviewsRpc = Rpc.make(WS_METHODS.botsPreviews, {
error: Schema.Union([BotError, EnvironmentAuthorizationError]),
});
+const BoatCloudErrors = Schema.Union([BoatCloudError, EnvironmentAuthorizationError]);
+
+const WsBoatCloudSubscribeRpc = Rpc.make(WS_METHODS.boatCloudSubscribe, {
+ payload: BoatCloudSubscribeInput,
+ success: BoatCloudStatus,
+ error: BoatCloudErrors,
+ stream: true,
+});
+
+const WsBoatCloudConnectRpc = Rpc.make(WS_METHODS.boatCloudConnect, {
+ payload: BoatCloudConnectInput,
+ success: BoatCloudStatus,
+ error: BoatCloudErrors,
+});
+
+const WsBoatCloudDisconnectRpc = Rpc.make(WS_METHODS.boatCloudDisconnect, {
+ payload: BoatCloudEmptyInput,
+ success: BoatCloudStatus,
+ error: BoatCloudErrors,
+});
+
+const WsBoatCloudRunSetupRpc = Rpc.make(WS_METHODS.boatCloudRunSetup, {
+ payload: BoatCloudRunSetupInput,
+ success: BoatCloudStatus,
+ error: BoatCloudErrors,
+});
+
+const WsBoatCloudConfigureEnvironmentRpc = Rpc.make(WS_METHODS.boatCloudConfigureEnvironment, {
+ payload: BoatCloudConfigureEnvironmentInput,
+ success: BoatCloudStatus,
+ error: BoatCloudErrors,
+});
+
+const WsBoatCloudAcquireRpc = Rpc.make(WS_METHODS.boatCloudAcquire, {
+ payload: BoatCloudAcquireInput,
+ success: BoatCloudSession,
+ error: BoatCloudErrors,
+});
+
+const WsBoatCloudWakeRpc = Rpc.make(WS_METHODS.boatCloudWake, {
+ payload: BoatCloudWakeInput,
+ success: BoatCloudSession,
+ error: BoatCloudErrors,
+});
+
+const BoxdCloudErrors = Schema.Union([BoxdCloudError, EnvironmentAuthorizationError]);
+
+const WsBoxdCloudSubscribeRpc = Rpc.make(WS_METHODS.boxdCloudSubscribe, {
+ payload: BoatCloudSubscribeInput,
+ success: BoxdCloudStatus,
+ error: BoxdCloudErrors,
+ stream: true,
+});
+
+const WsBoxdCloudConnectRpc = Rpc.make(WS_METHODS.boxdCloudConnect, {
+ payload: BoxdCloudConnectInput,
+ success: BoxdCloudStatus,
+ error: BoxdCloudErrors,
+});
+
+const WsBoxdCloudDisconnectRpc = Rpc.make(WS_METHODS.boxdCloudDisconnect, {
+ payload: BoatCloudEmptyInput,
+ success: BoxdCloudStatus,
+ error: BoxdCloudErrors,
+});
+
+const WsBoxdCloudRunSetupRpc = Rpc.make(WS_METHODS.boxdCloudRunSetup, {
+ payload: BoatCloudRunSetupInput,
+ success: BoxdCloudStatus,
+ error: BoxdCloudErrors,
+});
+
+const WsBoxdCloudAcquireRpc = Rpc.make(WS_METHODS.boxdCloudAcquire, {
+ payload: BoatCloudAcquireInput,
+ success: BoatCloudSession,
+ error: BoxdCloudErrors,
+});
+
const WsGuestShareCreateRpc = Rpc.make(WS_METHODS.guestShareCreate, {
payload: GuestShareCreateInput,
success: GuestShareCreateResult,
@@ -2239,6 +2343,18 @@ export const WsRpcGroup = RpcGroup.make(
WsBotsDeleteRpc,
WsBotsGenerateAvatarRpc,
WsBotsPreviewsRpc,
+ WsBoatCloudSubscribeRpc,
+ WsBoatCloudConnectRpc,
+ WsBoatCloudDisconnectRpc,
+ WsBoatCloudRunSetupRpc,
+ WsBoatCloudConfigureEnvironmentRpc,
+ WsBoatCloudAcquireRpc,
+ WsBoatCloudWakeRpc,
+ WsBoxdCloudSubscribeRpc,
+ WsBoxdCloudConnectRpc,
+ WsBoxdCloudDisconnectRpc,
+ WsBoxdCloudRunSetupRpc,
+ WsBoxdCloudAcquireRpc,
WsServerReportClientActivityRpc,
WsCloudGetRelayClientStatusRpc,
WsCloudInstallRelayClientRpc,
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 3216f52ebe950..0745ed8b9629b 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -578,6 +578,26 @@
"./speech": {
"types": "./src/speech.ts",
"import": "./src/speech.ts"
+ },
+ "./boatCloudApi": {
+ "types": "./src/boatCloudApi.ts",
+ "import": "./src/boatCloudApi.ts"
+ },
+ "./boatCloudStart": {
+ "types": "./src/boatCloudStart.ts",
+ "import": "./src/boatCloudStart.ts"
+ },
+ "./boatCloudVm": {
+ "types": "./src/boatCloudVm.ts",
+ "import": "./src/boatCloudVm.ts"
+ },
+ "./boxdCloudApi": {
+ "types": "./src/boxdCloudApi.ts",
+ "import": "./src/boxdCloudApi.ts"
+ },
+ "./boxdCloudStart": {
+ "types": "./src/boxdCloudStart.ts",
+ "import": "./src/boxdCloudStart.ts"
}
},
"scripts": {
diff --git a/packages/shared/src/boatCloudApi.test.ts b/packages/shared/src/boatCloudApi.test.ts
new file mode 100644
index 0000000000000..e46546388779a
--- /dev/null
+++ b/packages/shared/src/boatCloudApi.test.ts
@@ -0,0 +1,52 @@
+import { assert, describe, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as TestClock from "effect/testing/TestClock";
+import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
+
+import { makeBoatApi } from "./boatCloudApi.ts";
+
+const commandResult = { exitCode: 0, stdout: "ok" };
+
+describe("BoatApi.exec", () => {
+ it.effect("does not resend a command after the connection drops", () =>
+ Effect.gen(function* () {
+ let requests = 0;
+ const http = HttpClient.make((request) =>
+ Effect.suspend(() => {
+ requests += 1;
+ return Effect.fail(
+ new HttpClientError.HttpClientError({
+ reason: new HttpClientError.TransportError({ request, cause: new Error("reset") }),
+ }),
+ );
+ }),
+ );
+ const error = yield* Effect.flip(makeBoatApi(http, "key").exec("box", "echo hi"));
+ assert.strictEqual(error.code, "network");
+ assert.strictEqual(requests, 1);
+ }),
+ );
+
+ it.effect("retries a command Boat refused because the VM was still starting", () =>
+ Effect.gen(function* () {
+ let requests = 0;
+ const http = HttpClient.make((request) =>
+ Effect.sync(() => {
+ requests += 1;
+ return HttpClientResponse.fromWeb(
+ request,
+ requests === 1
+ ? Response.json({ code: "sandbox_starting", message: "starting" }, { status: 409 })
+ : Response.json(commandResult),
+ );
+ }),
+ );
+ const fiber = yield* Effect.forkChild(makeBoatApi(http, "key").exec("box", "echo hi"));
+ yield* TestClock.adjust("2 seconds");
+ const result = yield* Fiber.join(fiber);
+ assert.strictEqual(result.stdout, "ok");
+ assert.strictEqual(requests, 2);
+ }),
+ );
+});
diff --git a/packages/shared/src/boatCloudApi.ts b/packages/shared/src/boatCloudApi.ts
new file mode 100644
index 0000000000000..f572386e59732
--- /dev/null
+++ b/packages/shared/src/boatCloudApi.ts
@@ -0,0 +1,349 @@
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Schedule from "effect/Schedule";
+import * as Schema from "effect/Schema";
+import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http";
+import type { BoatCloudEnvironment } from "@t3tools/contracts";
+
+/**
+ * A thin client for the parts of the Boat v1 API that Boat cloud uses. It runs
+ * on the server and on the phone, so it needs only an HTTP client.
+ */
+
+const BOAT_API_URL = "https://boat.dev/api/v1";
+
+export class BoatApiError extends Schema.TaggedError()("BoatApiError", {
+ status: Schema.Number,
+ code: Schema.String,
+ /** Fixed or built from `code` and `status`; Boat's own text and VM output stay in `cause`. */
+ message: Schema.String,
+ retryable: Schema.Boolean,
+ cause: Schema.optional(Schema.Defect()),
+}) {}
+
+export const BoatSandbox = Schema.Struct({
+ id: Schema.String,
+ name: Schema.optional(Schema.NullOr(Schema.String)),
+ state: Schema.String,
+ /** Stable across stop and resume; hosted ports live at `-.on.boat.dev`. */
+ subdomain: Schema.optional(Schema.NullOr(Schema.String)),
+ labels: Schema.optional(Schema.NullOr(Schema.Record(Schema.String, Schema.String))),
+ /** The environment's name. A sandbox keeps it for life; null for one attached to none. */
+ environment: Schema.optional(Schema.NullOr(Schema.String)),
+});
+export type BoatSandbox = typeof BoatSandbox.Type;
+
+const BoatEnvironment = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ isDefault: Schema.Boolean,
+ passGithub: Schema.Boolean,
+ passSandboxCredentials: Schema.Boolean,
+ passSecrets: Schema.Boolean,
+ passAgentsCredentials: Schema.Boolean,
+ /** An id or a name; null means the account's default profile. */
+ credentialProfileId: Schema.optional(Schema.NullOr(Schema.String)),
+});
+export type BoatEnvironment = typeof BoatEnvironment.Type;
+const EnvironmentList = Schema.Struct({ environments: Schema.Array(BoatEnvironment) });
+
+const BoatCredentialProfile = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ isDefault: Schema.Boolean,
+ /** The ids of the credentials it holds, never their values. */
+ connected: Schema.Array(Schema.String),
+});
+export type BoatCredentialProfile = typeof BoatCredentialProfile.Type;
+const CredentialProfileList = Schema.Struct({ profiles: Schema.Array(BoatCredentialProfile) });
+
+/**
+ * What a client shows of each environment, with the AI credentials its VMs get:
+ * those of its profile, or none when it passes no agent credentials.
+ */
+export function cloudEnvironments(
+ environments: ReadonlyArray,
+ profiles: ReadonlyArray | null,
+): Array {
+ return environments.map((environment) => {
+ const named = environment.credentialProfileId ?? null;
+ const profile = profiles?.find((candidate) =>
+ named === null ? candidate.isDefault : candidate.id === named || candidate.name === named,
+ );
+ return {
+ id: environment.id,
+ name: environment.name,
+ isDefault: environment.isDefault,
+ passGithub: environment.passGithub,
+ passSandboxCredentials: environment.passSandboxCredentials,
+ passSecrets: environment.passSecrets,
+ passAgentsCredentials: environment.passAgentsCredentials,
+ agentCredentials: !environment.passAgentsCredentials ? [] : (profile?.connected ?? null),
+ };
+ });
+}
+
+export type BoatMachineType = "small" | "default" | "large" | "xlarge";
+
+const ErrorBody = Schema.Struct({
+ code: Schema.optional(Schema.String),
+ message: Schema.optional(Schema.String),
+ error: Schema.optional(
+ Schema.Struct({
+ details: Schema.optional(
+ Schema.Struct({
+ retryable: Schema.optional(Schema.Boolean),
+ message: Schema.optional(Schema.String),
+ }),
+ ),
+ }),
+ ),
+});
+const decodeErrorBody = Schema.decodeUnknownOption(ErrorBody);
+
+const Me = Schema.Struct({
+ user: Schema.Struct({
+ login: Schema.optional(Schema.String),
+ email: Schema.optional(Schema.NullOr(Schema.String)),
+ }),
+});
+const SandboxResponse = Schema.Struct({ sandbox: BoatSandbox });
+const SandboxList = Schema.Struct({ sandboxes: Schema.Array(BoatSandbox) });
+const CommandResult = Schema.Struct({
+ exitCode: Schema.NullOr(Schema.Number),
+ stdout: Schema.optional(Schema.String),
+ stderr: Schema.optional(Schema.String),
+ timedOut: Schema.optional(Schema.Boolean),
+});
+export type BoatCommandResult = typeof CommandResult.Type;
+const FileUrl = Schema.Struct({ url: Schema.String });
+const HostResponse = Schema.Struct({ url: Schema.String });
+const SavedSnapshot = Schema.Struct({
+ name: Schema.String,
+ status: Schema.String,
+ /** The VM it was saved from. A save under the same name replaces it. */
+ sourceSandboxId: Schema.optional(Schema.NullOr(Schema.String)),
+ /** When the name was first saved; a later save under it keeps this. */
+ createdAt: Schema.optional(Schema.NullOr(Schema.String)),
+});
+export type BoatSnapshot = typeof SavedSnapshot.Type;
+const SavedSnapshotList = Schema.Struct({ snapshots: Schema.Array(SavedSnapshot) });
+
+// Commands right after a create or resume can land while the VM mounts its files.
+const transientRetry = Schedule.spaced(Duration.seconds(2));
+
+export function makeBoatApi(http: HttpClient.HttpClient, apiKey: string) {
+ const fail = (response: HttpClientResponse.HttpClientResponse) =>
+ response.json.pipe(
+ Effect.orElseSucceed((): unknown => undefined),
+ Effect.flatMap((json) => {
+ const body = decodeErrorBody(json);
+ const parsed = body._tag === "Some" ? body.value : undefined;
+ const code = parsed?.code ?? `http_${response.status}`;
+ const retryable =
+ code === "sandbox_starting" ||
+ code === "sandbox_resuming" ||
+ parsed?.error?.details?.message === "sandbox_restoring" ||
+ (code === "sandbox_direct_failed" && parsed?.error?.details?.retryable === true) ||
+ response.status === 503;
+ return Effect.fail(
+ new BoatApiError({
+ status: response.status,
+ code,
+ message:
+ parsed?.code === undefined
+ ? `Boat answered ${response.status}.`
+ : `Boat answered ${response.status}: ${parsed.code}.`,
+ retryable,
+ cause: json,
+ }),
+ );
+ }),
+ );
+
+ const send = (
+ request: HttpClientRequest.HttpClientRequest,
+ schema: Schema.Codec,
+ timeout: Duration.Input = Duration.seconds(30),
+ ) =>
+ http.execute(HttpClientRequest.bearerToken(request, apiKey)).pipe(
+ Effect.mapError(
+ (cause) =>
+ new BoatApiError({
+ status: 0,
+ code: "network",
+ message: "Could not reach Boat.",
+ retryable: true,
+ cause,
+ }),
+ ),
+ Effect.flatMap((response) =>
+ response.status >= 200 && response.status < 300
+ ? response.json.pipe(
+ Effect.flatMap(Schema.decodeUnknownEffect(schema)),
+ Effect.mapError(
+ (cause) =>
+ new BoatApiError({
+ status: response.status,
+ code: "invalid_response",
+ message: "Boat returned an unexpected response.",
+ retryable: false,
+ cause,
+ }),
+ ),
+ )
+ : fail(response),
+ ),
+ Effect.timeoutOrElse({
+ duration: timeout,
+ orElse: () =>
+ Effect.fail(
+ new BoatApiError({
+ status: 0,
+ code: "timeout",
+ message: "Boat did not answer in time.",
+ retryable: false,
+ }),
+ ),
+ }),
+ );
+ const url = (path: string) => `${BOAT_API_URL}${path}`;
+ const json = (method: "POST" | "PUT" | "PATCH", path: string, body: unknown) =>
+ HttpClientRequest.make(method)(url(path)).pipe(HttpClientRequest.bodyJsonUnsafe(body));
+ const retryTransient = (
+ effect: Effect.Effect,
+ retryable = (error: BoatApiError) => error.retryable,
+ ) => effect.pipe(Effect.retry({ schedule: transientRetry, times: 15, while: retryable }));
+ const orNull = (effect: Effect.Effect) =>
+ effect.pipe(
+ Effect.catchIf(
+ (error) => error.status === 404,
+ () => Effect.succeed(null),
+ ),
+ );
+
+ return {
+ me: () =>
+ send(HttpClientRequest.get(url("/me")), Me).pipe(
+ Effect.map((me) => me.user.email ?? me.user.login ?? "Boat account"),
+ ),
+ listSandboxes: (label: string) =>
+ send(
+ HttpClientRequest.get(url("/sandboxes")).pipe(
+ HttpClientRequest.setUrlParam("label", label),
+ HttpClientRequest.setUrlParam("limit", "200"),
+ ),
+ SandboxList,
+ ).pipe(Effect.map((list) => list.sandboxes)),
+ getSandbox: (id: string) =>
+ orNull(
+ send(HttpClientRequest.get(url(`/sandboxes/${id}`)), SandboxResponse).pipe(
+ Effect.map((response) => response.sandbox),
+ ),
+ ),
+ createSandbox: (body: {
+ readonly name: string;
+ readonly type?: BoatMachineType;
+ readonly labels: Readonly>;
+ readonly from?: string;
+ /** Boat stops the VM this long after it starts unless something extends it. */
+ readonly ttlSeconds: number;
+ /** An environment name; Boat's default environment when absent. */
+ readonly environment?: string;
+ }) =>
+ send(json("POST", "/sandboxes", body), SandboxResponse, Duration.minutes(5)).pipe(
+ Effect.map((response) => response.sandbox),
+ ),
+ /** `type` resizes the VM as it starts; absent keeps its size. */
+ resume: (id: string, ttlSeconds: number, type?: BoatMachineType) =>
+ send(
+ json(
+ "POST",
+ `/sandboxes/${id}/resume`,
+ type === undefined ? { ttlSeconds } : { ttlSeconds, type },
+ ),
+ SandboxResponse,
+ Duration.minutes(5),
+ ),
+ rename: (id: string, name: string) =>
+ send(json("PATCH", `/sandboxes/${id}`, { name }), Schema.Unknown),
+ /** Moves the auto-stop deadline to now plus `ttlSeconds`. */
+ extend: (id: string, ttlSeconds: number) =>
+ send(json("PATCH", `/sandboxes/${id}`, { ttlSeconds }), Schema.Unknown),
+ stop: (id: string) => send(json("POST", `/sandboxes/${id}/stop`, {}), Schema.Unknown),
+ delete: (id: string) =>
+ orNull(
+ send(
+ HttpClientRequest.delete(url(`/sandboxes/${id}`)).pipe(
+ HttpClientRequest.setHeader("X-Ascii-Confirm-Delete", id),
+ ),
+ Schema.Unknown,
+ ),
+ ),
+ exec: (id: string, command: string, timeoutSeconds = 60) =>
+ retryTransient(
+ send(
+ json("POST", `/sandboxes/${id}/commands`, { command, timeoutSeconds }),
+ CommandResult,
+ Duration.seconds(timeoutSeconds + 30),
+ ),
+ // A dropped connection may follow a command Boat already ran, and commands are not idempotent.
+ (error) => error.retryable && error.code !== "network",
+ ),
+ writeFile: (id: string, path: string, content: string) =>
+ retryTransient(
+ send(json("PUT", `/sandboxes/${id}/files`, { path, content }), Schema.Unknown),
+ ),
+ host: (id: string, port: number) =>
+ send(
+ json("POST", `/sandboxes/${id}/host`, { port, public: true, localhost: true }),
+ HostResponse,
+ ).pipe(Effect.map((response) => response.url)),
+ /** A signed URL that takes a PUT of the file's bytes, with no size limit. */
+ uploadUrl: (id: string, path: string) =>
+ retryTransient(
+ send(json("POST", `/sandboxes/${id}/files/upload-url`, { path }), FileUrl),
+ ).pipe(Effect.map((response) => response.url)),
+ /** A signed URL that serves the file with a GET. */
+ downloadUrl: (id: string, path: string) =>
+ retryTransient(
+ send(json("POST", `/sandboxes/${id}/files/download-url`, { path }), FileUrl),
+ ).pipe(Effect.map((response) => response.url)),
+ saveSnapshot: (sandboxId: string, name: string) =>
+ send(json("POST", "/saved-snapshots", { sandboxId, name }), Schema.Unknown),
+ listSnapshots: () =>
+ send(HttpClientRequest.get(url("/saved-snapshots")), SavedSnapshotList).pipe(
+ Effect.map((list) => list.snapshots),
+ ),
+ deleteSnapshot: (name: string) =>
+ orNull(
+ send(
+ HttpClientRequest.delete(url(`/saved-snapshots/${name}`)).pipe(
+ HttpClientRequest.setHeader("X-Ascii-Confirm-Delete", name),
+ ),
+ Schema.Unknown,
+ ),
+ ),
+ listEnvironments: () =>
+ send(HttpClientRequest.get(url("/environments")), EnvironmentList).pipe(
+ Effect.map((list) => list.environments),
+ ),
+ listCredentialProfiles: () =>
+ send(HttpClientRequest.get(url("/credential-profiles")), CredentialProfileList).pipe(
+ Effect.map((list) => list.profiles),
+ ),
+ /** A change makes a new environment version, which only VMs started after it get. */
+ updateEnvironment: (
+ id: string,
+ body: Partial<
+ Pick<
+ BoatEnvironment,
+ "passGithub" | "passSandboxCredentials" | "passSecrets" | "passAgentsCredentials"
+ >
+ >,
+ ) => send(json("PUT", `/environments/${id}`, body), Schema.Unknown),
+ /** For a response from a signed URL, in Boat's error shape. */
+ fail,
+ };
+}
+export type BoatApi = ReturnType;
diff --git a/packages/shared/src/boatCloudStart.test.ts b/packages/shared/src/boatCloudStart.test.ts
new file mode 100644
index 0000000000000..8f23753ed4a4f
--- /dev/null
+++ b/packages/shared/src/boatCloudStart.test.ts
@@ -0,0 +1,259 @@
+import { assert, describe, it } from "@effect/vitest";
+import { EnvironmentId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import { HttpClient, HttpClientResponse } from "effect/http";
+
+import { makeBoatApi } from "./boatCloudApi.ts";
+import {
+ latestCliRelease,
+ makeSpareKeeper,
+ needsSnapshot,
+ type ReadySpare,
+ startingSnapshot,
+ startMachine,
+} from "./boatCloudStart.ts";
+import {
+ NOT_HOSTED_MARKER,
+ PAIRING_MARKER,
+ SNAPSHOT_LABEL,
+ SPARE_NAME,
+ parseRepository,
+} from "./boatCloudVm.ts";
+
+const repository = parseRepository("https://github.com/acme/app")!;
+const SNAPSHOT = "t3-code-0-1-9-boat-1";
+const SUBDOMAIN = "box-node-1";
+const VM_URL = `https://${SUBDOMAIN}-3773.on.boat.dev`;
+
+/**
+ * Boat with one running, lightly loaded VM whose server answers as `serverEnvironmentId`.
+ * Calls are recorded as `METHOD path`, a PATCH with its fields, a command by what it runs.
+ * A created VM is `vm-2`, and a renamed one is listed under its new name.
+ */
+const runningVm = (
+ serverEnvironmentId: string,
+ vm: { spare?: boolean; hostsItself?: boolean } = {},
+) => {
+ const calls: Array = [];
+ const commands: Array = [];
+ const names = new Map([["vm-1", vm.spare ? SPARE_NAME : "Boat cloud"]]);
+ const listed = (id: string) => ({
+ id,
+ state: "ready",
+ subdomain: id === "vm-1" ? SUBDOMAIN : `box-${id}`,
+ environment: "base",
+ name: names.get(id),
+ labels: { [SNAPSHOT_LABEL]: SNAPSHOT },
+ });
+ const http = HttpClient.make((request) =>
+ Effect.sync(() => {
+ const path = new URL(request.url).pathname.replace("/api/v1", "");
+ const body =
+ request.body._tag === "Uint8Array"
+ ? (JSON.parse(new TextDecoder().decode(request.body.body)) as Record)
+ : {};
+ const reply = (json: unknown) => HttpClientResponse.fromWeb(request, Response.json(json));
+ const command = /^\/sandboxes\/([^/]+)\/commands$/u.exec(path);
+ if (!command) {
+ calls.push(
+ request.method === "PATCH"
+ ? `PATCH ${path} ${Object.keys(body).join(",")}`
+ : `${request.method} ${path}`,
+ );
+ }
+ if (path === "/sandboxes" && request.method === "POST") {
+ names.set("vm-2", String(body.name));
+ return reply({ sandbox: listed("vm-2") });
+ }
+ if (path === "/sandboxes") return reply({ sandboxes: [...names.keys()].map(listed) });
+ const id = /^\/sandboxes\/([^/]+)/u.exec(path)?.[1] ?? "";
+ if (request.method === "PATCH" && typeof body.name === "string") names.set(id, body.name);
+ if (path === `/sandboxes/${id}` && request.method === "GET") {
+ return reply({ sandbox: listed(id) });
+ }
+ if (path.endsWith("/host")) return reply({ url: `${VM_URL}/` });
+ if (!command) return reply({});
+ const script = typeof body.command === "string" ? body.command : "";
+ commands.push(script);
+ const descriptor = JSON.stringify({ environmentId: serverEnvironmentId });
+ const pairing = JSON.stringify({
+ credential: "fresh-code",
+ expiresAt: "2999-01-01T00:00:00.000Z",
+ });
+ let stdout = "";
+ if (script.includes("/proc/loadavg")) {
+ calls.push("exec measure");
+ stdout = "0.1 1000 900\n";
+ } else if (script.includes("systemctl --user start t3code.service")) {
+ calls.push("exec server");
+ const head = vm.hostsItself === false ? `${NOT_HOSTED_MARKER}\n${descriptor}` : descriptor;
+ stdout = script.includes(PAIRING_MARKER) ? `${head}\n${PAIRING_MARKER}\n${pairing}` : head;
+ } else if (script.includes("auth pairing create")) stdout = pairing;
+ return reply({ exitCode: 0, stdout });
+ }),
+ );
+ return { api: makeBoatApi(http, "key"), calls, commands };
+};
+
+const start = (
+ vm: ReturnType,
+ pairedEnvironmentId: string | null,
+ readySpare: ReadySpare | null = null,
+) =>
+ startMachine({
+ api: vm.api,
+ repository,
+ baseBranch: null,
+ environment: "base",
+ snapshot: SNAPSHOT,
+ readySpare,
+ knownWorkspaceRoots: () => [],
+ paired:
+ pairedEnvironmentId === null
+ ? []
+ : [{ environmentId: EnvironmentId.make(pairedEnvironmentId), httpBaseUrl: VM_URL }],
+ report: () => Effect.void,
+ });
+
+describe("startMachine on a running VM", () => {
+ it.effect("reconnects a paired client without waiting on Boat, hosting or pairing", () =>
+ Effect.gen(function* () {
+ const vm = runningVm("env-1");
+ const started = yield* start(vm, "env-1");
+ yield* started.checkout;
+ assert.isNull(started.pairingCode);
+ assert.strictEqual(started.httpBaseUrl, VM_URL);
+ assert.deepStrictEqual(
+ vm.calls.filter((call) => !call.startsWith("exec ")),
+ ["GET /sandboxes", "PATCH /sandboxes/vm-1 ttlSeconds"],
+ );
+ assert.isFalse(vm.commands.some((command) => command.includes("auth pairing create")));
+ }),
+ );
+
+ it.effect("mints a code in the server command for a new client, or after the VM was reset", () =>
+ Effect.gen(function* () {
+ const fresh = runningVm("env-1");
+ assert.strictEqual((yield* start(fresh, null)).pairingCode, "fresh-code");
+ assert.strictEqual(
+ fresh.commands.filter((command) => command.includes("auth pairing create")).length,
+ 1,
+ );
+
+ const reset = runningVm("env-2");
+ assert.strictEqual((yield* start(reset, "env-1")).pairingCode, "fresh-code");
+ }),
+ );
+
+ it.effect("asks Boat to host the port only after the server started, when the VM could not", () =>
+ Effect.gen(function* () {
+ const vm = runningVm("env-1", { spare: true, hostsItself: false });
+ assert.strictEqual((yield* start(vm, null)).httpBaseUrl, VM_URL);
+ assert.include(vm.calls, "PATCH /sandboxes/vm-1 name");
+ const hosts = vm.calls.flatMap((call, index) =>
+ call === "POST /sandboxes/vm-1/host" ? [index] : [],
+ );
+ assert.strictEqual(hosts.length, 1);
+ assert.isAbove(hosts[0]!, vm.calls.indexOf("exec server"));
+ }),
+ );
+});
+
+describe("the ready spare", () => {
+ const keep = (vm: ReturnType, keeper: ReturnType) =>
+ keeper.keep(vm.api, SNAPSHOT, "base");
+
+ it.effect(
+ "is handed out before Boat hears of the start, and claimed alongside the checkout",
+ () =>
+ Effect.gen(function* () {
+ const vm = runningVm("env-1", { spare: true });
+ const keeper = makeSpareKeeper();
+ yield* keep(vm, keeper);
+ const spare = yield* keeper.take(SNAPSHOT, "base");
+ assert.strictEqual(spare?.sandboxId, "vm-1");
+ vm.calls.length = 0;
+
+ const started = yield* start(vm, null, spare);
+ assert.strictEqual(started.pairingCode, "fresh-code");
+ assert.strictEqual(started.httpBaseUrl, VM_URL);
+ assert.deepStrictEqual(
+ vm.calls.filter((call) => call !== "exec server" && call.startsWith("exec ")),
+ [],
+ );
+ yield* started.checkout;
+ assert.includeMembers(vm.calls, [
+ "PATCH /sandboxes/vm-1 name",
+ "PATCH /sandboxes/vm-1 ttlSeconds",
+ ]);
+ assert.notInclude(vm.calls, "GET /sandboxes");
+ }),
+ );
+
+ it.effect("goes to one start only, even while Boat still lists it as the spare", () =>
+ Effect.gen(function* () {
+ const vm = runningVm("env-1", { spare: true });
+ const keeper = makeSpareKeeper();
+ yield* keep(vm, keeper);
+ assert.strictEqual((yield* keeper.take(SNAPSHOT, "base"))?.sandboxId, "vm-1");
+ assert.isNull(yield* keeper.take(SNAPSHOT, "base"));
+
+ // The refill reads Boat's list before the start's rename lands.
+ yield* keep(vm, keeper);
+ assert.notInclude(vm.calls, "DELETE /sandboxes/vm-1");
+ assert.strictEqual((yield* keeper.take(SNAPSHOT, "base"))?.sandboxId, "vm-2");
+ }),
+ );
+
+ it.effect("is forgotten once Boat lists it taken by another holder", () =>
+ Effect.gen(function* () {
+ const vm = runningVm("env-1", { spare: true });
+ const keeper = makeSpareKeeper();
+ yield* keep(vm, keeper);
+ yield* vm.api.rename("vm-1", "Boat cloud");
+ keeper.reconcile(yield* vm.api.listSandboxes("t3code=cloud"));
+ assert.isNull(yield* keeper.take(SNAPSHOT, "base"));
+ }),
+ );
+});
+
+describe("latestCliRelease", () => {
+ const github = (tag: string) =>
+ HttpClient.make((request) =>
+ Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ tag_name: tag }))),
+ );
+
+ it.effect("finds the fork's build and refuses a latest release that is not one", () =>
+ Effect.gen(function* () {
+ assert.strictEqual(yield* latestCliRelease(github("boat-cli-v0.1.9-boat.1")), "0.1.9-boat.1");
+ for (const tag of ["v0.1.9", "boat-cli-v0.1.9;reboot", "boat-cli-v1.2"]) {
+ const error = yield* Effect.flip(latestCliRelease(github(tag)));
+ assert.strictEqual(error.code, "cli_release");
+ }
+ }),
+ );
+});
+
+describe("snapshot choice", () => {
+ const saved = (name: string, status: string, createdAt: string) => ({ name, status, createdAt });
+ const old = saved("t3-code-0-1-9-boat-1-skills", "ready", "2026-11-01T00:00:00Z");
+
+ it("starts VMs from the newest ready snapshot, the previous one while the next saves", () => {
+ const next = saved("t3-code-0-1-9-boat-2", "ready", "2026-11-02T00:00:00Z");
+ assert.strictEqual(startingSnapshot([old, next]), next.name);
+ assert.strictEqual(startingSnapshot([old, { ...next, status: "saving" }]), old.name);
+ assert.isNull(startingSnapshot([saved("other", "ready", "2026-11-03T00:00:00Z")]));
+ });
+
+ it("saves each build once, and only a holder with skills replaces one saved without", () => {
+ const plain = saved("t3-code-0-1-9-boat-2", "ready", "2026-11-02T00:00:00Z");
+ const skills = saved("t3-code-0-1-9-boat-2-skills", "saving", "2026-11-02T00:00:00Z");
+ for (const withSkills of [true, false]) {
+ assert.isTrue(needsSnapshot([old], "0.1.9-boat.2", withSkills));
+ assert.isFalse(needsSnapshot([skills], "0.1.9-boat.2", withSkills));
+ assert.isTrue(needsSnapshot([{ ...skills, status: "failed" }], "0.1.9-boat.2", withSkills));
+ }
+ assert.isTrue(needsSnapshot([plain], "0.1.9-boat.2", true));
+ assert.isFalse(needsSnapshot([plain], "0.1.9-boat.2", false));
+ });
+});
diff --git a/packages/shared/src/boatCloudStart.ts b/packages/shared/src/boatCloudStart.ts
new file mode 100644
index 0000000000000..d7708e18b01d7
--- /dev/null
+++ b/packages/shared/src/boatCloudStart.ts
@@ -0,0 +1,914 @@
+import {
+ type BoatCloudSetupStep,
+ type BoatCloudStartStep,
+ type BoatCloudStepProgress,
+ EnvironmentId,
+} from "@t3tools/contracts";
+import * as Clock from "effect/Clock";
+import * as Duration from "effect/Duration";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as Option from "effect/Option";
+import * as Random from "effect/Random";
+import * as Schedule from "effect/Schedule";
+import * as Schema from "effect/Schema";
+import { type HttpClient, HttpClientResponse } from "effect/http";
+
+import {
+ type BoatApi,
+ BoatApiError,
+ type BoatCommandResult,
+ type BoatSandbox,
+ type BoatSnapshot,
+} from "./boatCloudApi.ts";
+import {
+ BASE_BRANCH_MISSING_EXIT,
+ CLI_RELEASE_REPOSITORY,
+ IDLE_TTL_SECONDS,
+ type MachineCandidate,
+ MACHINE_LABEL_FILTER,
+ MACHINE_LABELS,
+ MACHINE_NAME,
+ NOT_HOSTED_MARKER,
+ PAIRING_MARKER,
+ type ParsedRepository,
+ type PreparedWorktree,
+ SNAPSHOT_LABEL,
+ SPARE_NAME,
+ SPARE_TTL_SECONDS,
+ SETUP_LABEL_FILTER,
+ SETUP_LABELS,
+ VM_T3_PORT,
+ checkoutScript,
+ cliVersionOfTag,
+ cloneRepositoriesScript,
+ installCliScript,
+ isBoatCloudSnapshot,
+ machineLabelOf,
+ machineStateOf,
+ measureScript,
+ parseMeasure,
+ pairScript,
+ parkWorktreesScript,
+ parseRepository,
+ pickMachine,
+ prepareSnapshotScript,
+ snapshotNameOf,
+ startServerScript,
+ stockPairingScript,
+ subdomainOfHttpBaseUrl,
+ worktreePathOf,
+} from "./boatCloudVm.ts";
+import { buildTemporaryWorktreeBranchName } from "./git.ts";
+
+/**
+ * Getting a Boat cloud VM ready for a thread. Every holder of the Boat key runs
+ * these: a server for the clients connected to it, or the phone on its own.
+ */
+
+const decodeDescriptor = Schema.decodeUnknownOption(
+ Schema.fromJsonString(Schema.Struct({ environmentId: EnvironmentId })),
+);
+const decodePairing = Schema.decodeUnknownOption(
+ Schema.fromJsonString(Schema.Struct({ credential: Schema.String, expiresAt: Schema.String })),
+);
+
+export const vmFailure = (message: string, code = "vm", cause?: unknown) =>
+ new BoatApiError({ status: 0, code, message, retryable: false, cause });
+
+/** The command's output stays in `cause`; `failure` names what did not work. */
+const commandFailure = (result: BoatCommandResult, failure?: string) =>
+ vmFailure(
+ failure ??
+ (result.timedOut
+ ? "A command on the VM timed out."
+ : `A command on the VM exited with ${result.exitCode}.`),
+ "vm",
+ result,
+ );
+
+export const exec = (
+ api: BoatApi,
+ sandboxId: string,
+ script: string,
+ timeoutSeconds = 120,
+ failure?: string,
+) =>
+ api
+ .exec(sandboxId, script, timeoutSeconds)
+ .pipe(
+ Effect.flatMap((result) =>
+ result.exitCode === 0
+ ? Effect.succeed(result.stdout ?? "")
+ : Effect.fail(commandFailure(result, failure)),
+ ),
+ );
+
+export const waitRunning = (api: BoatApi, sandboxId: string) =>
+ api.getSandbox(sandboxId).pipe(
+ Effect.flatMap((sandbox) => {
+ if (sandbox === null) return Effect.fail(vmFailure("The VM no longer exists.", "gone"));
+ if (machineStateOf(sandbox.state) === "running") return Effect.succeed(sandbox);
+ return Effect.fail(vmFailure(`The VM is still ${sandbox.state}.`, "starting"));
+ }),
+ Effect.retry({
+ schedule: Schedule.spaced(Duration.millis(250)),
+ times: 1200,
+ while: (error) => error.code === "starting",
+ }),
+ );
+
+const PAIRING_LABEL = "Boat cloud";
+
+const pairingOf = (output: string) =>
+ Option.match(decodePairing(output), {
+ onNone: () => Effect.fail(vmFailure("T3 Code on the VM did not issue a pairing code.")),
+ onSome: (pairing) =>
+ Effect.succeed({ code: pairing.credential, expiresAt: Date.parse(pairing.expiresAt) }),
+ });
+
+/**
+ * Starts the server and, when asked, mints a pairing code good for at least `minutes` in
+ * the same command. `hosted` is false when the VM could not serve its port by itself.
+ */
+const startServer = Effect.fn("BoatCloud.startServer")(function* (
+ api: BoatApi,
+ sandboxId: string,
+ pair: boolean,
+ minutes?: number,
+) {
+ const output = yield* exec(
+ api,
+ sandboxId,
+ startServerScript(pair ? PAIRING_LABEL : null, minutes),
+ 90,
+ "T3 Code did not start on the VM.",
+ );
+ const markerAt = output.indexOf(PAIRING_MARKER);
+ const head = markerAt === -1 ? output : output.slice(0, markerAt);
+ const hosted = !head.includes(NOT_HOSTED_MARKER);
+ const descriptor = decodeDescriptor(head.replace(NOT_HOSTED_MARKER, "").trim());
+ if (Option.isNone(descriptor)) {
+ return yield* vmFailure("T3 Code on the VM did not describe itself.");
+ }
+ const pairing = pair ? yield* pairingOf(output.slice(markerAt + PAIRING_MARKER.length)) : null;
+ return { environmentId: descriptor.value.environmentId, pairing, hosted };
+});
+
+const ensureServer = (api: BoatApi, sandboxId: string) =>
+ startServer(api, sandboxId, false).pipe(Effect.map((started) => started.environmentId));
+
+/** Boat routes a hosted port only when it is registered after the server listens on it. */
+const hostServer = (api: BoatApi, sandboxId: string) =>
+ api.host(sandboxId, VM_T3_PORT).pipe(
+ Effect.map((url) => {
+ const parsed = new URL(url);
+ return `${parsed.protocol}//${parsed.host}`;
+ }),
+ );
+
+const pair = (api: BoatApi, sandboxId: string) =>
+ exec(
+ api,
+ sandboxId,
+ pairScript(PAIRING_LABEL),
+ 60,
+ "T3 Code on the VM did not issue a pairing code.",
+ ).pipe(
+ Effect.flatMap(pairingOf),
+ Effect.map((pairing) => pairing.code),
+ );
+
+/** Where Boat serves the port the VM hosted, asking Boat to host it only when the VM could not. */
+const serverUrl = (api: BoatApi, sandbox: BoatSandbox, hosted: boolean) =>
+ hosted && sandbox.subdomain
+ ? Effect.succeed(`https://${sandbox.subdomain}-${VM_T3_PORT}.on.boat.dev`)
+ : hostServer(api, sandbox.id);
+
+const GIT_AUTH_FAILURE = /could not read Username|Authentication failed|Repository not found/u;
+
+/**
+ * Gets the checkout and adds it as a project. Boat clones with the GitHub access set
+ * up in its dashboard; without it git only says it cannot log in.
+ */
+const checkout = (
+ api: BoatApi,
+ sandboxId: string,
+ repository: ParsedRepository,
+ baseBranch: string | null,
+ worktree: PreparedWorktree | null,
+) =>
+ api.exec(sandboxId, checkoutScript(repository, baseBranch, worktree), 600).pipe(
+ Effect.flatMap((result) => {
+ if (result.exitCode === 0) return Effect.void;
+ if (baseBranch !== null && result.exitCode === BASE_BRANCH_MISSING_EXIT) {
+ return Effect.fail(
+ vmFailure(
+ `${baseBranch} is not on ${repository.name}. Push it, or start from a pushed branch.`,
+ "base_branch",
+ result,
+ ),
+ );
+ }
+ if (GIT_AUTH_FAILURE.test(result.stderr ?? "")) {
+ return Effect.fail(
+ vmFailure(
+ `Boat cannot clone ${repository.name}. Connect GitHub in the Boat dashboard, under Environments.`,
+ "clone",
+ result,
+ ),
+ );
+ }
+ return Effect.fail(commandFailure(result, `Could not get ${repository.name} on the VM.`));
+ }),
+ );
+
+export type ReportStep = (
+ step: BoatCloudStartStep,
+ state: BoatCloudStepProgress["state"],
+ detail: string | null,
+) => Effect.Effect;
+
+const runStep = (
+ report: ReportStep,
+ step: BoatCloudStartStep,
+ detail: string | null,
+ effect: Effect.Effect,
+) =>
+ report(step, "active", detail).pipe(
+ Effect.andThen(effect),
+ Effect.tapError(() => report(step, "failed", detail)),
+ Effect.tap(() => report(step, "done", detail)),
+ );
+
+export interface StartedMachine {
+ readonly sandboxId: string;
+ readonly environmentId: EnvironmentId;
+ readonly httpBaseUrl: string;
+ /** Null when the client already paired with this VM and only reconnects. */
+ readonly pairingCode: string | null;
+ readonly workspaceRoot: string;
+ /** The thread's worktree, ready once `checkout` is; null without a base branch. */
+ readonly worktree: PreparedWorktree | null;
+ readonly created: boolean;
+ /** The checkout, the worktree and the project, still running: the client connects meanwhile. */
+ readonly checkout: Effect.Effect;
+}
+
+/** A VM the client already paired with, by the URL it reaches it at. */
+export interface PairedEnvironment {
+ readonly environmentId: EnvironmentId;
+ readonly httpBaseUrl: string;
+}
+
+/**
+ * A running spare with its server up, hosted, and a pairing code the holder took for it,
+ * so a start hands it out with no call to Boat.
+ */
+export interface ReadySpare {
+ readonly sandboxId: string;
+ readonly environmentId: EnvironmentId;
+ readonly httpBaseUrl: string;
+ readonly pairingCode: string;
+ readonly snapshot: string;
+ readonly environment: string | null;
+ /** Epoch milliseconds the pairing code expires at. */
+ readonly codeExpiresAt: number;
+ /** Epoch milliseconds Boat may stop the VM from. */
+ readonly stopsAt: number;
+}
+
+interface StartMachineInput {
+ readonly api: BoatApi;
+ readonly repository: ParsedRepository;
+ /** The thread's base branch, which must be on the remote. */
+ readonly baseBranch: string | null;
+ /** The Boat environment a new VM starts on and a reused one must already run; Boat's default when null. */
+ readonly environment: string | null;
+ /** The saved snapshot a new VM starts from, from `startingSnapshot`. */
+ readonly snapshot: string;
+ /** The spare the holder took from its `makeSpareKeeper`; the start then asks Boat nothing first. */
+ readonly readySpare?: ReadySpare | null;
+ /** Boat's list of VMs, when the caller just read it. */
+ readonly sandboxes?: ReadonlyArray;
+ /** Checkouts the holder remembers on stopped VMs, which cannot be asked. */
+ readonly knownWorkspaceRoots: (sandboxId: string) => ReadonlyArray;
+ readonly paired?: ReadonlyArray;
+ readonly report: ReportStep;
+ /** Runs once a VM joins the holder's machines: one it created, or the spare it took. */
+ readonly onAdded?: (sandboxId: string) => Effect.Effect;
+ /** Runs before an existing VM is resumed or reused, so an idle sweep leaves it on. */
+ readonly onReused?: (sandboxId: string) => Effect.Effect;
+}
+
+/**
+ * Cuts the thread's worktree name and starts the checkout, together with `alongside`.
+ * Its failure carries the reason, since the client learns it from the step alone.
+ */
+const startCheckout = Effect.fn("BoatCloud.startCheckout")(function* (
+ input: StartMachineInput,
+ sandboxId: string,
+ alongside: Effect.Effect = Effect.void,
+) {
+ const { api, repository, report } = input;
+ // The same temporary name T3 gives a new worktree, so the server renames it after the first message.
+ const worktree: PreparedWorktree | null =
+ input.baseBranch === null
+ ? null
+ : yield* Effect.map(Random.next, (random) => {
+ const branch = buildTemporaryWorktreeBranchName(() =>
+ Math.floor(random * 0x1_0000_0000)
+ .toString(16)
+ .padStart(8, "0"),
+ );
+ return {
+ path: worktreePathOf(repository, branch),
+ branch,
+ baseBranch: input.baseBranch!,
+ };
+ });
+ const fiber = yield* report("repository", "active", repository.name).pipe(
+ Effect.andThen(checkout(api, sandboxId, repository, input.baseBranch, worktree)),
+ Effect.tap(() => report("repository", "done", repository.name)),
+ Effect.tapError((error) => report("repository", "failed", error.message)),
+ (effect) => Effect.all([effect, alongside], { concurrency: 2, discard: true }),
+ Effect.forkDetach,
+ );
+ return { worktree, fiber };
+});
+
+/**
+ * Hands out the spare the holder holds. The rename that tells other holders it is taken,
+ * and the thread's deadline, go to Boat alongside the checkout, after the client has
+ * what it needs to connect.
+ */
+const handOutSpare = Effect.fn("BoatCloud.handOutSpare")(function* (
+ input: StartMachineInput,
+ spare: ReadySpare,
+) {
+ const { api, report } = input;
+ const { sandboxId } = spare;
+ yield* report("machine", "done", "Using a ready VM");
+ if (input.onAdded) yield* input.onAdded(sandboxId);
+ if (input.onReused) yield* input.onReused(sandboxId);
+ const claim = Effect.all(
+ [api.rename(sandboxId, MACHINE_NAME), api.extend(sandboxId, IDLE_TTL_SECONDS)],
+ { concurrency: 2, discard: true },
+ ).pipe(
+ Effect.catchCause((cause) =>
+ Effect.logWarning("boat cloud could not claim the spare it handed out", { sandboxId, cause }),
+ ),
+ );
+ const { worktree, fiber } = yield* startCheckout(input, sandboxId, claim);
+ yield* report("server", "done", null);
+ return {
+ sandboxId,
+ environmentId: spare.environmentId,
+ httpBaseUrl: spare.httpBaseUrl,
+ pairingCode: spare.pairingCode,
+ workspaceRoot: input.repository.workspaceRoot,
+ worktree,
+ created: false,
+ checkout: Fiber.join(fiber),
+ } satisfies StartedMachine;
+});
+
+/**
+ * Hands out the holder's ready spare, else picks a VM (a free running one or the spare, a
+ * stopped one, a new one) and starts its server while the checkout runs. Returns once the
+ * server answers: a paired client reconnects, any other gets a code, the checkout carries on.
+ */
+export const startMachine = Effect.fn("BoatCloud.startMachine")(function* (
+ input: StartMachineInput,
+) {
+ if (input.readySpare) return yield* handOutSpare(input, input.readySpare);
+ const { api, repository, report } = input;
+ yield* report("machine", "active", "Looking for a VM");
+ const { choice, sandboxes } = yield* Effect.gen(function* () {
+ const sandboxes = input.sandboxes ?? (yield* api.listSandboxes(MACHINE_LABEL_FILTER));
+ const candidates = yield* Effect.forEach(
+ sandboxes.filter((sandbox) => machineStateOf(sandbox.state) !== "starting"),
+ (sandbox): Effect.Effect => {
+ const running = machineStateOf(sandbox.state) === "running";
+ const environment = sandbox.environment ?? null;
+ const spare = sandbox.name === SPARE_NAME;
+ if (!running) {
+ return Effect.succeed({
+ sandboxId: sandbox.id,
+ environment,
+ running,
+ usage: null,
+ workspaceRoots: input.knownWorkspaceRoots(sandbox.id),
+ spare,
+ });
+ }
+ // The load decides between sharing this VM and starting another, even when it is the only one.
+ return exec(api, sandbox.id, measureScript(repository.workspaceRoot), 20).pipe(
+ Effect.map(parseMeasure),
+ Effect.orElseSucceed(() => null),
+ Effect.map((measure) => ({
+ sandboxId: sandbox.id,
+ environment,
+ running,
+ usage: measure?.usage ?? null,
+ workspaceRoots: measure?.workspaceRoots ?? [],
+ spare,
+ })),
+ );
+ },
+ { concurrency: 8 },
+ );
+ return {
+ choice: pickMachine(candidates, repository.workspaceRoot, input.environment),
+ sandboxes,
+ };
+ }).pipe(Effect.tapError(() => report("machine", "failed", "Looking for a VM")));
+
+ const spare =
+ choice.kind !== "create" &&
+ sandboxes.find((listed) => listed.id === choice.sandboxId)?.name === SPARE_NAME;
+ const machineDetail =
+ choice.kind === "create"
+ ? "Creating a VM from the snapshot"
+ : choice.kind === "resume"
+ ? `Resuming ${machineLabelOf(choice.sandboxId)}`
+ : spare
+ ? "Using a ready VM"
+ : `Using ${machineLabelOf(choice.sandboxId)}`;
+ const runningSpare = spare && choice.kind === "use";
+ const join = Effect.fn("BoatCloud.joinMachine")(function* (sandboxId: string) {
+ if (spare) {
+ // The name is all that marks a spare, so no other holder takes it from here on.
+ yield* api.rename(sandboxId, MACHINE_NAME);
+ if (input.onAdded) yield* input.onAdded(sandboxId);
+ }
+ if (input.onReused) yield* input.onReused(sandboxId);
+ });
+ const sandbox = yield* runStep(
+ report,
+ "machine",
+ machineDetail,
+ Effect.gen(function* () {
+ if (choice.kind === "create") {
+ const created = yield* api.createSandbox({
+ name: MACHINE_NAME,
+ // Several threads share a VM, so it gets the medium size.
+ type: "default",
+ labels: { ...MACHINE_LABELS, [SNAPSHOT_LABEL]: input.snapshot },
+ from: input.snapshot,
+ ttlSeconds: IDLE_TTL_SECONDS,
+ ...(input.environment === null ? {} : { environment: input.environment }),
+ });
+ if (input.onAdded) yield* input.onAdded(created.id);
+ return yield* waitRunning(api, created.id);
+ }
+ // A running spare joins alongside its server start below.
+ if (!runningSpare) yield* join(choice.sandboxId);
+ if (choice.kind === "resume") {
+ // No environment on resume: Boat keeps the VM on the one it started with. A small
+ // spare grows to the shared size here.
+ yield* api.resume(choice.sandboxId, IDLE_TTL_SECONDS, "default");
+ return yield* waitRunning(api, choice.sandboxId);
+ }
+ // Listed running a moment ago, so it needs no wait. The new deadline is set
+ // alongside the server start below.
+ return sandboxes.find((listed) => listed.id === choice.sandboxId)!;
+ }),
+ );
+ const sandboxId = sandbox.id;
+ const { worktree, fiber: checkoutFiber } = yield* startCheckout(input, sandboxId);
+
+ // A client paired with this VM reconnects with its saved credential, so it needs no new code.
+ const expected = sandbox.subdomain
+ ? (input.paired?.find(
+ (environment) => subdomainOfHttpBaseUrl(environment.httpBaseUrl) === sandbox.subdomain,
+ ) ?? null)
+ : null;
+ const server = yield* runStep(
+ report,
+ "server",
+ null,
+ Effect.gen(function* () {
+ // A reused VM may be minutes from its deadline; the new thread restarts it.
+ const [started] = yield* Effect.all(
+ [
+ startServer(api, sandboxId, expected === null),
+ choice.kind === "use" ? api.extend(sandboxId, IDLE_TTL_SECONDS) : Effect.void,
+ runningSpare ? join(sandboxId) : Effect.void,
+ ],
+ { concurrency: "unbounded" },
+ );
+ // Its state was reset since the client paired, so the saved credential no longer works.
+ const pairingCode =
+ expected !== null && started.environmentId !== expected.environmentId
+ ? yield* pair(api, sandboxId)
+ : (started.pairing?.code ?? null);
+ const httpBaseUrl = yield* serverUrl(api, sandbox, started.hosted);
+ return { environmentId: started.environmentId, pairingCode, httpBaseUrl };
+ }),
+ ).pipe(Effect.onError(() => Fiber.interrupt(checkoutFiber)));
+ return {
+ sandboxId,
+ environmentId: server.environmentId,
+ httpBaseUrl: server.httpBaseUrl,
+ pairingCode: server.pairingCode,
+ workspaceRoot: repository.workspaceRoot,
+ worktree,
+ created: choice.kind === "create",
+ checkout: Fiber.join(checkoutFiber),
+ } satisfies StartedMachine;
+});
+
+/** Both return at once and carry on in the background on the VM. */
+const warmSpareScript = `${stockPairingScript(PAIRING_LABEL)}
+${parkWorktreesScript}`;
+
+/** A held spare is handed out only while its code and its deadline last this much longer. */
+const HAND_OUT_MARGIN_MS = 2 * 60 * 1000;
+/** The code a holder takes for its spare outlives the spare's deadline by this much. */
+const HOLD_MINUTES = SPARE_TTL_SECONDS / 60 + 5;
+
+/**
+ * Keeps one small spare from the current snapshot and environment ready: server up, hosted,
+ * a code taken for the holder, worktrees parked. A held spare whose code outlasts the new
+ * deadline only gets the deadline. Other spares are removed.
+ */
+const ensureSpare = Effect.fn("BoatCloud.ensureSpare")(function* (input: {
+ readonly api: BoatApi;
+ readonly snapshot: string;
+ readonly environment: string | null;
+ /** The spare this holder holds a code for. */
+ readonly held: ReadySpare | null;
+ /** Spares this holder handed out that Boat may still list under the spare's name. */
+ readonly taken: ReadonlySet;
+}) {
+ const { api, held } = input;
+ const spares = (yield* api.listSandboxes(MACHINE_LABEL_FILTER)).filter(
+ (sandbox) => sandbox.name === SPARE_NAME && !input.taken.has(sandbox.id),
+ );
+ const fits = (sandbox: BoatSandbox) =>
+ sandbox.labels?.[SNAPSHOT_LABEL] === input.snapshot &&
+ (input.environment === null || sandbox.environment === input.environment);
+ const kept =
+ spares.find((sandbox) => sandbox.id === held?.sandboxId && fits(sandbox)) ??
+ spares.find(fits) ??
+ null;
+ yield* Effect.forEach(
+ spares.filter((sandbox) => sandbox !== kept),
+ (sandbox) => api.delete(sandbox.id),
+ { concurrency: "unbounded", discard: true },
+ );
+ const stopsAt = (yield* Clock.currentTimeMillis) + SPARE_TTL_SECONDS * 1000;
+ if (
+ kept !== null &&
+ held?.sandboxId === kept.id &&
+ machineStateOf(kept.state) === "running" &&
+ held.codeExpiresAt - stopsAt > HAND_OUT_MARGIN_MS
+ ) {
+ // A client just looked, so a start may follow: the parked worktrees catch up meanwhile.
+ yield* Effect.all(
+ [
+ api.extend(kept.id, SPARE_TTL_SECONDS),
+ exec(api, kept.id, warmSpareScript, 30).pipe(Effect.ignore),
+ ],
+ { concurrency: 2, discard: true },
+ );
+ return { ...held, stopsAt } satisfies ReadySpare;
+ }
+ let sandboxId: string;
+ if (kept === null) {
+ const created = yield* api.createSandbox({
+ name: SPARE_NAME,
+ type: "small",
+ labels: { ...MACHINE_LABELS, [SNAPSHOT_LABEL]: input.snapshot },
+ from: input.snapshot,
+ ttlSeconds: SPARE_TTL_SECONDS,
+ ...(input.environment === null ? {} : { environment: input.environment }),
+ });
+ sandboxId = created.id;
+ } else if (machineStateOf(kept.state) === "stopped") {
+ yield* api.resume(kept.id, SPARE_TTL_SECONDS);
+ sandboxId = kept.id;
+ } else {
+ // Running, or starting under the holder that made it.
+ yield* api.extend(kept.id, SPARE_TTL_SECONDS);
+ sandboxId = kept.id;
+ }
+ const sandbox = yield* waitRunning(api, sandboxId);
+ const started = yield* startServer(api, sandboxId, true, HOLD_MINUTES);
+ const pairing =
+ started.pairing ?? (yield* vmFailure("T3 Code on the VM did not issue a pairing code."));
+ const [httpBaseUrl] = yield* Effect.all(
+ [serverUrl(api, sandbox, started.hosted), exec(api, sandboxId, warmSpareScript, 30)],
+ { concurrency: 2 },
+ );
+ return {
+ sandboxId,
+ environmentId: started.environmentId,
+ httpBaseUrl,
+ pairingCode: pairing.code,
+ snapshot: input.snapshot,
+ environment: input.environment,
+ codeExpiresAt: pairing.expiresAt,
+ stopsAt,
+ } satisfies ReadySpare;
+});
+
+/**
+ * One holder's spare, kept ready in the background and remembered, so a start takes it
+ * without asking Boat what is free. Boat's list, whenever the holder reads it, drops a
+ * spare another holder took, or that stopped or went away.
+ */
+export const makeSpareKeeper = () => {
+ let ready: ReadySpare | null = null;
+ const taken = new Set();
+ let keeping = false;
+ /** A keep asked for while one ran, run once that one ends since a start may have taken its spare. */
+ let queued: Effect.Effect | null = null;
+
+ const keep = (api: BoatApi, snapshot: string, environment: string | null): Effect.Effect =>
+ Effect.suspend(() => {
+ if (keeping) {
+ queued = keep(api, snapshot, environment);
+ return Effect.void;
+ }
+ keeping = true;
+ return ensureSpare({ api, snapshot, environment, held: ready, taken }).pipe(
+ Effect.tap((spare) =>
+ Effect.sync(() => {
+ ready = taken.has(spare.sandboxId) ? null : spare;
+ }),
+ ),
+ Effect.catchCause((cause) =>
+ Effect.logWarning("boat cloud could not keep a spare VM ready", { cause }),
+ ),
+ Effect.ensuring(
+ Effect.sync(() => {
+ keeping = false;
+ }),
+ ),
+ Effect.andThen(
+ Effect.suspend(() => {
+ const next = queued;
+ queued = null;
+ return next ?? Effect.void;
+ }),
+ ),
+ );
+ });
+
+ return {
+ keep,
+ /** The ready spare for this snapshot and environment, which no later start gets. */
+ take: (snapshot: string, environment: string | null) =>
+ Effect.map(Clock.currentTimeMillis, (now) => {
+ const spare = ready;
+ if (
+ spare === null ||
+ spare.snapshot !== snapshot ||
+ spare.environment !== environment ||
+ Math.min(spare.codeExpiresAt, spare.stopsAt) - now < HAND_OUT_MARGIN_MS
+ ) {
+ return null;
+ }
+ ready = null;
+ taken.add(spare.sandboxId);
+ return spare;
+ }),
+ /** Folds in Boat's list of the holder's VMs. */
+ reconcile: (sandboxes: ReadonlyArray) => {
+ const byId = new Map(sandboxes.map((sandbox) => [sandbox.id, sandbox]));
+ const listed = ready === null ? undefined : byId.get(ready.sandboxId);
+ if (
+ listed === undefined ||
+ listed.name !== SPARE_NAME ||
+ machineStateOf(listed.state) !== "running"
+ ) {
+ ready = null;
+ }
+ for (const sandboxId of taken) {
+ if (byId.get(sandboxId)?.name !== SPARE_NAME) taken.delete(sandboxId);
+ }
+ },
+ };
+};
+
+/** The Boat VM a paired environment's URL points at, or null when Boat has no such VM. */
+export const findSandboxByHttpBaseUrl = Effect.fn("BoatCloud.findSandboxByHttpBaseUrl")(function* (
+ api: BoatApi,
+ httpBaseUrl: string,
+) {
+ const subdomain = subdomainOfHttpBaseUrl(httpBaseUrl);
+ if (subdomain === null) return null;
+ const sandboxes = yield* api.listSandboxes(MACHINE_LABEL_FILTER);
+ return sandboxes.find((sandbox) => sandbox.subdomain === subdomain) ?? null;
+});
+
+/**
+ * Turns a stopped VM back on and serves its T3 server again. The disk keeps
+ * the server's identity, so clients already paired with it reconnect by themselves.
+ */
+export const wakeMachine = Effect.fn("BoatCloud.wakeMachine")(function* (
+ api: BoatApi,
+ sandboxId: string,
+ options?: { readonly pair?: boolean; readonly report?: ReportStep },
+) {
+ const report = options?.report ?? (() => Effect.void);
+ const sandbox = yield* runStep(
+ report,
+ "machine",
+ null,
+ Effect.gen(function* () {
+ const listed = yield* api.getSandbox(sandboxId);
+ if (listed === null) return yield* vmFailure("Boat deleted this VM.", "gone");
+ if (machineStateOf(listed.state) === "stopped") {
+ yield* api.resume(sandboxId, IDLE_TTL_SECONDS, "default");
+ } else {
+ yield* api.extend(sandboxId, IDLE_TTL_SECONDS);
+ }
+ return yield* waitRunning(api, sandboxId);
+ }),
+ );
+ return yield* runStep(
+ report,
+ "server",
+ null,
+ Effect.gen(function* () {
+ const started = yield* startServer(api, sandboxId, options?.pair === true);
+ return {
+ environmentId: started.environmentId,
+ pairingCode: started.pairing?.code ?? null,
+ httpBaseUrl: yield* serverUrl(api, sandbox, started.hosted),
+ };
+ }),
+ );
+});
+
+const LatestRelease = Schema.Struct({ tag_name: Schema.String });
+
+/** The newest Boat cloud build of t3, which every snapshot should carry. */
+export const latestCliRelease = Effect.fn("BoatCloud.latestCliRelease")(
+ function* (http: HttpClient.HttpClient) {
+ const response = yield* http
+ .get(`https://api.github.com/repos/${CLI_RELEASE_REPOSITORY}/releases/latest`, {
+ headers: { accept: "application/vnd.github+json" },
+ })
+ .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
+ const release = yield* response.json.pipe(
+ Effect.flatMap(Schema.decodeUnknownEffect(LatestRelease)),
+ );
+ const version = cliVersionOfTag(release.tag_name);
+ if (version === null) return yield* Effect.fail(release.tag_name);
+ return version;
+ },
+ Effect.timeout(Duration.seconds(30)),
+ Effect.mapError((cause) =>
+ vmFailure("Could not find the latest T3 Code build for Boat cloud.", "cli_release", cause),
+ ),
+);
+
+const createdMillis = (snapshot: BoatSnapshot) => Date.parse(snapshot.createdAt ?? "") || 0;
+
+/** The snapshot new VMs start from: the newest ready one, the previous build while one is saved. */
+export const startingSnapshot = (snapshots: ReadonlyArray) => {
+ let newest: BoatSnapshot | null = null;
+ for (const snapshot of snapshots) {
+ if (snapshot.status !== "ready" || !isBoatCloudSnapshot(snapshot.name)) continue;
+ if (newest === null || createdMillis(snapshot) > createdMillis(newest)) newest = snapshot;
+ }
+ return newest?.name ?? null;
+};
+
+/**
+ * Whether a holder should save the latest build: a machine wants it with its skills, and
+ * a holder without skills, such as the phone, takes any snapshot of it. One being saved
+ * counts, so holders never undo each other's work.
+ */
+export const needsSnapshot = (
+ snapshots: ReadonlyArray,
+ version: string,
+ withSkills: boolean,
+) => {
+ const has = (name: string) =>
+ snapshots.some((snapshot) => snapshot.name === name && snapshot.status !== "failed");
+ return (
+ !has(snapshotNameOf(version, true)) && (withSkills || !has(snapshotNameOf(version, false)))
+ );
+};
+
+/**
+ * The build a holder should save a snapshot of, or null when the snapshot is current or
+ * another holder is setting one up right now.
+ */
+export const snapshotToBuild = Effect.fn("BoatCloud.snapshotToBuild")(function* (
+ api: BoatApi,
+ http: HttpClient.HttpClient,
+ withSkills: boolean,
+) {
+ const [version, snapshots, setups] = yield* Effect.all(
+ [latestCliRelease(http), api.listSnapshots(), api.listSandboxes(SETUP_LABEL_FILTER)],
+ { concurrency: "unbounded" },
+ );
+ if (setups.some((sandbox) => machineStateOf(sandbox.state) !== "stopped")) return null;
+ return needsSnapshot(snapshots, version, withSkills) ? version : null;
+});
+
+// Until Boat starts saving, a name saved before still reports its previous snapshot as ready.
+const waitSnapshot = (api: BoatApi, name: string, sourceSandboxId: string) =>
+ api.listSnapshots().pipe(
+ Effect.flatMap((snapshots) => {
+ const snapshot = snapshots.find((candidate) => candidate.name === name);
+ if (snapshot?.status === "ready" && snapshot.sourceSandboxId === sourceSandboxId) {
+ return Effect.void;
+ }
+ if (snapshot?.status === "failed") {
+ return Effect.fail(vmFailure("Boat could not save the snapshot."));
+ }
+ return Effect.fail(vmFailure("Boat is still saving the snapshot.", "saving"));
+ }),
+ Effect.retry({
+ schedule: Schedule.spaced(Duration.seconds(5)),
+ times: 360,
+ while: (error) => error.code === "saving",
+ }),
+ );
+
+/** Clones what it can; a repository missing from the snapshot is cloned on first use instead. */
+const cloneRepositories = (api: BoatApi, sandboxId: string, remoteUrls: ReadonlyArray) => {
+ const repositories = [
+ ...new Map(
+ remoteUrls.flatMap((remoteUrl) => {
+ const parsed = parseRepository(remoteUrl);
+ return parsed ? [[parsed.key, parsed] as const] : [];
+ }),
+ ).values(),
+ ];
+ if (repositories.length === 0) return Effect.void;
+ return exec(api, sandboxId, cloneRepositoriesScript(repositories), 300).pipe(
+ Effect.flatMap((stdout) =>
+ Effect.logInfo("boat cloud snapshot holds repositories", {
+ cloned: stdout.split("\n").filter(Boolean).length,
+ asked: repositories.length,
+ }),
+ ),
+ Effect.catchCause((cause) =>
+ Effect.logWarning("boat cloud could not clone repositories into the snapshot", { cause }),
+ ),
+ );
+};
+
+/**
+ * Builds the snapshot every VM starts from: a VM with the given t3 build installed
+ * as a service that starts at boot, the holder's skills, the given repositories
+ * checked out, and no T3 state. Older snapshots are deleted once it is saved.
+ * Returns its name.
+ */
+export const buildSnapshot = Effect.fn("BoatCloud.buildSnapshot")(function* (input: {
+ readonly api: BoatApi;
+ readonly version: string;
+ /** Absent on a holder with no skills, such as the phone. */
+ readonly copySkills?: (sandboxId: string) => Effect.Effect