From 6a34a6f3c423a7c57616762eb4cea2b7da52eaf3 Mon Sep 17 00:00:00 2001 From: soryu Date: Sun, 22 Feb 2026 14:39:14 +0000 Subject: feat: Add daemon page with download binary and Cloudflare Agent setup (#77) * feat: soryu-co/soryu - makima: Create DaemonList and DaemonDetail page components * feat: soryu-co/soryu - makima: Add daemon page routes, CSS styles, and navigation * feat: soryu-co/soryu - makima: Create daemon page with download and monitoring * WIP: heartbeat checkpoint * WIP: heartbeat checkpoint * feat: soryu-co/soryu - makima: Integrate Cloudflare Agent setup into daemon page --- makima/frontend/src/components/NavStrip.tsx | 1 + .../frontend/src/hooks/useMultiTaskSubscription.ts | 84 --- makima/frontend/src/main.tsx | 9 + makima/frontend/src/routes/daemon.tsx | 746 +++++++++++++++++++++ makima/frontend/tsconfig.tsbuildinfo | 2 +- 5 files changed, 757 insertions(+), 85 deletions(-) create mode 100644 makima/frontend/src/routes/daemon.tsx (limited to 'makima/frontend') diff --git a/makima/frontend/src/components/NavStrip.tsx b/makima/frontend/src/components/NavStrip.tsx index 9556458..1bd0891 100644 --- a/makima/frontend/src/components/NavStrip.tsx +++ b/makima/frontend/src/components/NavStrip.tsx @@ -17,6 +17,7 @@ const NAV_LINKS: NavLink[] = [ { label: "Mesh", href: "/mesh", requiresAuth: true }, { label: "Daemons", href: "/daemons", requiresAuth: true }, { label: "History", href: "/history", requiresAuth: true }, + { label: "Daemon", href: "/daemon", requiresAuth: true }, ]; export function NavStrip() { diff --git a/makima/frontend/src/hooks/useMultiTaskSubscription.ts b/makima/frontend/src/hooks/useMultiTaskSubscription.ts index 41489c7..b229e90 100644 --- a/makima/frontend/src/hooks/useMultiTaskSubscription.ts +++ b/makima/frontend/src/hooks/useMultiTaskSubscription.ts @@ -31,8 +31,6 @@ export function useMultiTaskSubscription(options: UseMultiTaskSubscriptionOption const backfilledTasksRef = useRef>(new Set()); const taskMapRef = useRef(taskMap); const enabledRef = useRef(enabled); - /** Track which task IDs have already been backfilled to avoid re-fetching */ - const backfilledTasksRef = useRef>(new Set()); // Keep refs in sync useEffect(() => { @@ -43,88 +41,6 @@ export function useMultiTaskSubscription(options: UseMultiTaskSubscriptionOption enabledRef.current = enabled; }, [enabled]); - /** Max number of historical events to backfill per task */ - const MAX_BACKFILL_PER_TASK = 200; - - /** - * Convert a TaskEvent (from the REST API) into a MultiTaskOutputEntry. - * Only converts events with event_type === 'output'. - */ - const convertTaskEventToEntry = useCallback( - (event: TaskEvent): MultiTaskOutputEntry | null => { - if (event.eventType !== "output") return null; - const data = event.eventData; - if (!data) return null; - - return { - taskId: event.taskId, - messageType: (data.messageType as string) || "system", - content: (data.content as string) || "", - toolName: data.toolName as string | undefined, - toolInput: data.toolInput as Record | undefined, - isError: data.isError as boolean | undefined, - costUsd: data.costUsd as number | undefined, - durationMs: data.durationMs as number | undefined, - isPartial: false, - taskLabel: - taskMapRef.current.get(event.taskId) || event.taskId, - receivedAt: new Date(event.createdAt).getTime(), - isBackfill: true, - }; - }, - [] - ); - - /** - * Backfill historical log entries for a task from the REST API. - * Only fetches once per task ID (tracked in backfilledTasksRef). - */ - const backfillTask = useCallback( - async (taskId: string) => { - if (backfilledTasksRef.current.has(taskId)) return; - backfilledTasksRef.current.add(taskId); - - try { - const response = await listTaskEvents(taskId); - const events = response.events; - - // The API returns events in DESC order; reverse to get chronological ASC - const chronologicalEvents = [...events].reverse(); - - // Filter to output events and convert, limiting to MAX_BACKFILL_PER_TASK - const backfillEntries: MultiTaskOutputEntry[] = []; - for (const event of chronologicalEvents) { - const entry = convertTaskEventToEntry(event); - if (entry) { - backfillEntries.push(entry); - if (backfillEntries.length >= MAX_BACKFILL_PER_TASK) break; - } - } - - if (backfillEntries.length === 0) return; - - // Prepend historical entries before any existing live entries for this task, - // maintaining overall chronological order across all tasks - setEntries((prev) => { - // Merge backfill entries with existing entries, maintaining chronological order - const merged = [...backfillEntries, ...prev]; - // Sort by receivedAt to ensure proper chronological ordering - merged.sort((a, b) => a.receivedAt - b.receivedAt); - // Trim to maxEntries - if (merged.length > maxEntries) { - return merged.slice(merged.length - maxEntries); - } - return merged; - }); - } catch (e) { - console.error(`Failed to backfill task events for ${taskId}:`, e); - // Remove from backfilled set so it can be retried - backfilledTasksRef.current.delete(taskId); - } - }, - [convertTaskEventToEntry, maxEntries] - ); - // Derive task IDs from the map, stabilized to avoid unnecessary effect triggers const taskIdsKey = useMemo(() => Array.from(taskMap.keys()).sort().join(","), [taskMap]); const taskIds = useMemo(() => Array.from(taskMap.keys()), [taskIdsKey]); // eslint-disable-line react-hooks/exhaustive-deps diff --git a/makima/frontend/src/main.tsx b/makima/frontend/src/main.tsx index 32c05ba..a75d6a0 100644 --- a/makima/frontend/src/main.tsx +++ b/makima/frontend/src/main.tsx @@ -21,6 +21,7 @@ import SettingsPage from "./routes/settings"; import ContractFilePage from "./routes/contract-file"; import SpeakPage from "./routes/speak"; import DirectivesPage from "./routes/directives"; +import DaemonPage from "./routes/daemon"; createRoot(document.getElementById("root")!).render( @@ -161,6 +162,14 @@ createRoot(document.getElementById("root")!).render( } /> + + + + } + /> + {children} + + ); +} + +function ErrorAlert({ children }: { children: React.ReactNode }) { + return ( +
+ {children} +
+ ); +} + +function CodeBlock({ children }: { children: React.ReactNode }) { + return ( + + {children} + + ); +} + +function StepNumber({ n }: { n: number }) { + return ( + + {n} + + ); +} + +// ============================================================================= +// Download Section +// ============================================================================= + +function DownloadSection() { + const [release, setRelease] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [userPlatform] = useState(detectPlatform); + + useEffect(() => { + const fetchRelease = async () => { + try { + setLoading(true); + setError(null); + const res = await fetch( + "https://api.github.com/repos/soryu-co/makima/releases/latest" + ); + if (!res.ok) { + throw new Error(`GitHub API returned ${res.status}`); + } + const data: GitHubRelease = await res.json(); + setRelease(data); + } catch (err) { + setError( + err instanceof Error ? err.message : "Failed to fetch release info" + ); + } finally { + setLoading(false); + } + }; + fetchRelease(); + }, []); + + const platforms: PlatformDownload[] = [ + { + label: "Linux x86_64", + arch: "linux-x86_64", + pattern: "linux-x86_64.tar.gz", + asset: null, + recommended: userPlatform === "linux-x86_64", + }, + { + label: "macOS Intel (x86_64)", + arch: "macos-x86_64", + pattern: "macos-x86_64.tar.gz", + asset: null, + recommended: userPlatform === "macos-x86_64", + }, + { + label: "macOS Apple Silicon (ARM64)", + arch: "macos-arm64", + pattern: "macos-arm64.tar.gz", + asset: null, + recommended: userPlatform === "macos-arm64", + }, + ]; + + // Match assets to platforms + if (release) { + for (const p of platforms) { + p.asset = + release.assets.find((a) => a.name.includes(p.pattern)) || null; + } + } + + // Sort recommended first + const sortedPlatforms = [...platforms].sort( + (a, b) => (b.recommended ? 1 : 0) - (a.recommended ? 1 : 0) + ); + + return ( +
+ Download Daemon + + {loading && ( +

+ Fetching latest release... +

+ )} + + {error && Failed to load release: {error}} + + {release && ( + <> +
+
+ + {release.tag_name} + + + {formatDate(release.published_at)} + +
+ + All Releases → + +
+ +
+ {sortedPlatforms.map((p) => ( +
+
+ + {p.label} + + {p.recommended && ( + + Detected + + )} + {p.asset && ( + + {formatBytes(p.asset.size)} + + )} +
+ {p.asset ? ( + + Download + + ) : ( + + Not available + + )} +
+ ))} +
+ + )} +
+ ); +} + +// ============================================================================= +// Setup Instructions Section +// ============================================================================= + +function SetupSection() { + const [showConfig, setShowConfig] = useState(false); + + return ( +
+ Setup Instructions +
+
+ +
+

