import { DownloadConsentPrompt, useDownloadConsent } from "./consent"; import { useRpc } from "@getpaseo/plugin/client"; import { useMutation } from "@tanstack/react-query"; import { useState } from "react"; import { Text, View } from "react-native"; import { finishTemplateRpc, prepareTemplateRpc, refResultSchema, shellResultSchema } from "../shared/rpc"; import { TEMPLATE_TAG_PATTERN } from "../shared/spec"; import { errorMessage, formatBytes, plural, shortRef } from "./format"; import { Frame } from "./frame"; import { Actions, Button, Choice, ConfirmButton, Field, Note, Pill, Section, SwitchRow, kicker, mono, text, tint, toneColor, type Theme, } from "./kit"; import type { PanelTabProps } from "./panel"; import { useAwaitOperation, useInvalidateAll, useOpenTerminal, useRemoveTemplate, useRepoSettings, useSandboxAction, useSaveTemplate, useTemplates, } from "./queries"; function defaultTag(repoName: string): string { const slug = repoName .toLowerCase() .replace(/[^a-z0-9._-]+/g, "-") .replace(/^[-.]+|[-.]+$/g, "") || "template"; const now = new Date(); const pad = (value: number) => String(value).padStart(2, "0"); const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`; return `${slug}:${stamp}`; } type TemplateSummary = NonNullable["data"]>["templates"][number]; /** What keeps a template: settings that pick it, and sandboxes created from it. */ function usage(template: TemplateSummary, data: PanelTabProps["data"]): string { const otherRepos = template.users.filter((user) => user !== "default" && user !== data.repoKey).length; const otherSandboxes = template.sandboxes.filter((name) => name !== data.name).length; const parts = [ template.users.includes(data.repoKey) ? "used by this repository" : null, template.users.includes("default") ? "the default" : null, otherRepos > 0 ? `used by ${plural(otherRepos, "other repository", "other repositories")}` : null, template.sandboxes.includes(data.name) ? "this sandbox runs it" : null, otherSandboxes > 0 ? `${plural(otherSandboxes, "other sandbox", "other sandboxes")} ${otherSandboxes === 1 ? "runs" : "run"} it` : null, ].filter(Boolean); return parts.length > 0 ? parts.join(" · ") : "unused"; } /** Nothing picks it and no sandbox runs it: the server removes only those. */ const removable = (template: TemplateSummary) => template.users.length === 0 && template.sandboxes.length === 0; export function TemplateTab({ data, theme, compact, header, workspaceId, directory }: PanelTabProps) { const templates = useTemplates(); const remove = useRemoveTemplate(); const { repo, save, settings } = useRepoSettings(data.repoKey); const [selectError, setSelectError] = useState(null); const globalTemplate = settings.status === "ready" ? settings.values.template : ""; const custom = (templates.data?.templates ?? []).filter((template) => !template.base); const choices: { value: string; title: string; detail: string; removable: boolean }[] = [ { value: "", title: globalTemplate ? `Default · ${shortRef(globalTemplate)}` : "Default · sbx image", detail: "What the plugin settings pick for every repository", removable: false, }, ...custom.map((template) => ({ value: template.ref, title: shortRef(template.ref), detail: [formatBytes(template.sizeBytes), usage(template, data)].join(" · "), removable: removable(template), })), ]; if (repo?.template && !choices.some((choice) => choice.value === repo.template)) { choices.push({ value: repo.template, title: shortRef(repo.template), detail: "Missing: sbx no longer has it", removable: false, }); } const keptBySandbox = custom.some((template) => template.users.length === 0 && template.sandboxes.length > 0); return (
{data.status ? ( This sandbox runs {data.template.sandbox ? shortRef(data.template.sandbox) : data.template.status === "unknown" ? "an unrecorded template" : "the sbx image"} {data.template.status === "diverged" ? ( ) : data.template.status === "match" ? ( ) : null} ) : null} {repo ? ( {choices.map((choice) => ( remove.mutate(choice.value)} /> ) : null } onPress={() => { if (repo.template === choice.value) return; setSelectError(null); save({ template: choice.value }).catch((error: unknown) => setSelectError(errorMessage(error))); }} /> ))} ) : null} {keptBySandbox ? ( A template a sandbox was created from can be removed once that sandbox is recreated or removed. ) : null} {templates.error ? ( {errorMessage(templates.error)} ) : null} {remove.error ? ( {errorMessage(remove.error)} ) : null} {selectError ? ( {selectError} ) : null}
save({ template: ref })} /> {data.status ? save({ template: ref })} /> : null} ); } function Steps({ theme, current }: { theme: Theme; current: number }) { const steps = ["Open a clean shell", "Install your tools", "Save as a template"]; const accent = toneColor(theme, "accent"); return ( {steps.map((step, index) => { const done = index < current; const active = index === current; return ( {done ? "✓" : index + 1} {step} {index < steps.length - 1 ? → : null} ); })} ); } function Prepare({ data, theme, workspaceId, directory, onSaved, }: Pick & { onSaved(ref: string): Promise }) { const action = useSandboxAction(); const invalidate = useInvalidateAll(); const openTerminal = useOpenTerminal(workspaceId); const prepareRpc = useRpc(prepareTemplateRpc); const finishRpc = useRpc(finishTemplateRpc); const awaitOperation = useAwaitOperation(); const prepare = useMutation({ mutationFn: async () => openTerminal(shellResultSchema.parse(await awaitOperation(await prepareRpc({ workspaceId, directory })))), onSettled: invalidate, }); const finish = useMutation({ mutationFn: async (input: { name: string; tag: string }) => refResultSchema.parse(await awaitOperation(await finishRpc(input))), onSettled: invalidate, }); const prep = data.templatePrep; // Without a repository template, the preparation starts from sbx's kit image. const consent = useDownloadConsent(); return (
{prep ? ( <> {`Preparation sandbox ${prep}: install your tools from its shell, then save it here.`}
); } function SaveSandbox({ data, theme, onSaved }: Pick & { onSaved(ref: string): Promise }) { const saveTemplate = useSaveTemplate(); const [open, setOpen] = useState(false); return (
Saving stops this sandbox, and needs every agent in it archived. The template captures its whole filesystem, including /home/agent: shell history, caches and any login tokens stored there. {open ? ( setOpen(false)} onSubmit={async (tag, useForRepo) => { const { ref } = await saveTemplate.mutateAsync({ name: data.name, tag }); if (useForRepo) await onSaved(ref); setOpen(false); }} /> ) : (
); } function SaveForm({ theme, repoName, pending, error, submitLabel, onSubmit, onCancel, }: { theme: Theme; repoName: string; pending: boolean; error: unknown; submitLabel: string; onSubmit(tag: string, useForRepo: boolean): Promise; onCancel?(): void; }) { const [tag, setTag] = useState(() => defaultTag(repoName)); const [useForRepo, setUseForRepo] = useState(true); const [submitError, setSubmitError] = useState(null); const invalid = !TEMPLATE_TAG_PATTERN.test(tag.trim()); const shown = submitError ?? (error ? errorMessage(error) : null); return (