diff --git a/.github/workflows/boat-cloud-cli.yml b/.github/workflows/boat-cloud-cli.yml new file mode 100644 index 0000000000000..bd67342f778fa --- /dev/null +++ b/.github/workflows/boat-cloud-cli.yml @@ -0,0 +1,113 @@ +name: Boat cloud CLI + +# Builds this fork's t3 for Boat cloud VMs and publishes it as the latest +# GitHub release. Setup installs that release in the snapshot, and the holder +# of the Boat key saves a snapshot of each new one (packages/shared/src/boatCloudStart.ts). +# Push a tag such as boat-cli-v0.1.9-boat.1; v* tags stay with release.yml. + +on: + push: + tags: + - "boat-cli-v*" + +permissions: + contents: write + +concurrency: + group: boat-cloud-cli-${{ github.ref_name }} + +jobs: + release: + name: Build and publish the Linux x64 CLI + if: github.repository == 'vkpdeveloper/t3code' + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + # checkout's credential cleanup runs submodule foreach, which fails on the + # orphaned gitlinks in the vendored .repos tree. + - name: Checkout + shell: bash + env: + GIT_TERMINAL_PROMPT: "0" + run: | + set -euo pipefail + git init . + git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git" + git fetch --no-tags --depth=1 origin "$GITHUB_SHA" + git sparse-checkout set --no-cone '/*' '!/.repos/' + git -c checkout.workers=0 checkout --detach FETCH_HEAD + + - name: Read the version from the tag + id: version + shell: bash + run: | + set -euo pipefail + version="${GITHUB_REF_NAME#boat-cli-v}" + if [[ ! "$version" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]]; then + echo "Tag $GITHUB_REF_NAME does not carry an exact version." >&2 + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps + with: + install-args: --filter=t3... --filter=@t3tools/web... --filter=@t3tools/desktop... --filter=@t3tools/scripts... + + - name: Align package versions and public configuration + run: | + node scripts/update-release-package-versions.ts "${{ steps.version.outputs.version }}" + # Public T3 Connect identifiers (Clerk publishable key, relay URL). + cp .env.example .env + + - name: Setup Rust + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: stable + targets: x86_64-unknown-linux-gnu + + - name: Build resource monitor + shell: bash + run: | + set -euo pipefail + cargo build --locked --release --manifest-path native/resource-monitor/Cargo.toml --target x86_64-unknown-linux-gnu + mkdir -p "$RUNNER_TEMP/cli-resource-monitor/linux-x64" + cp native/resource-monitor/target/x86_64-unknown-linux-gnu/release/t3-resource-monitor "$RUNNER_TEMP/cli-resource-monitor/linux-x64/" + + # The Linux archive ships libatomic.so.1 and points t3's RUNPATH at it. + - name: Install patchelf + run: command -v patchelf || { sudo apt-get update && sudo apt-get install -y patchelf; } + + - name: Build server and web client + env: + T3CODE_TELEMETRY_CHANNEL: dev + run: | + vp run build:desktop:bundle + node scripts/apply-web-brand-assets.ts production apps/server/dist/client + + - name: Build CLI single-executable + env: + T3CODE_TELEMETRY_CHANNEL: dev + run: node apps/server/scripts/cli.ts build-exe --verbose + + - name: Build and smoke-test CLI archive + shell: bash + run: | + set -euo pipefail + node scripts/build-cli-archive.ts \ + --platform linux \ + --arch x64 \ + --version "${{ steps.version.outputs.version }}" \ + --resource-monitor-dir "$RUNNER_TEMP/cli-resource-monitor" \ + --output-dir release-cli + node scripts/smoke-cli-archive.ts --archive release-cli/* --expect-version "${{ steps.version.outputs.version }}" + (cd release-cli && sha256sum t3-*.tar.gz > SHA256SUMS && cat SHA256SUMS) + + - name: Publish release + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "$GITHUB_REF_NAME" release-cli/* \ + --title "Boat cloud CLI ${{ steps.version.outputs.version }}" \ + --notes "t3 ${{ steps.version.outputs.version }} for Boat cloud VMs, built from ${GITHUB_SHA}." \ + --latest diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 9b8d9506a63ca..8f475a27d1d2e 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -96,6 +96,7 @@ import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteSc import { SettingsEnvironmentDetailRouteScreen } from "./features/settings/SettingsEnvironmentDetailRouteScreen"; import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; import { SettingsFollowUpRouteScreen } from "./features/settings/SettingsFollowUpRouteScreen"; +import { SettingsCloudRouteScreen } from "./features/settings/SettingsCloudRouteScreen"; import { SettingsLanguageRouteScreen } from "./features/settings/SettingsLanguageRouteScreen"; import { SettingsEnvironmentMaintenanceRouteScreen, @@ -290,6 +291,11 @@ const SETTINGS_SCREENS = { linking: "settings/follow-ups", options: settingsPage("Chat"), }), + SettingsCloud: createNativeStackScreen({ + screen: SettingsCloudRouteScreen, + linking: "settings/cloud", + options: settingsPage("Cloud"), + }), SettingsScheduledTasks: createNativeStackScreen({ screen: SettingsScheduledTasksRouteScreen, linking: "settings/scheduled-tasks", diff --git a/apps/mobile/src/components/BoatIcon.tsx b/apps/mobile/src/components/BoatIcon.tsx new file mode 100644 index 0000000000000..c5a65e0508904 --- /dev/null +++ b/apps/mobile/src/components/BoatIcon.tsx @@ -0,0 +1,22 @@ +import Svg, { Path } from "react-native-svg"; +import { withUniwind } from "uniwind"; + +const ThemedPath = withUniwind(Path); + +/** The boat.dev mark. */ +export function BoatIcon(props: { readonly size: number; readonly colorClassName: string }) { + return ( + + + + ); +} diff --git a/apps/mobile/src/components/BoxdIcon.tsx b/apps/mobile/src/components/BoxdIcon.tsx new file mode 100644 index 0000000000000..eaf86f963bc7f --- /dev/null +++ b/apps/mobile/src/components/BoxdIcon.tsx @@ -0,0 +1,17 @@ +import Svg, { Path } from "react-native-svg"; +import { withUniwind } from "uniwind"; + +const ThemedPath = withUniwind(Path); + +/** The boxd.sh mark. */ +export function BoxdIcon(props: { readonly size: number; readonly colorClassName: string }) { + return ( + + + + ); +} diff --git a/apps/mobile/src/connection/onboarding.ts b/apps/mobile/src/connection/onboarding.ts index 54963759ed189..07e639a5b64ec 100644 --- a/apps/mobile/src/connection/onboarding.ts +++ b/apps/mobile/src/connection/onboarding.ts @@ -28,6 +28,27 @@ export const connectPairingUrl = createRuntimeCommand(connectionAtomRuntime, { ), }); +/** Pairs with a server from its address and a one-time code, such as a Boat cloud VM. */ +export const connectPairingCode = createRuntimeCommand(connectionAtomRuntime, { + label: "mobile:connection:connect-pairing-code", + scheduler: onboardingScheduler, + concurrency: { + mode: "singleFlight", + key: (input: { readonly host: string; readonly pairingCode: string }) => + JSON.stringify([input.host, input.pairingCode]), + }, + execute: (input: { + readonly host: string; + readonly pairingCode: string; + readonly expectedEnvironmentId: EnvironmentId; + }) => + ConnectionOnboarding.ConnectionOnboarding.pipe( + Effect.flatMap((onboarding) => + onboarding.registerPairing({ ...input, codeIsForExpectedEnvironment: true }), + ), + ), +}); + export const updateBearerConnection = createRuntimeCommand(connectionAtomRuntime, { label: "mobile:connection:update-bearer", scheduler: onboardingScheduler, diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts index de461f35ab104..83a672f9a94c2 100644 --- a/apps/mobile/src/connection/platform.ts +++ b/apps/mobile/src/connection/platform.ts @@ -6,6 +6,7 @@ import { Wakeups, } from "@t3tools/client-runtime/connection"; import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay"; +import { EnvironmentRpcUnavailableError, EnvironmentWaker } from "@t3tools/client-runtime/rpc"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -249,6 +250,26 @@ const layerPlatformConnectionSource = Layer.succeed( const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer)); const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer)); +const layerEnvironmentWaker = Layer.succeed( + EnvironmentWaker, + EnvironmentWaker.of({ + wakeIfAsleep: Effect.fn("mobile.connectionPlatform.wakeIfAsleep")(function* (environmentId) { + // Imported on use: the Boat cloud module reaches back into the connection runtime. + const woken = yield* Effect.promise(() => + import("../features/boatCloud/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 layerProvidedConnectionStorage | typeof Runtime.layer @@ -256,7 +277,8 @@ type ConnectionPlatformLayerSource = | typeof layerWakeups | typeof layerProvidedCapabilities | typeof layerPlatformConnectionSource - | typeof EnvironmentOwnedDataCleanup.layer; + | typeof EnvironmentOwnedDataCleanup.layer + | typeof layerEnvironmentWaker; export const layer: Layer.Layer< Layer.Success, @@ -270,4 +292,5 @@ export const layer: Layer.Layer< layerProvidedCapabilities, layerPlatformConnectionSource, EnvironmentOwnedDataCleanup.layer, + layerEnvironmentWaker, ); diff --git a/apps/mobile/src/features/boatCloud/BoatCloudSteps.tsx b/apps/mobile/src/features/boatCloud/BoatCloudSteps.tsx new file mode 100644 index 0000000000000..ee080939d0b25 --- /dev/null +++ b/apps/mobile/src/features/boatCloud/BoatCloudSteps.tsx @@ -0,0 +1,53 @@ +import type { BoatCloudStartStep, BoatCloudStepProgress } from "@t3tools/contracts"; +import { View } from "react-native"; + +import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; +import { ListRowLayout } from "../../components/ui/ListRowLayout"; +import { cn } from "../../lib/cn"; + +export type StepState = BoatCloudStepProgress["state"]; + +// Static glyphs: a VM takes seconds to minutes, and a spinner would repaint the whole time. +const STEP_ICONS: Record = { + done: { name: "checkmark.circle.fill", tint: "accent-success-foreground" }, + failed: { name: "xmark.circle.fill", tint: "accent-danger-foreground" }, + active: { name: "circle.inset.filled", tint: "accent-primary-text" }, + pending: { name: "circle.dashed", tint: "accent-icon-muted" }, +}; + +export function StepGlyph(props: { readonly state: StepState }) { + const icon = STEP_ICONS[props.state]; + return ; +} + +const START_STEP_LABELS: Record = { + machine: "Find a VM", + server: "Start T3 Code", + repository: "Clone or update the repository", + connect: "Connect", + project: "Open the project", + thread: "Move the draft", +}; + +/** Each step of starting on Boat cloud, as the holder and this app report it. */ +export function BoatCloudStartSteps(props: { + readonly steps: ReadonlyArray; +}) { + return ( + + {props.steps.map((entry, index) => ( + 0 && "border-t border-border-subtle")} + accessibilityLabel={`${START_STEP_LABELS[entry.step]}, ${entry.state}`} + > + } + label={START_STEP_LABELS[entry.step]} + description={entry.detail ?? undefined} + /> + + ))} + + ); +} diff --git a/apps/mobile/src/features/boatCloud/boatCloud.ts b/apps/mobile/src/features/boatCloud/boatCloud.ts new file mode 100644 index 0000000000000..300b961519128 --- /dev/null +++ b/apps/mobile/src/features/boatCloud/boatCloud.ts @@ -0,0 +1,491 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + connectionCatalogDisplayUrl, + type EnvironmentConnectionPhase, +} from "@t3tools/client-runtime/connection"; +import { + isAtomCommandInterrupted, + runAtomCommand, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { + BOAT_CLOUD_START_STEPS, + type BoatCloudAcquireInput, + type BoatCloudSession, + type BoatCloudStartStep, + type BoatCloudStatus, + type BoatCloudStepProgress, + type EnvironmentId, + isBoatCloudHttpBaseUrl, +} from "@t3tools/contracts"; +import { boatCloudProviderDrivers } from "@t3tools/shared/boatCloudVm"; +import * as Effect from "effect/Effect"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { useEffect } from "react"; + +import * as Dialog from "../../components/ui/Dialog"; +import { environmentCatalog } from "../../connection/catalog"; +import { connectPairingCode } from "../../connection/onboarding"; +import { uuidv4 } from "../../lib/uuid"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { connectedEnvironmentIdsAtom, environmentPresentations } from "../../state/presentation"; +import { environmentProjects } from "../../state/projects"; +import { serverEnvironment } from "../../state/server"; +import { boxdCloudMachinesAtom } from "../boxdCloud/boxdCloud"; +import { + ensurePhoneBoatCloudLoaded, + phoneBoatCloudAtom, + startOnPhone, + wakeOnPhone, +} from "./phoneBoatCloud"; + +/** + * Boat cloud VMs are ordinary environments. A holder of the Boat key hands out + * a VM, and this app pairs with it like any other machine. The holder is a + * connected machine when one has the key, else this phone. + */ + +const PROJECT_APPEAR_TIMEOUT_MS = 60_000; +const RECONNECT_TIMEOUT_MS = 15_000; + +interface BoatCloudHolder { + readonly environmentId: EnvironmentId; + readonly status: BoatCloudStatus; +} + +/** Who starts a VM: a connected machine with the key, or this phone with its own. */ +type BoatCloudStarter = + | { readonly kind: "machine"; readonly environmentId: EnvironmentId } + | { readonly kind: "phone" }; + +/** Paired Boat VMs, by environment, with the URL each one is reached at. */ +export const boatCloudMachinesAtom = Atom.make((get) => { + const machines = new Map(); + for (const [environmentId, presentation] of get(environmentPresentations.presentationsAtom)) { + const url = connectionCatalogDisplayUrl(presentation.entry); + if (url !== null && isBoatCloudHttpBaseUrl(url)) machines.set(environmentId, url); + } + return machines; +}).pipe(Atom.withLabel("mobile-boat-cloud:machines")); + +/** Boat VMs and boxd machines, which answer for Boat cloud too but must never get the key. */ +const cloudMachineIdsAtom = Atom.make( + (get) => new Set([...get(boatCloudMachinesAtom).keys(), ...get(boxdCloudMachinesAtom).keys()]), +).pipe(Atom.withLabel("mobile-boat-cloud:cloud-machine-ids")); + +/** Connected machines whose T3 Code predates Boat cloud, so they cannot take the key yet. */ +export const boatCloudOutdatedMachinesAtom = Atom.make((get): ReadonlyArray => { + const cloudMachines = get(cloudMachineIdsAtom); + return get(connectedEnvironmentIdsAtom).filter((environmentId) => { + if (cloudMachines.has(environmentId)) return false; + const config = get(serverEnvironment.configValueAtom(environmentId)); + return config !== null && config.environment.capabilities.boatCloud !== true; + }); +}).pipe(Atom.withLabel("mobile-boat-cloud:outdated-machines")); + +/** Connected machines that answer for Boat cloud, without the cloud machines, which answer too. */ +export const boatCloudHoldersAtom = Atom.make((get): ReadonlyArray => { + const cloudMachines = get(cloudMachineIdsAtom); + return get(connectedEnvironmentIdsAtom).flatMap((environmentId) => { + if (cloudMachines.has(environmentId)) return []; + const status = AsyncResult.getOrElse( + get(serverEnvironment.boatCloudStatus({ environmentId, input: {} })), + () => null, + ); + return status ? [{ environmentId, status }] : []; + }); +}).pipe(Atom.withLabel("mobile-boat-cloud:holders")); + +function boatCloudReady(status: BoatCloudStatus | null | undefined) { + return status?.connected === true && (status.setup.status === "ready" || status.snapshotReady); +} + +/** + * The holder that should start a VM: the draft's own machine when it can, then + * any ready machine, which keeps session backups, then this phone. + */ +function boatCloudStarterFor( + holders: ReadonlyArray, + phone: BoatCloudStatus, + preferredEnvironmentId: EnvironmentId | null, +): BoatCloudStarter | null { + const ready = holders.filter((holder) => boatCloudReady(holder.status)); + const machine = + ready.find((holder) => holder.environmentId === preferredEnvironmentId) ?? ready[0]; + if (machine) return { kind: "machine", environmentId: machine.environmentId }; + return boatCloudReady(phone) ? { kind: "phone" } : null; +} + +export function useBoatCloudStarter(preferredEnvironmentId: EnvironmentId | null) { + const holders = useAtomValue(boatCloudHoldersAtom); + const phone = useAtomValue(phoneBoatCloudAtom); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads this phone's Boat key from the keychain once per launch + useEffect(() => { + void ensurePhoneBoatCloudLoaded(); + }, []); + return boatCloudStarterFor(holders, phone, preferredEnvironmentId); +} + +/** The providers a new VM from this starter has sign-ins for, or null when unknown. */ +export function useBoatCloudProviderDrivers(preferredEnvironmentId: EnvironmentId | null) { + const holders = useAtomValue(boatCloudHoldersAtom); + const phone = useAtomValue(phoneBoatCloudAtom); + const starter = boatCloudStarterFor(holders, phone, preferredEnvironmentId); + const status = + starter?.kind === "machine" + ? holders.find((holder) => holder.environmentId === starter.environmentId)?.status + : starter?.kind === "phone" + ? phone + : null; + const chosen = status?.environments.find( + (environment) => environment.name === status.environment, + ); + return chosen?.agentCredentials ? boatCloudProviderDrivers(chosen.agentCredentials) : null; +} + +function errorMessage(error: unknown) { + return error instanceof Error ? error.message : "An error occurred."; +} + +/** Paired VMs as the holder takes them, so it skips their pairing code. */ +const pairedBoatCloudEnvironments = (): NonNullable => + [...appAtomRegistry.get(boatCloudMachinesAtom)].map(([environmentId, httpBaseUrl]) => ({ + environmentId, + httpBaseUrl, + })); + +const reconnectFailed = new Error("Could not reconnect to the Boat cloud machine."); + +/** Resolves once the environment is connected, or false after `timeoutMs`. */ +function waitForConnected(environmentId: EnvironmentId, timeoutMs: number): Promise { + const connected = () => appAtomRegistry.get(connectedEnvironmentIdsAtom).includes(environmentId); + if (connected()) return Promise.resolve(true); + return new Promise((resolve) => { + const finish = (result: boolean) => { + clearTimeout(timeout); + unsubscribe(); + resolve(result); + }; + const timeout = setTimeout(() => finish(false), timeoutMs); + const unsubscribe = appAtomRegistry.subscribe(connectedEnvironmentIdsAtom, () => { + if (connected()) finish(true); + }); + }); +} + +/** + * Connects this app to the VM: with its saved credential when the holder sent no + * pairing code, else by pairing. Throws what failed. + */ +async function attach( + session: Pick, +) { + if (appAtomRegistry.get(connectedEnvironmentIdsAtom).includes(session.environmentId)) return; + if (session.pairingCode === null) { + // A stopped VM left its connection backing off; retry now that the server is up. + void environmentCatalog.retryNow.run(appAtomRegistry, session.environmentId); + if (!(await waitForConnected(session.environmentId, RECONNECT_TIMEOUT_MS))) { + throw reconnectFailed; + } + return; + } + const paired = await runAtomCommand( + appAtomRegistry, + connectPairingCode, + { + host: session.httpBaseUrl, + pairingCode: session.pairingCode, + expectedEnvironmentId: session.environmentId, + }, + { label: connectPairingCode.label, reportFailure: false, reportDefect: true }, + ); + if (paired._tag === "Failure") throw squashAtomCommandFailure(paired); +} + +function waitForProject( + find: (projects: ReadonlyArray) => EnvironmentProject | undefined, +): Promise { + const atom = environmentProjects.projectsAtom; + const now = find(appAtomRegistry.get(atom)); + if (now) return Promise.resolve(now); + return new Promise((resolve) => { + const finish = (project: EnvironmentProject | null) => { + clearTimeout(timeout); + unsubscribe(); + resolve(project); + }; + const timeout = setTimeout(() => finish(null), PROJECT_APPEAR_TIMEOUT_MS); + const unsubscribe = appAtomRegistry.subscribe(atom, (projects) => { + const project = find(projects); + if (project) finish(project); + }); + }); +} + +const cancelled = new Error("Boat cloud start cancelled"); + +const HOLDER_STEPS = new Set(["machine", "server", "repository"]); + +const pendingBoatCloudSteps = (): ReadonlyArray => + BOAT_CLOUD_START_STEPS.map((step) => ({ step, state: "pending", detail: null })); + +/** + * Starts the VM through a connected machine. Its steps arrive in that machine's + * status, the checkout's after the acquire returns, so the caller stops watching. + */ +function startOnMachine(input: { + readonly environmentId: EnvironmentId; + readonly repositoryUrl: string; + readonly baseBranch: string | null; + readonly paired: BoatCloudAcquireInput["paired"]; + readonly onHolderSteps: (steps: ReadonlyArray) => void; +}) { + const requestId = uuidv4(); + const statusAtom = serverEnvironment.boatCloudStatus({ + environmentId: input.environmentId, + input: {}, + }); + const stopWatching = appAtomRegistry.subscribe(statusAtom, (result) => { + const start = AsyncResult.getOrElse(result, () => null)?.starts.find( + (candidate) => candidate.requestId === requestId, + ); + if (start) input.onHolderSteps(start.steps.filter((step) => HOLDER_STEPS.has(step.step))); + }); + const session = runAtomCommand( + appAtomRegistry, + serverEnvironment.acquireBoatCloud, + { + environmentId: input.environmentId, + input: { + repositoryUrl: input.repositoryUrl, + ...(input.baseBranch ? { baseBranch: input.baseBranch } : {}), + requestId, + paired: input.paired, + }, + }, + { label: serverEnvironment.acquireBoatCloud.label, reportFailure: false, reportDefect: true }, + ).then((acquired): BoatCloudSession => { + if (acquired._tag === "Failure") { + throw isAtomCommandInterrupted(acquired) ? cancelled : squashAtomCommandFailure(acquired); + } + return acquired.value; + }); + return { session, stopWatching }; +} + +/** The VM's project for a draft, and the worktree the VM made for its thread, when it made one. */ +export interface BoatCloudTarget { + readonly project: EnvironmentProject; + readonly worktree: BoatCloudSession["worktree"] | null; +} + +/** + * Gets a VM with the repository checked out and returns its project there, so + * a draft can move onto it, reporting every step on the way. The caller marks + * the last step, moving the thread, done. Null after telling the user what failed. + */ +export async function prepareBoatCloudProject(input: { + readonly starter: BoatCloudStarter; + readonly repositoryUrl: string; + readonly baseBranch: string | null; + readonly onProgress: (steps: ReadonlyArray) => void; +}): Promise { + let steps = pendingBoatCloudSteps(); + const set = (step: BoatCloudStartStep, patch: Partial) => { + steps = steps.map((entry) => (entry.step === step ? { ...entry, ...patch } : entry)); + input.onProgress(steps); + }; + // The checkout keeps running after the acquire returns, and only its step says how it ended. + let checkoutFailed: (error: Error) => void = () => undefined; + const watchCheckout = () => + new Promise((_, reject) => { + checkoutFailed = reject; + }); + let checkoutFailure = watchCheckout(); + const setHolderStep = (step: BoatCloudStartStep, patch: Partial) => { + set(step, patch); + if (step === "repository" && patch.state === "failed") { + checkoutFailed(new Error(patch.detail ?? "Could not get the repository on the VM.")); + } + }; + const setHolderSteps = (holderSteps: ReadonlyArray) => { + for (const entry of holderSteps) setHolderStep(entry.step, entry); + }; + const stops: Array<() => void> = []; + // A start that was retried keeps reporting, so only the latest one's steps count. + let attempt = 0; + const start = (paired: BoatCloudAcquireInput["paired"]) => { + attempt += 1; + const mine = attempt; + if (input.starter.kind === "phone") { + return startOnPhone({ + repositoryUrl: input.repositoryUrl, + baseBranch: input.baseBranch, + paired, + report: (step, state, detail) => + Effect.sync(() => { + if (mine === attempt) setHolderStep(step, { state, detail }); + }), + }); + } + const started = startOnMachine({ + environmentId: input.starter.environmentId, + repositoryUrl: input.repositoryUrl, + baseBranch: input.baseBranch, + paired, + onHolderSteps: (holderSteps) => { + if (mine === attempt) setHolderSteps(holderSteps); + }, + }); + stops.push(started.stopWatching); + return started.session; + }; + let current: BoatCloudStartStep = "machine"; + try { + let session = await start(pairedBoatCloudEnvironments()); + // The VM and its server are up; the checkout may still run while this app connects. + set("machine", { state: "done" }); + set("server", { state: "done" }); + if (steps.find((entry) => entry.step === "repository")?.state === "pending") { + set("repository", { state: "active" }); + } + current = "connect"; + set("connect", { state: "active" }); + try { + await attach(session); + } catch { + // The saved credential no longer works, or the VM did not answer, so start once more + // and pair as a new app. A VM that does not answer gets no new thread. + checkoutFailure = watchCheckout(); + session = await start([]); + await attach(session); + } + set("connect", { state: "done" }); + current = "project"; + const project = await Promise.race([ + waitForProject((projects) => + projects.find( + (candidate) => + candidate.environmentId === session.environmentId && + candidate.workspaceRoot === session.workspaceRoot, + ), + ), + checkoutFailure, + ]); + if (!project) throw new Error("The Boat cloud machine did not open the project."); + // The project is added after the checkout and its worktree, so it appearing means both are done. + set("repository", { state: "done" }); + set("project", { state: "done" }); + set("thread", { state: "active" }); + return { project, worktree: session.worktree ?? null }; + } catch (error) { + if (!steps.some((entry) => entry.state === "failed")) { + set(current, { state: "failed" }); + } + if (error !== cancelled) Dialog.alert("Could not start on Boat cloud", errorMessage(error)); + return null; + } finally { + for (const stop of stops) stop(); + } +} + +const wakesInFlight = new Map>(); + +/** Whether this app is turning a VM back on, so its thread shows "Waking" rather than "Sleeping". */ +const boatCloudWakingAtom = Atom.family((_environmentId: EnvironmentId | null) => + Atom.make(false).pipe(Atom.keepAlive), +); + +/** + * Turns a stopped VM back on. A machine that owns it can also restore it from + * its backup and hands out a new pairing; the phone reconnects to the same server. + */ +function wakeBoatCloudMachine(environmentId: EnvironmentId, httpBaseUrl: string): Promise { + const inFlight = wakesInFlight.get(environmentId); + if (inFlight) return inFlight; + const waking = boatCloudWakingAtom(environmentId); + appAtomRegistry.set(waking, true); + const wake = (async () => { + await ensurePhoneBoatCloudLoaded(); + const holders = appAtomRegistry.get(boatCloudHoldersAtom); + const phoneHasKey = appAtomRegistry.get(phoneBoatCloudAtom).connected; + // The machine that started the VM can restore it; any other machine with the key can wake it. + const owner = + holders.find((holder) => + holder.status.machines.some((machine) => machine.environmentId === environmentId), + ) ?? (phoneHasKey ? undefined : holders.find((holder) => holder.status.connected)); + if (owner) { + const woken = await runAtomCommand( + appAtomRegistry, + serverEnvironment.wakeBoatCloud, + { environmentId: owner.environmentId, input: { environmentId, httpBaseUrl } }, + { label: serverEnvironment.wakeBoatCloud.label, reportFailure: false, reportDefect: true }, + ); + if (woken._tag === "Failure") { + if (!isAtomCommandInterrupted(woken)) { + Dialog.alert( + "Could not wake the Boat cloud machine", + errorMessage(squashAtomCommandFailure(woken)), + ); + } + return; + } + // A restored VM has a new address, so pair again rather than wait for the old one. + await attach(woken.value).catch((error: unknown) => + Dialog.alert("Could not reconnect to Boat cloud", errorMessage(error)), + ); + return; + } + if (!phoneHasKey) return; + await wakeOnPhone(httpBaseUrl).catch((error: unknown) => + Dialog.alert("Could not wake the Boat cloud machine", errorMessage(error)), + ); + })().finally(() => { + wakesInFlight.delete(environmentId); + appAtomRegistry.set(waking, false); + }); + wakesInFlight.set(environmentId, wake); + return wake; +} + +const WAKE_CONNECT_TIMEOUT_MS = 90_000; + +/** + * Wakes a Boat VM that is not connected before an action runs on it. False when it + * could not be woken; true when it is connected or is not a Boat VM at all. + */ +export async function wakeBoatCloudIfAsleep(environmentId: EnvironmentId): Promise { + if (appAtomRegistry.get(connectedEnvironmentIdsAtom).includes(environmentId)) return true; + const httpBaseUrl = appAtomRegistry.get(boatCloudMachinesAtom).get(environmentId); + if (httpBaseUrl === undefined) return true; + await wakeBoatCloudMachine(environmentId, httpBaseUrl); + return waitForConnected(environmentId, WAKE_CONNECT_TIMEOUT_MS); +} + +export interface BoatCloudSleep { + readonly state: "sleeping" | "waking"; + readonly wake: () => void; +} + +/** + * A Boat VM that is not reachable is asleep: it stopped itself after its threads + * went quiet. A message sent meanwhile waits in the queue and wakes it, so its + * thread reads "Sleeping" rather than disconnected. + */ +export function useBoatCloudSleep( + environmentId: EnvironmentId | null, + phase: EnvironmentConnectionPhase | null, +): BoatCloudSleep | null { + const machines = useAtomValue(boatCloudMachinesAtom); + const waking = useAtomValue(boatCloudWakingAtom(environmentId)); + const httpBaseUrl = environmentId === null ? null : (machines.get(environmentId) ?? null); + if (environmentId === null || httpBaseUrl === null || phase === null || phase === "connected") { + return null; + } + // Retries cycle the phase, so only this app's own wake reads as waking. + return { + state: waking ? "waking" : "sleeping", + wake: () => void wakeBoatCloudMachine(environmentId, httpBaseUrl), + }; +} diff --git a/apps/mobile/src/features/boatCloud/boatCloudThreads.ts b/apps/mobile/src/features/boatCloud/boatCloudThreads.ts new file mode 100644 index 0000000000000..ad04357e57780 --- /dev/null +++ b/apps/mobile/src/features/boatCloud/boatCloudThreads.ts @@ -0,0 +1,52 @@ +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { createBoatCloudThreadListAtoms } from "@t3tools/client-runtime/state/threads"; +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { useEffect } from "react"; + +import { environmentCatalog } from "../../connection/catalog"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; + +const MAX_REMEMBERED = 500; +const NONE: ReadonlyArray = []; + +const openedThreadsAtom = Atom.make( + (get) => + AsyncResult.getOrElse(get(mobilePreferencesAtom), () => null)?.boatCloudOpenedThreads ?? NONE, +).pipe(Atom.withLabel("mobile-boat-cloud-opened-threads")); + +/** Boat cloud VM threads this phone started or opened, the only VM threads its lists show. */ +export const boatCloudThreadList = createBoatCloudThreadListAtoms({ + catalogValueAtom: environmentCatalog.catalogValueAtom, + openedThreadsAtom, +}); + +const preferencesLoadedAtom = Atom.make((get) => AsyncResult.isSuccess(get(mobilePreferencesAtom))); +const NO_ENVIRONMENT_ATOM = Atom.make(false); + +/** Lists an opened VM thread here from now on; the catalog and preferences load after the route. */ +export function useRememberOpenedBoatCloudThread(ref: ScopedThreadRef | null): void { + const environmentId = ref?.environmentId ?? null; + const threadId = ref?.threadId ?? null; + const onBoatCloud = useAtomValue( + environmentId === null + ? NO_ENVIRONMENT_ATOM + : boatCloudThreadList.onBoatCloudAtom(environmentId), + ); + const loaded = useAtomValue(preferencesLoadedAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records the visit in stored preferences, outside React + useEffect(() => { + if (!onBoatCloud || !loaded || environmentId === null || threadId === null) return; + const opened = appAtomRegistry.get(openedThreadsAtom); + if ( + opened.some((other) => other.environmentId === environmentId && other.threadId === threadId) + ) { + return; + } + savePreferences({ + boatCloudOpenedThreads: [...opened, { environmentId, threadId }].slice(-MAX_REMEMBERED), + }); + }, [onBoatCloud, loaded, environmentId, threadId, savePreferences]); +} diff --git a/apps/mobile/src/features/boatCloud/phoneBoatCloud.ts b/apps/mobile/src/features/boatCloud/phoneBoatCloud.ts new file mode 100644 index 0000000000000..856a434e2ddce --- /dev/null +++ b/apps/mobile/src/features/boatCloud/phoneBoatCloud.ts @@ -0,0 +1,391 @@ +import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections"; +import { mostWorkedRepositories } from "@t3tools/client-runtime/state/threads"; +import { + BOAT_CLOUD_SNAPSHOT_REPOSITORIES, + type BoatCloudEnvironmentAccess, + type BoatCloudSession, + type BoatCloudStatus, +} from "@t3tools/contracts"; +import { + type BoatApi, + BoatApiError, + cloudEnvironments, + makeBoatApi, +} from "@t3tools/shared/boatCloudApi"; +import { + type PairedEnvironment, + type ReportStep, + buildSnapshot, + findSandboxByHttpBaseUrl, + latestCliRelease, + makeSpareKeeper, + snapshotToBuild, + startMachine, + startingSnapshot, + wakeMachine, +} from "@t3tools/shared/boatCloudStart"; +import { + MACHINE_LABEL_FILTER, + SPARE_NAME, + VM_T3_PORT, + machineLabelOf, + machineStateOf, + parseRepository, +} from "@t3tools/shared/boatCloudVm"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import { HttpClient } from "effect/http"; +import { Atom } from "effect/reactivity"; + +import * as Runtime from "../../lib/runtime"; +import { MobileSecureStorage } from "../../persistence/mobile-secure-storage"; +import { environmentCatalog } from "../../connection/catalog"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { threadEnvironment } from "../../state/threads"; + +/** + * The phone as a Boat cloud holder: with the key in its own keychain it starts + * and wakes VMs without any machine connected. A machine holding the key does + * more (session backups, an idle sweep), so a connected one is used first. + */ + +const API_KEY_STORAGE_KEY = "t3code.boat-cloud.api-key"; +/** The Boat environment new VMs start on, by name, as a machine holder keeps it. */ +const ENVIRONMENT_STORAGE_KEY = "t3code.boat-cloud.environment"; + +const DISCONNECTED: BoatCloudStatus = { + connected: false, + account: null, + setup: { status: "idle", step: null, error: null }, + snapshotReady: false, + machines: [], + starts: [], + environment: null, + environments: [], + environmentsError: null, +}; + +export const phoneBoatCloudAtom = Atom.make(DISCONNECTED).pipe( + Atom.keepAlive, + Atom.withLabel("mobile-boat-cloud:phone"), +); + +const setStatus = (update: (status: BoatCloudStatus) => BoatCloudStatus) => + appAtomRegistry.update(phoneBoatCloudAtom, update); + +const notConnected = new BoatApiError({ + status: 0, + code: "not_connected", + message: "Connect Boat in Settings, Cloud first.", + retryable: false, +}); + +const phoneApi = Effect.gen(function* () { + const key = yield* MobileSecureStorage.use((storage) => storage.getItem(API_KEY_STORAGE_KEY)); + if (key === null) return yield* notConnected; + return makeBoatApi(yield* HttpClient.HttpClient, key); +}); + +const run = (effect: Effect.Effect) => + Runtime.runtime.runPromise(effect); + +const errorMessage = (error: unknown) => + error instanceof Error ? error.message : "Boat could not be reached."; + +// Bumped once the key is stored or removed, so a refresh that read the old key drops its result. +let keyGeneration = 0; +/** The saved snapshot new VMs start from, or null before setup. */ +let snapshotName: string | null = null; + +/** + * Reads the key, the snapshot and the VMs from Boat. Leaves a setup in progress alone, + * and saves the latest t3 build when Boat has no snapshot of it. + */ +export function refreshPhoneBoatCloud(): Promise { + const generation = keyGeneration; + const stale = () => generation !== keyGeneration; + return run( + Effect.gen(function* () { + const api = yield* phoneApi; + const [account, snapshots, sandboxes, environments, profiles, stored] = yield* Effect.all( + [ + api.me(), + api.listSnapshots(), + api.listSandboxes(MACHINE_LABEL_FILTER), + api.listEnvironments().pipe(Effect.result), + // Without it the sign-ins are unknown, and every provider stays offered. + api.listCredentialProfiles().pipe(Effect.option), + MobileSecureStorage.use((storage) => storage.getItem(ENVIRONMENT_STORAGE_KEY)), + ], + { concurrency: "unbounded" }, + ); + if (stale()) return; + spares.reconcile(sandboxes); + const listed = Result.isSuccess(environments) + ? cloudEnvironments(environments.success, Option.getOrNull(profiles)) + : []; + // With none chosen yet, Boat's default becomes the choice, so later VMs stay on it. + const environment = stored ?? listed.find((candidate) => candidate.isDefault)?.name ?? null; + if (stored === null && environment !== null) { + yield* MobileSecureStorage.use((storage) => + storage.setItem(ENVIRONMENT_STORAGE_KEY, environment), + ); + if (stale()) return; + } + snapshotName = startingSnapshot(snapshots); + const ready = snapshotName !== null; + setStatus((status) => ({ + ...status, + connected: true, + account, + setup: + status.setup.status === "running" + ? status.setup + : ready + ? { status: "ready", step: null, error: null } + : status.setup.status === "failed" + ? status.setup + : { status: "idle", step: null, error: null }, + snapshotReady: ready, + // The spare is no one's machine until a start takes it. + machines: sandboxes + .filter((sandbox) => sandbox.name !== SPARE_NAME) + .map((sandbox) => ({ + sandboxId: sandbox.id, + environmentId: null, + label: machineLabelOf(sandbox.id), + httpBaseUrl: sandbox.subdomain + ? `https://${sandbox.subdomain}-${VM_T3_PORT}.on.boat.dev` + : null, + state: machineStateOf(sandbox.state), + repositories: [], + backedUpAt: null, + environment: sandbox.environment ?? null, + })), + environment, + environments: listed, + environmentsError: Result.isFailure(environments) ? environments.failure.message : null, + })); + // Before the first setup, Settings offers it; a failed one waits for the button. + if (!ready || appAtomRegistry.get(phoneBoatCloudAtom).setup.status !== "ready") return; + yield* keepSpare(api, environment).pipe(Effect.forkDetach); + const version = yield* snapshotToBuild(api, yield* HttpClient.HttpClient, false).pipe( + Effect.orElseSucceed(() => null), + ); + if (version !== null && !stale()) void runPhoneBoatCloudSetup(version); + }).pipe( + Effect.catchTags({ + BoatApiError: (error) => + Effect.sync(() => { + if (error.code === "not_connected" && !stale()) setStatus(() => DISCONNECTED); + }), + }), + ), + ).catch(() => undefined); +} + +const spares = makeSpareKeeper(); +/** Keeps one spare VM ready for this phone's next start. */ +const keepSpare = (api: BoatApi, environment: string | null) => + Effect.suspend(() => + snapshotName === null ? Effect.void : spares.keep(api, snapshotName, environment), + ); + +let loaded: Promise | null = null; + +/** Loads the phone's Boat state once per launch; Settings, Cloud refreshes it on open. */ +export function ensurePhoneBoatCloudLoaded(): Promise { + loaded ??= refreshPhoneBoatCloud(); + return loaded; +} + +/** Checks the key with Boat, then keeps it in this phone's keychain. Null on success. */ +export async function connectPhoneBoatCloud(apiKey: string): Promise { + try { + await run( + Effect.gen(function* () { + yield* makeBoatApi(yield* HttpClient.HttpClient, apiKey).me(); + yield* MobileSecureStorage.use((storage) => storage.setItem(API_KEY_STORAGE_KEY, apiKey)); + }), + ); + } catch (error) { + return errorMessage(error); + } + keyGeneration += 1; + await refreshPhoneBoatCloud(); + return null; +} + +/** The key this phone keeps, so it can hand it to machines that lack it. */ +export function readPhoneBoatCloudKey(): Promise { + return run(MobileSecureStorage.use((storage) => storage.getItem(API_KEY_STORAGE_KEY))).catch( + () => null, + ); +} + +export async function disconnectPhoneBoatCloud(): Promise { + keyGeneration += 1; + await run( + MobileSecureStorage.use((storage) => + Effect.all([ + storage.removeItem(API_KEY_STORAGE_KEY), + storage.removeItem(ENVIRONMENT_STORAGE_KEY), + ]), + ), + ).catch(() => undefined); + setStatus(() => DISCONNECTED); +} + +/** Picks the environment for the phone's new VMs, and optionally changes what it passes. Null on success. */ +export async function configurePhoneBoatCloudEnvironment( + environmentId: string, + access?: BoatCloudEnvironmentAccess, +): Promise { + const chosen = appAtomRegistry + .get(phoneBoatCloudAtom) + .environments.find((environment) => environment.id === environmentId); + if (!chosen) return "Boat has no such environment."; + try { + await run( + Effect.gen(function* () { + const api = yield* phoneApi; + if (access) yield* api.updateEnvironment(environmentId, access); + yield* MobileSecureStorage.use((storage) => + storage.setItem(ENVIRONMENT_STORAGE_KEY, chosen.name), + ); + }), + ); + } catch (error) { + return errorMessage(error); + } + await refreshPhoneBoatCloud(); + return null; +} + +/** What the Boat cloud snapshot checks out: the most worked repositories on every machine. */ +export function boatCloudSnapshotRepositories(): Array { + const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom); + return mostWorkedRepositories( + [...enabledEnvironmentIds(catalog)].map((environmentId) => + appAtomRegistry.get(threadEnvironment.snapshotAtom(environmentId)), + ), + BOAT_CLOUD_SNAPSHOT_REPOSITORIES, + ); +} + +/** + * Builds the snapshot from the phone, with the latest Boat cloud build of t3. The phone + * has no skills; a machine holding the key saves the build again with its own. + */ +export async function runPhoneBoatCloudSetup(knownVersion?: string): Promise { + if (appAtomRegistry.get(phoneBoatCloudAtom).setup.status === "running") return; + setStatus((status) => ({ ...status, setup: { status: "running", step: null, error: null } })); + try { + await run( + Effect.gen(function* () { + const api = yield* phoneApi; + const version = knownVersion ?? (yield* latestCliRelease(yield* HttpClient.HttpClient)); + snapshotName = yield* buildSnapshot({ + api, + version, + repositories: boatCloudSnapshotRepositories(), + setStep: (step) => + Effect.sync(() => + setStatus((status) => ({ + ...status, + setup: { status: "running", step, error: null }, + })), + ), + }); + }), + ); + setStatus((status) => ({ + ...status, + setup: { status: "ready", step: null, error: null }, + snapshotReady: true, + })); + } catch (error) { + setStatus((status) => ({ + ...status, + setup: { status: "failed", step: status.setup.step, error: errorMessage(error) }, + })); + } +} + +/** + * Gets a VM ready for the repository from the phone, reporting each step as it + * goes. Resolves once its server is up; the checkout reports its own step after. + */ +export function startOnPhone(input: { + readonly repositoryUrl: string; + readonly baseBranch: string | null; + readonly paired?: ReadonlyArray | undefined; + readonly report: ReportStep; +}): Promise { + const repository = parseRepository(input.repositoryUrl); + if (repository === null) { + return Promise.reject(new Error("Boat cloud cannot clone this project's remote.")); + } + return run( + Effect.gen(function* () { + const api = yield* phoneApi; + if (snapshotName === null) { + snapshotName = startingSnapshot(yield* api.listSnapshots()); + } + if (snapshotName === null) { + return yield* new BoatApiError({ + status: 0, + code: "no_snapshot", + message: "Finish Boat cloud setup in Settings, Cloud.", + retryable: false, + }); + } + const { environment } = appAtomRegistry.get(phoneBoatCloudAtom); + const started = yield* startMachine({ + api, + repository, + baseBranch: input.baseBranch, + environment, + snapshot: snapshotName, + readySpare: yield* spares.take(snapshotName, environment), + // The phone keeps no record of stopped VMs, so it resumes them only for load. + knownWorkspaceRoots: () => [], + paired: input.paired ?? [], + report: input.report, + }); + // The start may have taken the spare, so the next one is readied while this one checks out. + yield* keepSpare(api, environment).pipe(Effect.forkDetach); + return { + sandboxId: started.sandboxId, + environmentId: started.environmentId, + httpBaseUrl: started.httpBaseUrl, + pairingCode: started.pairingCode, + workspaceRoot: started.workspaceRoot, + worktree: started.worktree, + }; + }), + ).finally(() => void refreshPhoneBoatCloud()); +} + +/** + * Turns the VM behind a paired URL back on. Its identity lives on its disk, so + * the saved pairing reconnects without a new code. Fails when Boat deleted it. + */ +export function wakeOnPhone(httpBaseUrl: string) { + return run( + Effect.gen(function* () { + const api = yield* phoneApi; + const sandbox = yield* findSandboxByHttpBaseUrl(api, httpBaseUrl); + if (sandbox === null) { + return yield* new BoatApiError({ + status: 0, + code: "gone", + message: "Boat deleted this VM, and this phone keeps no copy of it.", + retryable: false, + }); + } + return yield* wakeMachine(api, sandbox.id); + }), + ); +} diff --git a/apps/mobile/src/features/boxdCloud/BoxdCloudSettingsSections.tsx b/apps/mobile/src/features/boxdCloud/BoxdCloudSettingsSections.tsx new file mode 100644 index 0000000000000..2f8e7e0c048c0 --- /dev/null +++ b/apps/mobile/src/features/boxdCloud/BoxdCloudSettingsSections.tsx @@ -0,0 +1,175 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { BoatCloudSetup, BoxdCloudMachine } from "@t3tools/contracts"; +import { useState } from "react"; +import { Linking, View } from "react-native"; + +import { BoxdIcon } from "../../components/BoxdIcon"; +import { Button } from "../../components/ui/Button"; +import { ListRowLayout } from "../../components/ui/ListRowLayout"; +import { SecretTextInput } from "../../components/ui/SecretTextInput"; +import { cn } from "../../lib/cn"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { StepGlyph, type StepState } from "../boatCloud/BoatCloudSteps"; +import { boatCloudSnapshotRepositories } from "../boatCloud/phoneBoatCloud"; +import { SettingsSection } from "../settings/components/SettingsSection"; +import { boxdCloudHoldersAtom } from "./boxdCloud"; + +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_LABELS: Record = { + running: "Running", + asleep: "Asleep", + stopped: "Stopped", +}; + +function stepState(setup: BoatCloudSetup, index: number): StepState { + if (setup.status === "ready") return "done"; + if (setup.step === null || setup.status === "idle") return "pending"; + const current = SETUP_STEPS.findIndex((step) => step === setup.step); + if (index < current) return "done"; + if (index > current) return "pending"; + return setup.status === "failed" ? "failed" : "active"; +} + +function Separated(props: { readonly index: number; readonly children: React.ReactNode }) { + return ( + 0 && "border-t border-border-subtle")}>{props.children} + ); +} + +/** boxd cloud on the Cloud settings screen. A connected machine holds the key, never the phone. */ +export function BoxdCloudSettingsSections() { + const holders = useAtomValue(boxdCloudHoldersAtom); + 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"); + const holder = holders.find((candidate) => candidate.status.connected) ?? holders[0]; + if (!holder) return null; + const { environmentId, status } = holder; + const { connected, setup } = status; + const setUp = () => + runSetup({ environmentId, input: { repositories: boatCloudSnapshotRepositories() } }); + const submitKey = async (value: string) => { + const key = value.trim(); + if (!key || busy) return; + setBusy(true); + const result = await connect({ environmentId, input: { apiKey: key } }); + setBusy(false); + if (result._tag !== "Success") return; + setApiKey(""); + if (result.value.setup.status === "idle") void setUp(); + }; + + return ( + <> + + {connected ? ( + + } + label={status.account ?? "Connected"} + description="Connected" + /> + +