+ Download the binary for your platform above +

+
+
+ +
+ +
+

+ Extract the archive +

+ tar xzf makima-*.tar.gz +
+
+ +
+ +
+

+ Move to PATH +

+ sudo mv makima /usr/local/bin/ +
+
+ +
+ +
+

+ Set your API key ( + + generate one in Settings + + ) +

+ export MAKIMA_API_KEY="your-key" +
+
+ +
+ +
+

+ Set server URL +

+ + export MAKIMA_DAEMON_SERVER_URL="ws://your-server:8080" + +
+
+ +
+ +
+

+ Run the daemon +

+ makima daemon +
+
+
+ + {/* Config file alternative */} +
+ + {showConfig && ( +
+

+ Create makima-daemon.toml{" "} + in the working directory: +

+ + {`[daemon] +api_key = "your-key" +server_url = "ws://your-server:8080" +max_concurrent_tasks = 4`} + +
+ )} +
+
+ ); +} + +// ============================================================================= +// Cloudflare Edge Deployment Section +// ============================================================================= + +function CloudflareAgentSection() { + const [showSetup, setShowSetup] = useState(false); + + const benefits = [ + { + label: "Global edge presence", + desc: "Lower latency from 300+ Cloudflare locations worldwide", + }, + { + label: "Auto-scaling & hibernation", + desc: "Cost-efficient — only runs when needed", + }, + { + label: "WebSocket relay", + desc: "Coordinate remote daemon instances through persistent connections", + }, + { + label: "Durable Objects", + desc: "Built on Cloudflare's stateful edge compute primitives", + }, + ]; + + return ( +
+ Edge Deployment + +

