Files
fly-sprites-workers/client/workers-screen.tsx
T

570 lines
19 KiB
TypeScript

import {
type PluginHostProps,
useRpc,
useSubscription,
} from "@getpaseo/plugin/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 SpriteSummary,
type WorkerSummary,
createCheckpointRpc,
createSpriteRpc,
destroySpriteRpc,
listCheckpointsRpc,
restoreCheckpointRpc,
spawnWorkerRpc,
statusRpc,
stopWorkerRpc,
syncWorkspaceRpc,
watchWorkersSub,
workerLogsRpc,
} from "../shared/contracts";
interface WorkersScreenProps extends PluginHostProps {
workspaceName?: string;
workspaceDirectory?: string;
}
export function FlySpritesWorkersScreen({
theme,
layout,
host,
workspaceName,
workspaceDirectory,
}: WorkersScreenProps) {
const toast = useToast();
const fetchStatus = useRpc(statusRpc);
const createSprite = useRpc(createSpriteRpc);
const syncWorkspace = useRpc(syncWorkspaceRpc);
const spawnWorker = useRpc(spawnWorkerRpc);
const stopWorker = useRpc(stopWorkerRpc);
const fetchLogs = useRpc(workerLogsRpc);
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<"settings" | "env" | "none">("none");
const [remoteError, setRemoteError] = useState<string | null>(null);
const [sprites, setSprites] = useState<SpriteSummary[]>([]);
const [workers, setWorkers] = useState<WorkerSummary[]>([]);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [spriteNameInput, setSpriteNameInput] = useState("");
const [commandInput, setCommandInput] = useState("");
const [syncPathInput, setSyncPathInput] = useState(workspaceDirectory ?? "");
const [syncBeforeSpawn, setSyncBeforeSpawn] = useState(Boolean(workspaceDirectory));
const [selectedWorkerId, setSelectedWorkerId] = useState<string | null>(null);
const [fullLogs, setFullLogs] = useState<string>("");
const [checkpointsSprite, setCheckpointsSprite] = useState<string | null>(null);
const [checkpoints, setCheckpoints] = useState<CheckpointSummary[]>([]);
useEffect(() => {
if (workspaceDirectory && !syncPathInput) {
setSyncPathInput(workspaceDirectory);
setSyncBeforeSpawn(true);
}
}, [workspaceDirectory, syncPathInput]);
const watchInput = useMemo(() => ({}), []);
useSubscription(watchWorkersSub, watchInput, (event) => {
setWorkers(event.workers);
});
const refresh = useCallback(async () => {
setLoading(true);
try {
const res = await fetchStatus({ includeRemote: true });
setConfigured(res.configured);
setTokenSource(res.tokenSource);
setRemoteError(res.remoteError);
setSprites(res.sprites);
setWorkers(res.workers);
} catch (error) {
toast.error(error instanceof Error ? error.message : String(error));
} finally {
setLoading(false);
}
}, [fetchStatus, toast]);
useEffect(() => {
void refresh();
}, [refresh]);
const selectedWorker = useMemo(
() => workers.find((w) => w.workerId === selectedWorkerId) ?? null,
[workers, selectedWorkerId],
);
useEffect(() => {
if (!selectedWorkerId) return;
let cancelled = false;
const load = async () => {
const res = await fetchLogs({ workerId: selectedWorkerId }).catch(() => null);
if (!cancelled && res?.ok) {
setFullLogs(res.output);
}
};
void load();
return () => {
cancelled = true;
};
}, [selectedWorkerId, workers, fetchLogs]);
const handleCreateSprite = async () => {
setBusy(true);
try {
const res = await createSprite({
name: spriteNameInput.trim() || undefined,
syncLocalPath: syncBeforeSpawn && syncPathInput.trim() ? syncPathInput.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 handleSpawnWorker = async () => {
const command = commandInput.trim();
if (!command) {
toast.error("Enter a worker command to run.");
return;
}
setBusy(true);
try {
const res = await spawnWorker({
spriteName: spriteNameInput.trim() || undefined,
command,
syncLocalPath: syncBeforeSpawn && syncPathInput.trim() ? syncPathInput.trim() : undefined,
});
if (!res.ok) {
toast.error(res.error);
return;
}
toast.show(`Spawned ${res.worker.workerId} on ${res.worker.spriteName}`, { variant: "success" });
setSelectedWorkerId(res.worker.workerId);
setCommandInput("");
await refresh();
} catch (error) {
toast.error(error instanceof Error ? error.message : String(error));
} finally {
setBusy(false);
}
};
const handleSyncSprite = async (name: string) => {
const localPath = syncPathInput.trim();
if (!localPath) {
toast.error("Enter a local workspace 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 },
monoBox: {
backgroundColor: theme.colors.surface0,
borderWidth: 1,
borderColor: theme.colors.border,
borderRadius: 8,
padding: 10,
},
monoText: {
color: theme.colors.foreground,
fontSize: 12,
fontFamily: "monospace",
},
}),
[theme, layout.compact],
);
const statusColor = (status: WorkerSummary["status"]) => {
if (status === "completed") return theme.colors.statusSuccess;
if (status === "failed") return theme.colors.statusDanger;
if (status === "running" || status === "starting") return theme.colors.accent;
return theme.colors.foregroundMuted;
};
return (
<ScrollView style={styles.screen} contentContainerStyle={styles.body}>
<View style={styles.headerRow}>
<View>
<Text style={styles.title}>Fly Sprites Workers</Text>
<Text style={styles.muted}>
Host: {host.label} · Token: {tokenSource}
{workspaceName ? ` · Workspace: ${workspaceName}` : ""}
</Text>
</View>
<Pressable style={styles.btnSecondary} onPress={() => void refresh()} disabled={loading}>
<Text style={styles.btnSecondaryText}>{loading ? "Refreshing…" : "Refresh"}</Text>
</Pressable>
</View>
{!configured ? (
<View style={styles.card}>
<Text style={styles.error}>
No Fly Sprites API token configured. Open Settings → Fly Sprites Workers or set SPRITES_TOKEN on the host.
</Text>
</View>
) : null}
{remoteError ? (
<View style={styles.card}>
<Text style={styles.error}>Remote API error: {remoteError}</Text>
</View>
) : null}
<View style={styles.card}>
<Text style={styles.sectionTitle}>Spawn Worker / Create Sprite</Text>
<TextInput
style={styles.input}
value={spriteNameInput}
onChangeText={setSpriteNameInput}
placeholder="Sprite name (blank creates a new paseo-worker-* sprite)"
placeholderTextColor={theme.colors.foregroundMuted}
/>
<TextInput
style={styles.input}
value={commandInput}
onChangeText={setCommandInput}
placeholder="Command to run (e.g. npm test, or claude -p '...')"
placeholderTextColor={theme.colors.foregroundMuted}
/>
<TextInput
style={styles.input}
value={syncPathInput}
onChangeText={setSyncPathInput}
placeholder="Optional local folder to sync to /workspace"
placeholderTextColor={theme.colors.foregroundMuted}
/>
<View style={styles.row}>
<Pressable
style={styles.btnSecondary}
onPress={() => setSyncBeforeSpawn((v) => !v)}
>
<Text style={styles.btnSecondaryText}>
{syncBeforeSpawn ? "Sync workspace: ON" : "Sync workspace: OFF"}
</Text>
</Pressable>
<Pressable
style={styles.btnSecondary}
onPress={() => void handleCreateSprite()}
disabled={busy || !configured}
>
<Text style={styles.btnSecondaryText}>Create Sprite</Text>
</Pressable>
<Pressable
style={styles.btnPrimary}
onPress={() => void handleSpawnWorker()}
disabled={busy || !configured}
>
<Text style={styles.btnPrimaryText}>Spawn Worker</Text>
</Pressable>
</View>
</View>
<Text style={styles.sectionTitle}>Tracked Workers ({workers.length})</Text>
{workers.length === 0 ? (
<View style={styles.card}>
<Text style={styles.muted}>No workers spawned on this daemon yet.</Text>
</View>
) : (
workers.map((worker) => (
<View key={worker.workerId} style={styles.card}>
<View style={styles.headerRow}>
<Text style={{ color: theme.colors.foreground, fontWeight: "600", fontSize: 13 }}>
{worker.workerId} · {worker.spriteName}
</Text>
<Text style={{ color: statusColor(worker.status), fontSize: 12, fontWeight: "600" }}>
{worker.status}
{worker.exitCode !== null ? ` (${worker.exitCode})` : ""}
</Text>
</View>
<Text style={styles.muted} numberOfLines={2}>
$ {worker.command}
</Text>
<Text style={styles.muted}>
cwd: {worker.cwd} · started: {worker.startedAt}
</Text>
{worker.error ? <Text style={styles.error}>{worker.error}</Text> : null}
<View style={styles.row}>
<Pressable
style={styles.btnSecondary}
onPress={() =>
setSelectedWorkerId((cur) => (cur === worker.workerId ? null : worker.workerId))
}
>
<Text style={styles.btnSecondaryText}>
{selectedWorkerId === worker.workerId ? "Hide Logs" : "View Logs"}
</Text>
</Pressable>
{worker.status === "running" || worker.status === "starting" ? (
<Pressable
style={styles.btnDanger}
onPress={() => void stopWorker({ workerId: worker.workerId })}
>
<Text style={styles.btnDangerText}>Stop</Text>
</Pressable>
) : null}
</View>
{selectedWorker?.workerId === worker.workerId ? (
<View style={styles.monoBox}>
<View style={[styles.headerRow, { marginBottom: 6 }]}>
<Text style={styles.muted}>Output ({worker.outputBytes} bytes)</Text>
<Pressable
onPress={() => {
void copyText(fullLogs || worker.outputTail);
toast.show("Copied worker output", { variant: "info" });
}}
>
<Text style={{ color: theme.colors.accent, fontSize: 12 }}>Copy</Text>
</Pressable>
</View>
<Text style={styles.monoText}>
{fullLogs || worker.outputTail || "(no output yet)"}
</Text>
</View>
) : null}
</View>
))
)}
<Text style={styles.sectionTitle}>Remote Fly Sprites ({sprites.length})</Text>
{sprites.length === 0 ? (
<View style={styles.card}>
<Text style={styles.muted}>No Fly Sprites found.</Text>
</View>
) : (
sprites.map((sprite) => (
<View key={sprite.name} style={styles.card}>
<View style={styles.headerRow}>
<Text style={{ color: theme.colors.foreground, fontWeight: "600", fontSize: 13 }}>
{sprite.name}
</Text>
<Text style={styles.muted}>
{sprite.status}
{sprite.primaryRegion ? ` · ${sprite.primaryRegion}` : ""}
</Text>
</View>
{sprite.url ? <Text style={styles.muted}>{sprite.url}</Text> : null}
<View style={styles.row}>
<Pressable
style={styles.btnSecondary}
onPress={() => setSpriteNameInput(sprite.name)}
>
<Text style={styles.btnSecondaryText}>Select</Text>
</Pressable>
<Pressable
style={styles.btnSecondary}
onPress={() => void handleSyncSprite(sprite.name)}
disabled={busy}
>
<Text style={styles.btnSecondaryText}>Sync Here</Text>
</Pressable>
<Pressable
style={styles.btnSecondary}
onPress={() => void handleCheckpoint(sprite.name)}
disabled={busy}
>
<Text style={styles.btnSecondaryText}>Checkpoint</Text>
</Pressable>
<Pressable
style={styles.btnSecondary}
onPress={() => void handleLoadCheckpoints(sprite.name)}
>
<Text style={styles.btnSecondaryText}>Checkpoints</Text>
</Pressable>
<Pressable
style={styles.btnDanger}
onPress={() => void handleDestroySprite(sprite.name)}
disabled={busy}
>
<Text style={styles.btnDangerText}>Delete</Text>
</Pressable>
</View>
{checkpointsSprite === sprite.name ? (
<View style={styles.monoBox}>
<Text style={[styles.muted, { marginBottom: 4 }]}>
Checkpoints for {sprite.name} ({checkpoints.length})
</Text>
{checkpoints.length === 0 ? (
<Text style={styles.muted}>No checkpoints.</Text>
) : (
checkpoints.map((cp) => (
<View key={cp.id} style={[styles.headerRow, { paddingVertical: 4 }]}>
<Text style={styles.muted}>
{cp.id} {cp.comment ? `— ${cp.comment}` : ""}
</Text>
<Pressable
style={styles.btnSecondary}
onPress={() => void handleRestoreCheckpoint(sprite.name, cp.id)}
disabled={busy}
>
<Text style={styles.btnSecondaryText}>Restore</Text>
</Pressable>
</View>
))
)}
</View>
) : null}
</View>
))
)}
</ScrollView>
);
}