import { type PluginSurfaceProps, openExternalUrl, usePaseo, useRpc, } from "@getpaseo/plugin/client"; import type { PaseoAgent, PaseoWorkspace } from "@getpaseo/client"; import { ScrollView, TextInput, copyText, useToast } from "@getpaseo/plugin/client/ui"; import { useCallback, useEffect, useMemo, useState } from "react"; import { Pressable, Text, View } from "react-native"; import { type CheckpointSummary, type SpriteAgentSummary, type SpriteHostSummary, type SpriteSummary, type TokenSource, createCheckpointRpc, createSpriteRpc, destroySpriteRpc, ensureSpriteHostRpc, launchSpriteAgentRpc, listCheckpointsRpc, restoreCheckpointRpc, spriteAgentActionRpc, statusRpc, syncWorkspaceRpc, } from "../shared/contracts"; import { useOpenBaoAuth } from "./use-openbao-auth"; interface WorkersScreenProps extends PluginSurfaceProps { workspaceName?: string; workspaceDirectory?: string; } const PROVIDER_CHOICES = [ { id: "auto", label: "Auto" }, { id: "claude", label: "Claude" }, { id: "codex", label: "Codex" }, { id: "opencode", label: "OpenCode" }, { id: "pi", label: "Pi" }, ] as const; function getWorkspacePath(ws: PaseoWorkspace): string { return ws.workspaceDirectory || ws.projectRootPath; } export function FlySpritesWorkersScreen({ theme, layout, host, navigation, workspaceName, workspaceDirectory, }: WorkersScreenProps) { const paseo = usePaseo(); const toast = useToast(); const fetchStatus = useRpc(statusRpc); const createSprite = useRpc(createSpriteRpc); const ensureSpriteHost = useRpc(ensureSpriteHostRpc); const launchSpriteAgent = useRpc(launchSpriteAgentRpc); const spriteAgentAction = useRpc(spriteAgentActionRpc); const syncWorkspace = useRpc(syncWorkspaceRpc); const destroySprite = useRpc(destroySpriteRpc); const listCheckpoints = useRpc(listCheckpointsRpc); const createCheckpoint = useRpc(createCheckpointRpc); const restoreCheckpoint = useRpc(restoreCheckpointRpc); const [configured, setConfigured] = useState(false); const [tokenSource, setTokenSource] = useState("none"); const [remoteError, setRemoteError] = useState(null); const [sprites, setSprites] = useState([]); const [spriteHosts, setSpriteHosts] = useState([]); const [spriteAgents, setSpriteAgents] = useState([]); const [legacyAgents, setLegacyAgents] = useState([]); const [workspaces, setWorkspaces] = useState([]); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const [agentBusyId, setAgentBusyId] = useState(null); const [spriteNameInput, setSpriteNameInput] = useState(""); const [agentTitleInput, setAgentTitleInput] = useState(""); const [promptInput, setPromptInput] = useState(""); const [cwdInput, setCwdInput] = useState(workspaceDirectory ?? ""); const [providerInput, setProviderInput] = useState("auto"); const [syncBeforeOpen, setSyncBeforeOpen] = useState(true); const [checkpointsSprite, setCheckpointsSprite] = useState(null); const [checkpoints, setCheckpoints] = useState([]); useEffect(() => { if (workspaceDirectory && !cwdInput) { setCwdInput(workspaceDirectory); setSyncBeforeOpen(true); } }, [workspaceDirectory, cwdInput]); const refreshClusterState = useCallback(async () => { const [agentsRes, workspacesRes] = await Promise.all([ paseo.agents.list().catch(() => null), paseo.workspaces.list().catch(() => null), ]); if (agentsRes) { const flyAgents = agentsRes.entries .map((entry) => entry.agent) .filter((agent) => agent.provider === "fly-sprites" && !agent.archivedAt) .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); setLegacyAgents(flyAgents); } if (workspacesRes) { const activeWorkspaces = workspacesRes.entries.filter( (ws) => !ws.archivingAt && !ws.background && Boolean(getWorkspacePath(ws)), ); setWorkspaces(activeWorkspaces); setCwdInput((cur) => { if (cur || workspaceDirectory || activeWorkspaces.length === 0) return cur; return getWorkspacePath(activeWorkspaces[0]); }); } }, [paseo, workspaceDirectory]); const refresh = useCallback(async () => { setLoading(true); try { const [statusRes] = await Promise.all([ fetchStatus({ includeRemote: true }), refreshClusterState(), ]); setConfigured(statusRes.configured); setTokenSource(statusRes.tokenSource); setRemoteError(statusRes.remoteError); setSprites(statusRes.sprites); setSpriteHosts(statusRes.spriteHosts); setSpriteAgents(statusRes.spriteAgents); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setLoading(false); } }, [fetchStatus, refreshClusterState, toast]); useEffect(() => { void refresh(); }, [refresh]); const openbao = useOpenBaoAuth({ onConnected: refresh }); const pendingFlow = openbao.status?.pendingAuth?.status === "pending" ? openbao.status.pendingAuth : null; const hostBySprite = useMemo(() => { const map = new Map(); for (const h of spriteHosts) { map.set(h.spriteName, h); } return map; }, [spriteHosts]); const handleCreateSprite = async () => { setBusy(true); try { const res = await createSprite({ name: spriteNameInput.trim() || undefined, syncLocalPath: syncBeforeOpen && cwdInput.trim() ? cwdInput.trim() : undefined, }); if (!res.ok) { toast.error(res.error); return; } toast.show(`Sprite ${res.sprite.name} ready`, { variant: "success" }); setSpriteNameInput(res.sprite.name); await refresh(); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setBusy(false); } }; const handleConnectHost = async (name?: string) => { setBusy(true); try { const res = await ensureSpriteHost({ spriteName: name?.trim() || undefined, syncLocalPath: syncBeforeOpen && cwdInput.trim() ? cwdInput.trim() : undefined, }); if (!res.ok) { toast.error(res.error); return; } toast.show(`Sprite host ${res.spriteName} connected`, { variant: "success" }); setSpriteNameInput(res.spriteName); await refresh(); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setBusy(false); } }; const handleLaunchAgent = async () => { const targetSprite = spriteNameInput.trim(); const initialPrompt = promptInput.trim(); const title = agentTitleInput.trim(); setBusy(true); try { const res = await launchSpriteAgent({ spriteName: targetSprite || undefined, title: title || undefined, prompt: initialPrompt || undefined, syncLocalPath: syncBeforeOpen && cwdInput.trim() ? cwdInput.trim() : undefined, provider: providerInput || "auto", }); if (!res.ok) { toast.error(res.error); await refresh(); return; } toast.show(`Launched on ${res.spriteName} (${res.provider})`, { variant: "success" }); setSpriteNameInput(res.spriteName); setPromptInput(""); setAgentTitleInput(""); await refresh(); navigation?.openAgent({ agentId: res.agentId, serverId: res.serverId }); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setBusy(false); } }; const handleSpriteAgentAction = async ( agent: SpriteAgentSummary, action: "interrupt" | "archive", ) => { setAgentBusyId(agent.agentId); try { const res = await spriteAgentAction({ serverId: agent.serverId, agentId: agent.agentId, action, }); if (!res.ok) { toast.error(res.error ?? `Failed to ${action} agent`); return; } toast.show(action === "interrupt" ? "Interrupted agent turn" : "Archived agent", { variant: "info", }); await refresh(); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setAgentBusyId(null); } }; const handleArchiveLegacyAgent = async (agentId: string) => { setAgentBusyId(agentId); try { await paseo.agents.ref(agentId).archive(); toast.show("Archived legacy cluster agent", { variant: "info" }); setLegacyAgents((prev) => prev.filter((a) => a.id !== agentId)); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setAgentBusyId(null); } }; const handleSyncSprite = async (name: string) => { const localPath = cwdInput.trim(); if (!localPath) { toast.error("Select a workspace or enter a local folder path to sync."); return; } setBusy(true); try { const res = await syncWorkspace({ spriteName: name, localPath }); if (!res.ok) { toast.error(res.error); return; } toast.show(`Synced ${res.fileCount} files to ${name}:${res.remoteDir}`, { variant: "success" }); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setBusy(false); } }; const handleCheckpoint = async (name: string) => { setBusy(true); try { const res = await createCheckpoint({ spriteName: name, comment: `paseo-${new Date().toISOString()}`, }); if (!res.ok) { toast.error(res.error); return; } toast.show(`Checkpointed ${name}`, { variant: "success" }); await handleLoadCheckpoints(name); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setBusy(false); } }; const handleLoadCheckpoints = async (name: string) => { setCheckpointsSprite(name); try { const res = await listCheckpoints({ spriteName: name }); if (!res.ok) { toast.error(res.error); return; } setCheckpoints(res.checkpoints); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } }; const handleRestoreCheckpoint = async (name: string, checkpointId: string) => { setBusy(true); try { const res = await restoreCheckpoint({ spriteName: name, checkpointId }); if (!res.ok) { toast.error(res.error); return; } toast.show(`Restored ${name} to ${checkpointId}`, { variant: "success" }); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setBusy(false); } }; const handleDestroySprite = async (name: string) => { setBusy(true); try { const res = await destroySprite({ spriteName: name }); if (!res.ok) { toast.error(res.error ?? "Failed to delete sprite"); return; } toast.show(`Deleted sprite ${name}`, { variant: "info" }); if (checkpointsSprite === name) { setCheckpointsSprite(null); setCheckpoints([]); } await refresh(); } catch (error) { toast.error(error instanceof Error ? error.message : String(error)); } finally { setBusy(false); } }; const styles = useMemo( () => ({ screen: { flex: 1, backgroundColor: theme.colors.surface0 }, body: { padding: layout.compact ? 16 : 24, gap: 14 }, headerRow: { flexDirection: "row" as const, justifyContent: "space-between" as const, alignItems: "center" as const, gap: 8, }, title: { color: theme.colors.foreground, fontSize: 18, fontWeight: "600" as const }, sectionTitle: { color: theme.colors.foreground, fontSize: 15, fontWeight: "600" as const, marginTop: 6 }, muted: { color: theme.colors.foregroundMuted, fontSize: 12 }, error: { color: theme.colors.statusDanger, fontSize: 12 }, card: { borderWidth: 1, borderColor: theme.colors.border, backgroundColor: theme.colors.surface1, borderRadius: 10, padding: 12, gap: 8, }, input: { borderWidth: 1, borderColor: theme.colors.border, backgroundColor: theme.colors.surface0, color: theme.colors.foreground, borderRadius: 8, paddingHorizontal: 10, paddingVertical: 8, fontSize: 13, }, row: { flexDirection: "row" as const, flexWrap: "wrap" as const, gap: 8, alignItems: "center" as const }, btnPrimary: { backgroundColor: theme.colors.accent, borderRadius: 8, paddingHorizontal: 12, paddingVertical: 8, }, btnPrimaryText: { color: theme.colors.accentForeground, fontSize: 12, fontWeight: "600" as const }, btnSecondary: { borderWidth: 1, borderColor: theme.colors.border, backgroundColor: theme.colors.surface2, borderRadius: 8, paddingHorizontal: 10, paddingVertical: 6, }, btnSecondaryText: { color: theme.colors.foreground, fontSize: 12, fontWeight: "500" as const }, btnDanger: { borderWidth: 1, borderColor: theme.colors.statusDanger, borderRadius: 8, paddingHorizontal: 10, paddingVertical: 6, }, btnDangerText: { color: theme.colors.statusDanger, fontSize: 12, fontWeight: "500" as const }, chip: { borderWidth: 1, borderColor: theme.colors.border, backgroundColor: theme.colors.surface0, borderRadius: 999, paddingHorizontal: 10, paddingVertical: 4, }, chipActive: { borderWidth: 1, borderColor: theme.colors.accent, backgroundColor: theme.colors.surface2, borderRadius: 999, paddingHorizontal: 10, paddingVertical: 4, }, chipText: { color: theme.colors.foregroundMuted, fontSize: 12 }, chipActiveText: { color: theme.colors.foreground, fontSize: 12, fontWeight: "600" as const }, monoBox: { backgroundColor: theme.colors.surface0, borderWidth: 1, borderColor: theme.colors.border, borderRadius: 8, padding: 10, }, }), [theme, layout.compact], ); const statusColor = (status: string) => { if (status === "running" || status === "initializing" || status === "connecting") { return theme.colors.accent; } if (status === "error" || status === "offline") return theme.colors.statusDanger; if (status === "idle" || status === "online") return theme.colors.statusSuccess; return theme.colors.foregroundMuted; }; return ( Fly Sprites Agents Host: {host.label} · Token: {tokenSource} {workspaceName ? ` · Workspace: ${workspaceName}` : ""} void refresh()} disabled={loading}> {loading ? "Refreshing…" : "Refresh"} {!configured ? ( No Fly Sprites API token loaded. Sign in with Zitadel to pull FLY_TOKEN from OpenBao, or configure a token in Settings → Fly Sprites Workers. {openbao.status?.lastError ? ( OpenBao: {openbao.status.lastError} ) : null} {pendingFlow ? ( Waiting for Zitadel approval · Code: {pendingFlow.userCode} void openExternalUrl( pendingFlow.verificationUriComplete || pendingFlow.verificationUri, ) } > Open Zitadel Login void copyText(pendingFlow.userCode)} > Copy Code ) : ( void openbao.startLogin()} disabled={openbao.busy} > {openbao.busy ? "Starting…" : openbao.status?.authenticated ? "Re-authenticate Zitadel" : "Sign in with Zitadel"} {openbao.status?.authenticated ? ( void openbao.pullNow()} disabled={openbao.busy} > Pull from OpenBao ) : null} )} ) : null} {remoteError ? ( Remote API error: {remoteError} ) : null} Launch Agent on Sprite Host Provisions Paseo inside the Sprite and connects it as its own host so workspaces and agents appear under the Sprite host. {workspaces.length > 0 && !workspaceDirectory ? ( {workspaces.map((ws) => { const wsPath = getWorkspacePath(ws); const active = cwdInput === wsPath; return ( setCwdInput(wsPath)} > {ws.title || ws.name || wsPath} ); })} ) : null} {PROVIDER_CHOICES.map((choice) => { const active = providerInput === choice.id; return ( setProviderInput(choice.id)} > {choice.label} ); })} setSyncBeforeOpen((v) => !v)} > {syncBeforeOpen ? "Sync workspace: ON" : "Sync workspace: OFF"} void handleCreateSprite()} disabled={busy || !configured} > Create Sprite void handleConnectHost(spriteNameInput)} disabled={busy || !configured} > Connect Host void handleLaunchAgent()} disabled={busy || !configured} > {busy ? "Working…" : "Launch Agent"} Sprite Host Agents ({spriteAgents.length}) {spriteAgents.length === 0 ? ( No agents on connected Sprite hosts yet. Launch one above to create it under its Sprite host. ) : ( spriteAgents.map((agent) => { const isBusy = agentBusyId === agent.agentId; return ( {agent.title || `Agent ${agent.agentId.slice(0, 8)}`} {agent.status} {agent.pendingPermissionsCount > 0 ? " · permission" : ""} Host: {agent.hostLabel} · {agent.provider} {agent.model ? `/${agent.model}` : ""} · {agent.cwd} {agent.lastError ? {agent.lastError} : null} {navigation ? ( navigation.openAgent({ agentId: agent.agentId, serverId: agent.serverId }) } > Open ) : null} {agent.status === "running" ? ( void handleSpriteAgentAction(agent, "interrupt")} disabled={isBusy} > Interrupt ) : null} void handleSpriteAgentAction(agent, "archive")} disabled={isBusy} > Archive ); }) )} {legacyAgents.length > 0 ? ( <> Cluster-Hosted Fly Agents ({legacyAgents.length}) {legacyAgents.map((agent) => ( {agent.title || `Agent ${agent.id.slice(0, 8)}`} {agent.status} Cluster host ({host.label}) · {agent.cwd} {navigation ? ( navigation.openAgent({ agentId: agent.id, serverId: host.id })} > Open ) : null} void handleArchiveLegacyAgent(agent.id)} disabled={agentBusyId === agent.id} > Archive ))} ) : null} Remote Fly Sprites ({sprites.length}) {sprites.length === 0 ? ( No Fly Sprites found. ) : ( sprites.map((sprite) => { const connectedHost = hostBySprite.get(sprite.name); return ( {sprite.name} VM: {sprite.status} {connectedHost ? ` · Host: ${connectedHost.status}` : " · Host: not connected"} {connectedHost?.error ? ( Host error: {connectedHost.error} ) : null} {sprite.url ? {sprite.url} : null} setSpriteNameInput(sprite.name)} > Select {!connectedHost || connectedHost.status !== "online" ? ( void handleConnectHost(sprite.name)} disabled={busy} > Connect Host ) : null} void handleSyncSprite(sprite.name)} disabled={busy} > Sync Here void handleCheckpoint(sprite.name)} disabled={busy} > Checkpoint void handleLoadCheckpoints(sprite.name)} > Checkpoints void handleDestroySprite(sprite.name)} disabled={busy} > Delete {checkpointsSprite === sprite.name ? ( Checkpoints for {sprite.name} ({checkpoints.length}) {checkpoints.length === 0 ? ( No checkpoints. ) : ( checkpoints.map((cp) => ( {cp.id} {cp.comment ? `— ${cp.comment}` : ""} void handleRestoreCheckpoint(sprite.name, cp.id)} disabled={busy} > Restore )) )} ) : null} ); }) )} ); }