+ Deploy a lightweight Makima relay agent on Cloudflare's edge network for + global, low-latency daemon coordination. Ideal for distributed teams or + production deployments requiring high availability. +

+ + {/* Benefits */} +
+ {benefits.map((b) => ( +
+ +
+ {b.label} + — {b.desc} +
+
+ ))} +
+ + {/* Quick Setup */} +
+ + {showSetup && ( +
+
+ +
+

+ Navigate to the Cloudflare agent directory +

+ cd makima/cloudflare-agent +
+
+
+ +
+

+ Run the setup script +

+ ./setup.sh +
+
+
+ +
+

+ Deploy to Cloudflare +

+ npx wrangler deploy +
+
+
+ )} +
+ + {/* Link to repo */} +
+ + Full documentation & source + + + View on GitHub → + +
+
+ ); +} + +// ============================================================================= +// Connected Daemons Section +// ============================================================================= + +function ConnectedDaemonsSection() { + const [daemons, setDaemons] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [restartingDaemonId, setRestartingDaemonId] = useState( + null + ); + const [restartConfirmDaemonId, setRestartConfirmDaemonId] = useState< + string | null + >(null); + + const loadDaemons = useCallback(async () => { + try { + setError(null); + const response = await listDaemons(); + setDaemons(response.daemons); + } catch (err) { + setError( + err instanceof Error ? err.message : "Failed to load daemons" + ); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + loadDaemons(); + }, [loadDaemons]); + + // Auto-refresh every 30 seconds + useEffect(() => { + const interval = setInterval(() => { + loadDaemons(); + }, 30000); + return () => clearInterval(interval); + }, [loadDaemons]); + + const handleRestartDaemon = async (id: string) => { + try { + setRestartingDaemonId(id); + setError(null); + await restartDaemon(id); + setRestartConfirmDaemonId(null); + // Daemon will restart, so refresh the list after a short delay + setTimeout(() => { + loadDaemons(); + }, 2000); + } catch (err) { + setError( + err instanceof Error ? err.message : "Failed to restart daemon" + ); + } finally { + setRestartingDaemonId(null); + } + }; + + return ( +
+
+
+

+ Connected Daemons +

+ {daemons.length > 0 && ( + + ({daemons.filter((d) => d.status === "connected").length}{" "} + connected / {daemons.length} total) + + )} +
+ +
+ + {error && {error}} + + {loading && daemons.length === 0 ? ( +

Loading...

+ ) : daemons.length === 0 ? ( +
+

+ No daemons connected +

+

+ Follow the setup instructions above to connect a daemon +

+
+ ) : ( +
+ {daemons.map((daemon) => ( +
+
+ + {daemon.hostname || "Unknown Host"} + +
+ + {daemon.status} + +
+
+
+
+ Tasks + + {daemon.currentTaskCount} / {daemon.maxConcurrentTasks} + +
+
+ Connected + + {new Date(daemon.connectedAt).toLocaleString()} + +
+ {daemon.machineId && ( +
+ Machine + + {daemon.machineId.substring(0, 16)}... + +
+ )} +
+ {/* Restart Section */} + {daemon.status === "connected" && ( +
+ {restartConfirmDaemonId === daemon.id ? ( +
+ + Restart daemon? Running tasks will be interrupted. + +
+ + +
+
+ ) : ( + + )} +
+ )} +
+ ))} +
+ )} +
+ ); +} + +// ============================================================================= +// Main Page +// ============================================================================= + +export default function DaemonPage() { + const { + isAuthenticated, + isAuthConfigured, + isLoading: authLoading, + } = useAuth(); + const navigate = useNavigate(); + + useEffect(() => { + if (!authLoading && isAuthConfigured && !isAuthenticated) { + navigate("/login"); + } + }, [authLoading, isAuthConfigured, isAuthenticated, navigate]); + + if (authLoading) { + return ( +
+ +
+

Loading...

+
+
+ ); + } + + return ( +
+ +
+ {/* Page header */} +
+

+ Daemon Management +

+

+ Download, configure, and monitor Makima daemons +

+
+ +
+ {/* Left Column: Downloads & Setup */} +
+ + +
+ + {/* Right Column: Edge Deployment & Connected Daemons */} +
+ + +
+
+
+
+ ); +} diff --git a/makima/frontend/tsconfig.tsbuildinfo b/makima/frontend/tsconfig.tsbuildinfo index 68f2eac..410931d 100644 --- a/makima/frontend/tsconfig.tsbuildinfo +++ b/makima/frontend/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/main.tsx","./src/vite-env.d.ts","./src/components/gridoverlay.tsx","./src/components/japanesehovertext.tsx","./src/components/logo.tsx","./src/components/masthead.tsx","./src/components/navstrip.tsx","./src/components/phaseconfirmationnotification.tsx","./src/components/protectedroute.tsx","./src/components/rewritelink.tsx","./src/components/simplemarkdown.tsx","./src/components/supervisorquestionnotification.tsx","./src/components/charts/chartrenderer.tsx","./src/components/contracts/commandmodepanel.tsx","./src/components/contracts/contractcliinput.tsx","./src/components/contracts/contractcontextmenu.tsx","./src/components/contracts/contractdetail.tsx","./src/components/contracts/contractlist.tsx","./src/components/contracts/phasebadge.tsx","./src/components/contracts/phaseconfirmationmodal.tsx","./src/components/contracts/phasedeliverablespanel.tsx","./src/components/contracts/phasehint.tsx","./src/components/contracts/phaseprogressbar.tsx","./src/components/contracts/quickactionbuttons.tsx","./src/components/contracts/repositorypanel.tsx","./src/components/contracts/taskderivationpreview.tsx","./src/components/directives/directivedag.tsx","./src/components/directives/directivedetail.tsx","./src/components/directives/directivelist.tsx","./src/components/directives/directivelogstream.tsx","./src/components/directives/stepnode.tsx","./src/components/files/bodyrenderer.tsx","./src/components/files/cliinput.tsx","./src/components/files/conflictnotification.tsx","./src/components/files/elementcontextmenu.tsx","./src/components/files/filedetail.tsx","./src/components/files/filelist.tsx","./src/components/files/reposyncindicator.tsx","./src/components/files/updatenotification.tsx","./src/components/files/versionhistorydropdown.tsx","./src/components/history/checkpointcard.tsx","./src/components/history/checkpointlist.tsx","./src/components/history/conversationmessage.tsx","./src/components/history/conversationview.tsx","./src/components/history/historyfilters.tsx","./src/components/history/resumecontrols.tsx","./src/components/history/timelineeventcard.tsx","./src/components/history/timelinelist.tsx","./src/components/history/index.ts","./src/components/listen/contractpickermodal.tsx","./src/components/listen/controlpanel.tsx","./src/components/listen/discusscontractmodal.tsx","./src/components/listen/speakerpanel.tsx","./src/components/listen/transcriptanalysispanel.tsx","./src/components/listen/transcriptpanel.tsx","./src/components/mesh/branchtaskmodal.tsx","./src/components/mesh/contractcompletequestion.tsx","./src/components/mesh/directoryinput.tsx","./src/components/mesh/gitactionspanel.tsx","./src/components/mesh/inlinesubtaskeditor.tsx","./src/components/mesh/mergeconflictresolver.tsx","./src/components/mesh/overlaydiffviewer.tsx","./src/components/mesh/prpreview.tsx","./src/components/mesh/patcheslistpanel.tsx","./src/components/mesh/subtasktree.tsx","./src/components/mesh/taskdetail.tsx","./src/components/mesh/tasklist.tsx","./src/components/mesh/taskoutput.tsx","./src/components/mesh/tasktree.tsx","./src/components/mesh/unifiedmeshchatinput.tsx","./src/components/mesh/worktreefilespanel.tsx","./src/components/orders/orderdetail.tsx","./src/components/orders/orderlist.tsx","./src/contexts/authcontext.tsx","./src/contexts/supervisorquestionscontext.tsx","./src/hooks/usecontracts.ts","./src/hooks/usedirectives.ts","./src/hooks/usefilesubscription.ts","./src/hooks/usefiles.ts","./src/hooks/usemeshchathistory.ts","./src/hooks/usemicrophone.ts","./src/hooks/usemultitasksubscription.ts","./src/hooks/useorders.ts","./src/hooks/usespeakwebsocket.ts","./src/hooks/usetasksubscription.ts","./src/hooks/usetasks.ts","./src/hooks/usetextscramble.ts","./src/hooks/useversionhistory.ts","./src/hooks/usewebsocket.ts","./src/lib/api.ts","./src/lib/listenapi.ts","./src/lib/markdown.ts","./src/lib/supabase.ts","./src/routes/_index.tsx","./src/routes/contract-file.tsx","./src/routes/contracts.tsx","./src/routes/directives.tsx","./src/routes/files.tsx","./src/routes/history.tsx","./src/routes/listen.tsx","./src/routes/login.tsx","./src/routes/mesh.tsx","./src/routes/orders.tsx","./src/routes/settings.tsx","./src/routes/speak.tsx","./src/types/messages.ts"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/main.tsx","./src/vite-env.d.ts","./src/components/gridoverlay.tsx","./src/components/japanesehovertext.tsx","./src/components/logo.tsx","./src/components/masthead.tsx","./src/components/navstrip.tsx","./src/components/phaseconfirmationnotification.tsx","./src/components/protectedroute.tsx","./src/components/rewritelink.tsx","./src/components/simplemarkdown.tsx","./src/components/supervisorquestionnotification.tsx","./src/components/charts/chartrenderer.tsx","./src/components/contracts/commandmodepanel.tsx","./src/components/contracts/contractcliinput.tsx","./src/components/contracts/contractcontextmenu.tsx","./src/components/contracts/contractdetail.tsx","./src/components/contracts/contractlist.tsx","./src/components/contracts/phasebadge.tsx","./src/components/contracts/phaseconfirmationmodal.tsx","./src/components/contracts/phasedeliverablespanel.tsx","./src/components/contracts/phasehint.tsx","./src/components/contracts/phaseprogressbar.tsx","./src/components/contracts/quickactionbuttons.tsx","./src/components/contracts/repositorypanel.tsx","./src/components/contracts/taskderivationpreview.tsx","./src/components/directives/directivedag.tsx","./src/components/directives/directivedetail.tsx","./src/components/directives/directivelist.tsx","./src/components/directives/directivelogstream.tsx","./src/components/directives/orchestratorstepnode.tsx","./src/components/directives/stepnode.tsx","./src/components/files/bodyrenderer.tsx","./src/components/files/cliinput.tsx","./src/components/files/conflictnotification.tsx","./src/components/files/elementcontextmenu.tsx","./src/components/files/filedetail.tsx","./src/components/files/filelist.tsx","./src/components/files/reposyncindicator.tsx","./src/components/files/updatenotification.tsx","./src/components/files/versionhistorydropdown.tsx","./src/components/history/checkpointcard.tsx","./src/components/history/checkpointlist.tsx","./src/components/history/conversationmessage.tsx","./src/components/history/conversationview.tsx","./src/components/history/historyfilters.tsx","./src/components/history/resumecontrols.tsx","./src/components/history/timelineeventcard.tsx","./src/components/history/timelinelist.tsx","./src/components/history/index.ts","./src/components/listen/contractpickermodal.tsx","./src/components/listen/controlpanel.tsx","./src/components/listen/discusscontractmodal.tsx","./src/components/listen/speakerpanel.tsx","./src/components/listen/transcriptanalysispanel.tsx","./src/components/listen/transcriptpanel.tsx","./src/components/mesh/branchtaskmodal.tsx","./src/components/mesh/contractcompletequestion.tsx","./src/components/mesh/directoryinput.tsx","./src/components/mesh/gitactionspanel.tsx","./src/components/mesh/inlinesubtaskeditor.tsx","./src/components/mesh/mergeconflictresolver.tsx","./src/components/mesh/overlaydiffviewer.tsx","./src/components/mesh/prpreview.tsx","./src/components/mesh/patcheslistpanel.tsx","./src/components/mesh/subtasktree.tsx","./src/components/mesh/taskdetail.tsx","./src/components/mesh/tasklist.tsx","./src/components/mesh/taskoutput.tsx","./src/components/mesh/tasktree.tsx","./src/components/mesh/unifiedmeshchatinput.tsx","./src/components/mesh/worktreefilespanel.tsx","./src/components/orders/orderdetail.tsx","./src/components/orders/orderlist.tsx","./src/contexts/authcontext.tsx","./src/contexts/supervisorquestionscontext.tsx","./src/hooks/usecontracts.ts","./src/hooks/usedirectives.ts","./src/hooks/usefilesubscription.ts","./src/hooks/usefiles.ts","./src/hooks/usemeshchathistory.ts","./src/hooks/usemicrophone.ts","./src/hooks/usemultitasksubscription.ts","./src/hooks/useorders.ts","./src/hooks/usespeakwebsocket.ts","./src/hooks/usetasksubscription.ts","./src/hooks/usetasks.ts","./src/hooks/usetextscramble.ts","./src/hooks/useversionhistory.ts","./src/hooks/usewebsocket.ts","./src/lib/api.ts","./src/lib/listenapi.ts","./src/lib/markdown.ts","./src/lib/supabase.ts","./src/routes/_index.tsx","./src/routes/contract-file.tsx","./src/routes/contracts.tsx","./src/routes/daemon.tsx","./src/routes/directives.tsx","./src/routes/files.tsx","./src/routes/history.tsx","./src/routes/listen.tsx","./src/routes/login.tsx","./src/routes/mesh.tsx","./src/routes/orders.tsx","./src/routes/settings.tsx","./src/routes/speak.tsx","./src/types/messages.ts"],"errors":true,"version":"5.9.3"} \ No newline at end of file -- cgit v1.2.3