mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 09:20:03 +01:00
refactor: retire bash-daemon TS consumers (Session 4a)
Session 4 of killing-the-bash-daemon plan, commit A — removes every
TS reference that pointed at the bash daemon, the bash bridge, or the
standalone home/server.ts. Bash file deletion (commit B) follows.
DELETED:
home/server.ts (790 LoC)
The standalone Brain HTTP server at 127.0.0.1:3001. Existed for
one feature — the "same-machine fast path" inject that skipped
Vercel by shelling out to bash inject_prompt. Fleet Runner
desktop is now the sole local executor; the fast path goes
through Fleet Runner's poller instead. The Brain's library
pieces (home/watcher.ts, home/decide.ts, home/render.ts, home/
state.ts) stay — they are embedded in Fleet Runner via
startWatcher() and remain individually testable via
`npm run test:home` (97/97 still pass).
scripts/home-start.sh (74 LoC)
Launcher for the deleted Brain server. Nothing to launch.
src/app/api/system/daemon/route.ts (103 LoC)
POST/GET that controlled the fleetcrown-daemon.service systemd
unit. The unit was disabled in Session 1; the route's
raison-d'être is gone.
src/components/control/DaemonControls.tsx (102 LoC)
UI for the deleted /api/system/daemon route. Showed start/
restart/stop buttons that called into the bash daemon. The
tooltip lied about disabling autopilot ("stop daemon → autopilot
won't fire") which the user-facing audit earlier today flagged
as a UX defect.
REWRITTEN:
src/app/api/agent/daemon/route.ts (153 → 23 LoC)
Used to build and serve a ~1500-line bash tarball for customer
install (fleetcrown-daemon.sh + agent-hook-bridge.sh +
agent-hook-lib.sh + Python beacon stack). Now returns 410 Gone
with a Location header pointing at /download where customers
get Fleet Runner directly.
src/app/api/system/doctor/route.ts
Removed the beacon-window and bash-daemon systemd unit probes.
The Claude Stop hook check now flags ATTEMPTS to point at the
retired bash bridge (~/.local/share/fleetcrown-beacon/
agent-hook-bridge.sh) as failures — a hook that exec's a
deleted path is broken, not a feature.
src/components/control/DaemonStatusBanner.tsx
Removed the embedded DaemonControls. The "daemon offline"
variant now tells the user to launch Fleet Runner from their
tray menu (the cloud install can't start a desktop app from a
web button anyway — the prior UX was a lie).
src/hooks/use-control-data.ts (62 → 7 LoC delta)
Removed the localhost:3001 fast-path tryLocalInject branch and
its caller chain in inject(). Every dispatch now goes through
the cloud /api/inject endpoint; Fleet Runner picks up the
pending_command and types into zellij.
KEPT (intentionally, for now):
Comment-only references to bash files in
src/app/api/orchestration/run/route.ts
src/db/schema/pending-commands.ts
src/config/prompt-library.ts
home/{watcher,worker,projects}.ts
desktop/src/main/{dispatch,poller}.ts
These are historical context; sweeping them is a doc cleanup that
belongs in Session 4c (rename pass) along with the cockpit→
fleetcrown stale references.
Verification: tsc clean. test:home 97/97. test:autopilot-defaults
11/11. test:dispatch-gates 11/11. lint clean (11 pre-existing
warnings, no errors).
Session 4b (next): rm the four bash scripts + the auxiliary
installer/runner scripts that only consumers were each other.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
2391c6f735
commit
a3f470ded7
8 files changed
+63
-1298
No files matched your search
-790
@@ -1,790 +0,0 @@
|
||||
#!/usr/bin/env -S npx tsx
|
||||
/**
|
||||
* Brain — local Node HTTP server.
|
||||
*
|
||||
* Boots, tails ~/.<APP_SLUG>/events.jsonl, projects events into in-memory
|
||||
* state, serves a minimal /control view and a /api/state JSON endpoint.
|
||||
*
|
||||
* No external deps beyond what the existing repo already brings in (node:*
|
||||
* for the server, zod via src/lib/events for parsing). M2 deliberately keeps
|
||||
* the surface tiny: this is the smallest possible thing that proves the
|
||||
* event-log → state projection → UI loop works.
|
||||
*
|
||||
* Run: npx tsx home/server.ts
|
||||
* Test: echo '<event-json>' >> ~/.<APP_SLUG>/events.jsonl
|
||||
* curl http://localhost:3001/api/state
|
||||
*
|
||||
* Brain growth: M3 wires a Bridge that pulls events from the OS / hooks.
|
||||
* M5 adds the decide() function. M6 wires dispatch back to
|
||||
* workers. This file stays small.
|
||||
*/
|
||||
|
||||
import http from "node:http";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { APP_NAME, APP_SLUG } from "@/config/brand";
|
||||
import type { Autonomy, Adapter } from "@/lib/events";
|
||||
import { ADAPTERS, parseEvent } from "@/lib/events";
|
||||
import { tailLog } from "./log";
|
||||
import { applyEvent, type GlobalState, type ProjectState } from "./state";
|
||||
import { decide, type Decision } from "./decide";
|
||||
import { appendEvent } from "./emit";
|
||||
import { renderPromptForDispatch } from "./render";
|
||||
import { resolveProjectPath, resolveProjectAdapter, loadProjects } from "./projects";
|
||||
import { ORCHESTRATION_TASK_INTENT_IDS, type OrchestrationTaskIntentId } from "@/lib/orchestration";
|
||||
|
||||
// Boot-mode gate. Naked `npx tsx home/server.ts` (no flags) should NOT spin
|
||||
// up the HTTP server + fs.watch — otherwise a one-shot test invocation
|
||||
// (e.g. inside a `tail -3` pipe) leaves an orphan server eating port 3001
|
||||
// + watching the event log forever. Require an explicit --start.
|
||||
if (!process.argv.includes("--start")) {
|
||||
console.log(`${APP_NAME} brain — local HTTP server (Brain layer of the home/ stack).
|
||||
Usage: npx tsx home/server.ts --start
|
||||
Env: APP_HOME_PORT port to bind (default 3001)`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const LOG_PATH = path.join(os.homedir(), `.${APP_SLUG}`, "events.jsonl");
|
||||
const PORT = parseInt(process.env.APP_HOME_PORT ?? process.env.FLEETCROWN_HOME_PORT ?? process.env.COCKPIT_HOME_PORT ?? "3001", 10);
|
||||
|
||||
// Repo root derived from this file's location — used by the same-machine
|
||||
// inject fast path below to spawn bash with the right script paths.
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const REPO_ROOT = path.resolve(path.dirname(__filename), "..");
|
||||
const AGENT_HOOK_LIB = path.join(REPO_ROOT, "scripts", "agent-hook-lib.sh");
|
||||
const BRAND_LIB = path.join(REPO_ROOT, "scripts", "_brand.sh");
|
||||
|
||||
let state: GlobalState = new Map();
|
||||
let lastError: { ts: string; message: string; raw?: string } | null = null;
|
||||
|
||||
/**
|
||||
* Union live event-projected state with registered-but-eventless projects
|
||||
* from agent-projects.conf so the UI can show every project the user has
|
||||
* registered, even ones that have never emitted an event yet (fresh boot,
|
||||
* new project just added, etc.). Live state always wins on name collision.
|
||||
*
|
||||
* Lowercase-keyed dedup matches the registry's case-insensitive lookup.
|
||||
*/
|
||||
function assembleProjectList(): ProjectState[] {
|
||||
const live = Array.from(state.values());
|
||||
const liveLower = new Set(live.map((p) => p.project.toLowerCase()));
|
||||
const idleRegistered: ProjectState[] = [];
|
||||
for (const cfg of loadProjects().values()) {
|
||||
if (liveLower.has(cfg.name.toLowerCase())) continue;
|
||||
idleRegistered.push({
|
||||
project: cfg.name,
|
||||
lastEventTs: "", // empty signals "never seen an event" to the UI
|
||||
recentOutcomes: [],
|
||||
});
|
||||
}
|
||||
return [...live, ...idleRegistered];
|
||||
}
|
||||
|
||||
const handle = tailLog(
|
||||
LOG_PATH,
|
||||
(event) => { state = applyEvent(state, event); },
|
||||
(err, raw) => {
|
||||
lastError = { ts: new Date().toISOString(), message: err.message, raw };
|
||||
// Don't spam — only echo parse errors to stderr if they look unexpected.
|
||||
if (!err.message.startsWith("parse: schema:")) console.error("[home]", err.message);
|
||||
},
|
||||
);
|
||||
|
||||
// ── HTML page (vanilla JS, polls /api/state every 2s) ────────────────────────
|
||||
//
|
||||
// Editing trap: the entire HTML+JS body lives inside the backtick template
|
||||
// literal below. Two characters need careful handling when adding content
|
||||
// here that don't matter in a normal .ts file:
|
||||
// • Backticks (`) close the literal — escape as \` or avoid in comments
|
||||
// and strings. A stray ` mid-comment produces opaque TS1005 errors
|
||||
// pointing at the surrounding line, not the backtick itself.
|
||||
// • ${expr} interpolates at server-render time. Use \${ in any JS that
|
||||
// should evaluate in the browser (we already do this for refresh's
|
||||
// template strings — see the renderProposal returns).
|
||||
//
|
||||
// If a tsc syntax error points at a line that "looks fine," grep for an
|
||||
// unescaped backtick or ${ in the surrounding template body.
|
||||
|
||||
const INDEX_HTML = `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>${APP_NAME} · home</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: ui-monospace, "SF Mono", Menlo, monospace; background: #0a0a0a; color: #e5e5e5; padding: 2rem; margin: 0; line-height: 1.5; }
|
||||
header { display: flex; align-items: baseline; gap: 1rem; margin-bottom: 1.5rem; }
|
||||
h1 { font-size: 14px; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase; color: #a3a3a3; margin: 0; }
|
||||
.meta { font-size: 12px; color: #525252; }
|
||||
.empty { color: #525252; font-style: italic; padding: 2rem 0; }
|
||||
.project { border-left: 2px solid #404040; padding: 0.5rem 1rem; margin-bottom: 0.75rem; transition: border-color .15s; }
|
||||
.project.running { border-left-color: #4ade80; }
|
||||
.project h2 { font-size: 14px; font-weight: 500; margin: 0 0 0.5rem; color: #fafafa; display: flex; align-items: center; gap: 0.5rem; }
|
||||
.running-pill { font-size: 11px; padding: 0.1rem 0.4rem; border-radius: 4px; background: #16a34a33; color: #4ade80; font-weight: 500; }
|
||||
.status-pill { font-size: 11px; padding: 0.1rem 0.4rem; border-radius: 4px; font-weight: 500; }
|
||||
.status-pill.ready { background: #16a34a33; color: #4ade80; }
|
||||
.status-pill.working { background: #eab30833; color: #fbbf24; }
|
||||
.queue-pill { font-size: 11px; padding: 0.1rem 0.4rem; border-radius: 4px; background: #3b82f633; color: #93c5fd; font-weight: 500; }
|
||||
.outcomes { display: inline-flex; gap: 0.25rem; }
|
||||
.o { font-size: 13px; padding: 0 0.4rem; border-radius: 4px; font-weight: 600; line-height: 1.4; }
|
||||
.o.success { background: #16a34a33; color: #4ade80; }
|
||||
.o.partial { background: #eab30833; color: #fbbf24; }
|
||||
.o.error, .o.hang, .o.timeout { background: #dc262633; color: #f87171; }
|
||||
.o.user_abort { background: #eab30833; color: #fbbf24; }
|
||||
.handoff { color: #a3a3a3; font-size: 12px; margin-top: 0.5rem; word-break: break-word; }
|
||||
.reason { color: #d4d4d8; font-size: 12px; margin: 0.4rem 0 0.5rem; word-break: break-word; line-height: 1.5; }
|
||||
.conf { color: #71717a; font-size: 11px; }
|
||||
.proj-err { color: #f87171; font-size: 12px; margin-top: 0.5rem; padding: 0.3rem 0.6rem; border-left: 2px solid #dc2626; background: #dc262611; word-break: break-word; line-height: 1.5; }
|
||||
.ts { color: #525252; font-size: 11px; margin-left: auto; }
|
||||
.actions { display: flex; gap: 0.4rem; margin-top: 0.6rem; }
|
||||
.actions button { font: inherit; font-size: 11px; padding: 0.25rem 0.6rem; border: 1px solid #404040; background: #1a1a1a; color: #d4d4d8; border-radius: 4px; cursor: pointer; transition: background .12s, border-color .12s; }
|
||||
.actions button:hover:not(:disabled) { background: #262626; border-color: #525252; }
|
||||
.actions button:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.actions button.primary { border-color: #16a34a55; color: #4ade80; }
|
||||
.actions button.primary:hover:not(:disabled) { background: #16a34a22; }
|
||||
.actions button.danger { border-color: #dc262655; color: #f87171; }
|
||||
.actions button.danger:hover:not(:disabled) { background: #dc262622; }
|
||||
.proposal { font-size: 11px; color: #a3a3a3; margin-top: 0.5rem; padding: 0.4rem 0.6rem; border-left: 2px solid #525252; background: #0f0f0f; line-height: 1.5; word-break: break-word; }
|
||||
.proposal .label { color: #71717a; text-transform: uppercase; letter-spacing: 0.05em; font-size: 10px; margin-right: 0.4rem; }
|
||||
pre { color: #525252; font-size: 11px; background: #050505; padding: 1rem; border-radius: 4px; margin-top: 2rem; overflow-x: auto; }
|
||||
.err { color: #f87171; font-size: 12px; margin-top: 1rem; padding: 0.5rem 1rem; border-left: 2px solid #dc2626; background: #dc262611; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>${APP_NAME} · home</h1>
|
||||
<span class="meta">tailing ~/.${APP_SLUG}/events.jsonl</span>
|
||||
<span class="meta" id="meta"></span>
|
||||
</header>
|
||||
<div id="projects"></div>
|
||||
<div id="err"></div>
|
||||
<pre id="raw"></pre>
|
||||
<script>
|
||||
const GLYPH = { success: '✓', partial: '~', error: '✗', hang: '✗', timeout: '✗', user_abort: '✕' };
|
||||
function compact(iso) {
|
||||
if (!iso) return 'idle';
|
||||
try {
|
||||
const d = new Date(iso);
|
||||
return isNaN(d.getTime()) ? 'idle' : d.toLocaleTimeString();
|
||||
} catch { return 'idle'; }
|
||||
}
|
||||
// Per-project transient UI: last /api/dispatch response shown until the next
|
||||
// refresh succeeds or a new run starts. Keyed by project name.
|
||||
const proposals = new Map();
|
||||
function escapeHtml(s) {
|
||||
return String(s).replace(/[&<>"']/g, (c) => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
}
|
||||
// If a dispatched chip has been showing this long without the brain seeing
|
||||
// a corresponding currentRun (worker.started never arrived), the worker
|
||||
// almost certainly isn't running. Stop showing the optimistic "dispatched"
|
||||
// and surface a diagnostic instead.
|
||||
const DISPATCH_ACK_TIMEOUT_MS = 10000;
|
||||
function renderProposal(p) {
|
||||
const prop = proposals.get(p.project);
|
||||
if (!prop) return '';
|
||||
if (prop.dispatched) {
|
||||
const age = Date.now() - (prop.postedAt ?? Date.now());
|
||||
if (age > DISPATCH_ACK_TIMEOUT_MS) {
|
||||
return '<div class="proposal" style="border-left-color:#dc2626;color:#f87171"><span class="label">unacked</span>' +
|
||||
'dispatched ' + Math.round(age / 1000) + 's ago but worker.started never arrived · runId ' +
|
||||
escapeHtml(prop.runId.slice(0, 8)) + ' · is the worker running?</div>';
|
||||
}
|
||||
return '<div class="proposal"><span class="label">dispatched</span>' +
|
||||
escapeHtml(prop.decision.action.intent) + ' · runId ' + escapeHtml(prop.runId.slice(0, 8)) + '</div>';
|
||||
}
|
||||
const a = prop.decision.action;
|
||||
const reason = a.reason ?? '';
|
||||
// Cancel and error chips carry their full message in the reason field —
|
||||
// don't tack on the meaningless 0% confidence pill or the "proposed"
|
||||
// prefix (Cancel isn't a proposal, Error wasn't a brain decision). Only
|
||||
// real decide()-produced proposals (wait/dispatch/recovery) get the
|
||||
// confidence footer.
|
||||
if (a.kind === 'cancelled') {
|
||||
return '<div class="proposal"><span class="label">cancelled</span>' +
|
||||
(reason ? escapeHtml(reason) : 'Ctrl+C sent') + '</div>';
|
||||
}
|
||||
if (a.kind === 'error') {
|
||||
return '<div class="proposal" style="border-left-color:#dc2626;color:#f87171"><span class="label">error</span>' +
|
||||
escapeHtml(reason || 'unknown') + '</div>';
|
||||
}
|
||||
return '<div class="proposal"><span class="label">proposed</span>' +
|
||||
escapeHtml(a.kind) + (a.intent ? ' · ' + escapeHtml(a.intent) : '') +
|
||||
(reason ? ' — ' + escapeHtml(reason) : '') +
|
||||
' <span class="conf">· ' + Math.round(prop.decision.confidence * 100) + '% confidence</span></div>';
|
||||
}
|
||||
async function dispatch(project, autonomy, btn) {
|
||||
const buttons = btn.parentElement.querySelectorAll('button');
|
||||
buttons.forEach(b => b.disabled = true);
|
||||
try {
|
||||
const r = await fetch('/api/dispatch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ project, autonomy }),
|
||||
});
|
||||
const j = await r.json();
|
||||
if (!r.ok) {
|
||||
proposals.set(project, { dispatched: false, decision: { action: { kind: 'error', intent: '', reason: j.error || ('HTTP ' + r.status) }, confidence: 0 } });
|
||||
} else {
|
||||
proposals.set(project, { ...j, postedAt: Date.now() });
|
||||
}
|
||||
} catch (e) {
|
||||
proposals.set(project, { dispatched: false, decision: { action: { kind: 'error', intent: '', reason: String(e) }, confidence: 0 } });
|
||||
} finally {
|
||||
buttons.forEach(b => b.disabled = false);
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
async function cancelRun(project, btn) {
|
||||
const buttons = btn.parentElement.querySelectorAll('button');
|
||||
buttons.forEach(b => b.disabled = true);
|
||||
try {
|
||||
const r = await fetch('/api/cancel', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ project, reason: 'cancelled from /control' }),
|
||||
});
|
||||
const j = await r.json();
|
||||
if (!r.ok) {
|
||||
proposals.set(project, { dispatched: false, decision: { action: { kind: 'error', intent: '', reason: j.error || ('HTTP ' + r.status) }, confidence: 0 } });
|
||||
} else {
|
||||
proposals.set(project, { dispatched: false, decision: { action: { kind: 'cancelled', intent: '', reason: 'Ctrl+C sent · runId ' + (j.runId || '').slice(0, 8) }, confidence: 0 } });
|
||||
}
|
||||
} catch (e) {
|
||||
proposals.set(project, { dispatched: false, decision: { action: { kind: 'error', intent: '', reason: String(e) }, confidence: 0 } });
|
||||
} finally {
|
||||
buttons.forEach(b => b.disabled = false);
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
document.addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('button[data-action]');
|
||||
if (!btn) return;
|
||||
if (btn.dataset.action === 'dispatch') {
|
||||
dispatch(btn.dataset.project, btn.dataset.autonomy, btn);
|
||||
} else if (btn.dataset.action === 'cancel') {
|
||||
cancelRun(btn.dataset.project, btn);
|
||||
}
|
||||
});
|
||||
async function refresh() {
|
||||
try {
|
||||
const r = await fetch('/api/state');
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
const j = await r.json();
|
||||
document.getElementById('meta').textContent = j.projects.length + ' project' + (j.projects.length === 1 ? '' : 's');
|
||||
const root = document.getElementById('projects');
|
||||
if (j.projects.length === 0) {
|
||||
root.innerHTML = '<div class="empty">no events yet — append one to ~/.${APP_SLUG}/events.jsonl</div>';
|
||||
} else {
|
||||
// Clear stale proposals once the project actually starts a run.
|
||||
for (const p of j.projects) {
|
||||
if (p.currentRun && proposals.has(p.project)) proposals.delete(p.project);
|
||||
}
|
||||
root.innerHTML = j.projects.map(p => {
|
||||
const cr = p.currentRun;
|
||||
const confPct = cr && typeof cr.confidence === 'number' ? Math.round(cr.confidence * 100) + '%' : null;
|
||||
const reasonLine = cr && cr.reason
|
||||
? '<div class="reason">' + escapeHtml(cr.reason) + (confPct ? ' <span class="conf">· ' + confPct + ' confidence</span>' : '') + '</div>'
|
||||
: '';
|
||||
const errorLine = p.lastError
|
||||
? '<div class="proj-err">last error @ ' + compact(p.lastError.ts) + ': ' + escapeHtml(p.lastError.message) + '</div>'
|
||||
: '';
|
||||
const projAttr = escapeHtml(p.project);
|
||||
const actions = cr
|
||||
? '<div class="actions">' +
|
||||
'<button class="danger" data-action="cancel" data-project="' + projAttr + '">Cancel</button>' +
|
||||
'</div>'
|
||||
: '<div class="actions">' +
|
||||
'<button data-action="dispatch" data-project="' + projAttr + '" data-autonomy="confirm">Propose</button>' +
|
||||
'<button class="primary" data-action="dispatch" data-project="' + projAttr + '" data-autonomy="manual">Dispatch</button>' +
|
||||
'</div>';
|
||||
return \`
|
||||
<div class="project\${cr ? ' running' : ''}">
|
||||
<h2>
|
||||
\${escapeHtml(p.project)}
|
||||
\${cr ? '<span class="running-pill">' + escapeHtml(cr.intent) + (cr.adapter && cr.adapter !== 'claude' ? ' · ' + escapeHtml(cr.adapter) : '') + '</span>' : (() => {
|
||||
const st = (p.lastHandoff && p.lastHandoff.status || '').toLowerCase();
|
||||
if (st === 'ready') return '<span class="status-pill ready">ready</span>';
|
||||
if (st === 'working') return '<span class="status-pill working">working</span>';
|
||||
return '';
|
||||
})()}
|
||||
\${p.queueLen > 0 ? '<span class="queue-pill">' + p.queueLen + ' queued</span>' : ''}
|
||||
<span class="ts">\${compact(p.lastEventTs)}</span>
|
||||
</h2>
|
||||
\${reasonLine}
|
||||
\${(p.recentOutcomes ?? []).length > 0 ? '<div class="outcomes">' + p.recentOutcomes.map(o => '<span class="o ' + o + '">' + (GLYPH[o] ?? '?') + '</span>').join('') + '</div>' : ''}
|
||||
\${errorLine}
|
||||
\${p.lastHandoff && p.lastHandoff.done ? '<div class="handoff">' + escapeHtml(p.lastHandoff.done) + '</div>' : ''}
|
||||
\${renderProposal(p)}
|
||||
\${actions}
|
||||
</div>
|
||||
\`;
|
||||
}).join('');
|
||||
}
|
||||
document.getElementById('err').innerHTML = j.lastError
|
||||
? '<div class="err">last parse error @ ' + compact(j.lastError.ts) + ': ' + escapeHtml(j.lastError.message) + '</div>'
|
||||
: '';
|
||||
document.getElementById('raw').textContent = JSON.stringify(j, null, 2);
|
||||
} catch (e) {
|
||||
// Server probably restarted — silent
|
||||
}
|
||||
}
|
||||
refresh();
|
||||
setInterval(refresh, 2000);
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
// ── HTTP handlers ────────────────────────────────────────────────────────────
|
||||
|
||||
// ── Same-machine fast path ───────────────────────────────────────────────────
|
||||
//
|
||||
// /control in the browser tries POST http://localhost:3001/api/inject before
|
||||
// falling back to the cloud /api/inject. Cutting Vercel + Postgres + long-poll
|
||||
// out of the local case turns 7 hops into 3 (browser → home → zellij → agent)
|
||||
// and removes the failure modes that come with each missing hop.
|
||||
//
|
||||
// Security model:
|
||||
// - The home server binds to 127.0.0.1 only (see listen() at the bottom),
|
||||
// so machines on the LAN cannot reach it.
|
||||
// - CORS allow-list is tight: only the deployed cloud origin and the local
|
||||
// dev server can read responses. The browser blocks cross-origin reads
|
||||
// from anywhere else, so a malicious page in another tab cannot tell
|
||||
// whether the inject succeeded.
|
||||
// - POST is harmless without a valid project name — bad inputs return 4xx
|
||||
// with no side effect.
|
||||
|
||||
const ALLOWED_ORIGINS = new Set<string>([
|
||||
"https://fleetcrown.vercel.app",
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
]);
|
||||
|
||||
function applyCors(req: http.IncomingMessage, res: http.ServerResponse): void {
|
||||
const origin = (req.headers.origin ?? "") as string;
|
||||
if (ALLOWED_ORIGINS.has(origin)) {
|
||||
res.setHeader("Access-Control-Allow-Origin", origin);
|
||||
res.setHeader("Vary", "Origin");
|
||||
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
|
||||
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
// Chrome's Private Network Access blocks HTTPS pages (cloud /control)
|
||||
// from reaching a private IP / loopback (this server on 127.0.0.1)
|
||||
// unless the target opts in by acknowledging the cross-network
|
||||
// request. Without this header the browser silently aborts the
|
||||
// request before the daemon ever sees it.
|
||||
// https://developer.chrome.com/blog/private-network-access-preflight
|
||||
res.setHeader("Access-Control-Allow-Private-Network", "true");
|
||||
}
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = req.url ?? "/";
|
||||
|
||||
// Preflight for the fast-path inject from cross-origin /control.
|
||||
if (req.method === "OPTIONS") {
|
||||
applyCors(req, res);
|
||||
res.statusCode = 204;
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
applyCors(req, res);
|
||||
|
||||
if (url === "/" || url === "/control") {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end(INDEX_HTML);
|
||||
return;
|
||||
}
|
||||
|
||||
if (url === "/api/state") {
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
// Annotate each project with the local /tmp/agent-queue-<tab> length so
|
||||
// the /control UI can surface a "Nqueued" badge. The file mirror is
|
||||
// hydrated by the FleetCrown API/daemon bridge from DB authority.
|
||||
// Reading the file lets home/ show queue depth without taking
|
||||
// a DB dep — keeping home/ local-first.
|
||||
const projects = assembleProjectList().map((p) => {
|
||||
let queueLen = 0;
|
||||
try {
|
||||
const raw = fs.readFileSync(path.join("/tmp", `agent-queue-${p.project.toLowerCase()}`), "utf8");
|
||||
const arr = JSON.parse(raw);
|
||||
if (Array.isArray(arr)) queueLen = arr.length;
|
||||
} catch { /* file missing or unreadable → no badge */ }
|
||||
return { ...p, queueLen };
|
||||
});
|
||||
res.end(JSON.stringify({
|
||||
projects,
|
||||
logPath: LOG_PATH,
|
||||
position: handle.position(),
|
||||
lastError,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
if (url === "/api/health") {
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: true, projectCount: state.size, logPath: LOG_PATH }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Same-machine fast path. Body: { project: string, prompt: string }.
|
||||
// Looks up the project's filesystem path from agent-projects.conf, then
|
||||
// spawns bash to source agent-hook-lib.sh and call inject_prompt directly.
|
||||
// Returns {ok:true} on success or {ok:false, reason} on failure — the
|
||||
// reason is the structured single-line message inject_prompt emits via
|
||||
// _inject_fail_reason, so the caller can render it to the user without
|
||||
// having to re-diagnose.
|
||||
if (url === "/api/inject" && req.method === "POST") {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => { body += String(chunk); });
|
||||
req.on("end", () => {
|
||||
try {
|
||||
const parsed = body.trim() ? JSON.parse(body) : {};
|
||||
const project: string | undefined = parsed.project;
|
||||
const prompt: string | undefined = parsed.prompt;
|
||||
if (typeof project !== "string" || !project || typeof prompt !== "string") {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: false, reason: "bad-request: body must be {project: string, prompt: string}" }));
|
||||
return;
|
||||
}
|
||||
// Resolve project_dir from the same SSOT the daemon reads. Falls
|
||||
// back to empty string — inject_prompt's cwd path is optional.
|
||||
const projectDir = resolveProjectPath(project) ?? "";
|
||||
|
||||
// Source brand + agent-hook-lib then invoke inject_prompt with our
|
||||
// three positional args. Stderr lines starting with "inject:" carry
|
||||
// the structured failure reason; we grep for the last one.
|
||||
const result = spawnSync(
|
||||
"bash",
|
||||
[
|
||||
"-c",
|
||||
`source "${BRAND_LIB}" 2>/dev/null; source "${AGENT_HOOK_LIB}" || exit 90; inject_prompt "$1" "$2" "$3"`,
|
||||
"fleetcrown-inject",
|
||||
project,
|
||||
prompt,
|
||||
projectDir,
|
||||
],
|
||||
{ encoding: "utf8", timeout: 8000 },
|
||||
);
|
||||
|
||||
if (result.status === 0) {
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: true }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Pull the last "inject:" line out of stderr for the reason; otherwise
|
||||
// synthesize a fallback that still names the failure mode.
|
||||
const stderr = (result.stderr ?? "").toString();
|
||||
const lastReasonLine = stderr.split("\n").filter((l) => l.startsWith("inject:")).pop();
|
||||
const reason = lastReasonLine
|
||||
? lastReasonLine.slice("inject:".length)
|
||||
: result.status === 90
|
||||
? `bash-init: could not source ${AGENT_HOOK_LIB} — is the repo checked out and home/ daemon started from it?`
|
||||
: result.signal === "SIGTERM" || result.signal === null && result.status === null
|
||||
? "timeout: inject_prompt did not return within 8s — zellij may be hung; restart your session"
|
||||
: `inject_prompt exit=${result.status}: ${stderr.trim().split("\n").pop() ?? "no output"}`;
|
||||
|
||||
res.statusCode = 200;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: false, reason }));
|
||||
} catch (err) {
|
||||
res.statusCode = 500;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: false, reason: `home-inject crash: ${err instanceof Error ? err.message : String(err)}` }));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Convenience: POST a JSONL event body to append to the log. Used for manual
|
||||
// testing; the real producers are home/watcher.ts, home/worker.ts, and the
|
||||
// emit_worker_finished function in scripts/agent-hook-bridge.sh.
|
||||
//
|
||||
// Validated against the v=1 schema before append — otherwise a typo or
|
||||
// half-built event leaves a permanent garbled line in the log that
|
||||
// parseEvent on the read side has to skip on every boot.
|
||||
if (url === "/api/events" && req.method === "POST") {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => { body += String(chunk); });
|
||||
req.on("end", () => {
|
||||
try {
|
||||
const line = body.trim();
|
||||
if (!line) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: false, error: "empty body" }));
|
||||
return;
|
||||
}
|
||||
const parsed = parseEvent(line);
|
||||
if (!parsed.ok) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: false, error: parsed.error, raw: parsed.raw }));
|
||||
return;
|
||||
}
|
||||
// Append the original line (preserves caller's field ordering /
|
||||
// formatting) — parsed.event is just the validation product.
|
||||
fs.appendFileSync(LOG_PATH, line + "\n");
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: true, kind: parsed.event.kind }));
|
||||
} catch (e) {
|
||||
res.statusCode = 500;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: false, error: String(e) }));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Cancel an in-flight run. Emits a bridge.cancel event that:
|
||||
// 1) the worker tails and turns into a Ctrl+C sent to the project's tab
|
||||
// 2) state.ts projects into "currentRun = undefined" once the runId matches
|
||||
// 3) the worker treats as a terminator so a never-started dispatch sitting
|
||||
// in pendingDispatches doesn't fire on next worker restart
|
||||
//
|
||||
// Body: { project: string, runId?: string, reason?: string }
|
||||
// If runId is omitted, the live currentRun.runId is used. 404 if there's
|
||||
// no active run for the project.
|
||||
if (url === "/api/cancel" && req.method === "POST") {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => { body += String(chunk); });
|
||||
req.on("end", () => {
|
||||
try {
|
||||
const parsed = body.trim() ? JSON.parse(body) : {};
|
||||
const projectName: string | undefined = parsed.project;
|
||||
if (typeof projectName !== "string" || !projectName) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ error: "missing 'project' string in body" }));
|
||||
return;
|
||||
}
|
||||
const liveState = state.get(projectName);
|
||||
const runId: string | undefined =
|
||||
(typeof parsed.runId === "string" && parsed.runId) || liveState?.currentRun?.runId;
|
||||
if (!runId) {
|
||||
res.statusCode = 404;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({
|
||||
error: `no active run for project: ${projectName}`,
|
||||
hint: "POST body can include a runId to cancel a specific run; otherwise the project must have a currentRun.",
|
||||
}));
|
||||
return;
|
||||
}
|
||||
const reason = (typeof parsed.reason === "string" && parsed.reason.slice(0, 200)) || "user cancel";
|
||||
const cancelled = appendEvent({
|
||||
kind: "bridge.cancel",
|
||||
project: projectName,
|
||||
runId,
|
||||
reason,
|
||||
});
|
||||
// Eager projection — match the /api/dispatch pattern. Closes the
|
||||
// same race: a follow-up dispatch arriving before fs.watch fires
|
||||
// would see stale currentRun and refuse to proceed; with eager
|
||||
// apply, currentRun is already cleared (bridge.cancel projection
|
||||
// matches runId and unsets it). Idempotent re-application by
|
||||
// tailLog: cancelledRunIds.filter() dedupes, currentRun stays
|
||||
// undefined.
|
||||
state = applyEvent(state, cancelled);
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: true, runId, reason }));
|
||||
} catch (e) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ error: String(e) }));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// M6 — dispatch. Run decide() against the current state for a project and
|
||||
// either emit a bridge.dispatch event (when autonomy + confidence say "go")
|
||||
// or return the proposed action for a confirm-mode UI to render.
|
||||
//
|
||||
// Body: { project: string, queueHead?: string, autonomy?: Autonomy, projectPath?: string }
|
||||
// Response on auto-execute: { dispatched: true, decision, runId }
|
||||
// Response on hold: { dispatched: false, decision }
|
||||
if (url === "/api/dispatch" && req.method === "POST") {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => { body += String(chunk); });
|
||||
req.on("end", () => {
|
||||
try {
|
||||
const parsed = body.trim() ? JSON.parse(body) : {};
|
||||
const projectName: string | undefined = parsed.project;
|
||||
if (typeof projectName !== "string" || !projectName) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ error: "missing 'project' string in body" }));
|
||||
return;
|
||||
}
|
||||
// Look up the project — first in the live event-projected state, then
|
||||
// fall back to the agent-projects.conf registry so a brand-new project
|
||||
// (no events yet) can still receive its first dispatch. Last resort:
|
||||
// accept the name verbatim; the brain has nothing to reason about so
|
||||
// decide() defaults to "next_best" with neutral confidence, but that's
|
||||
// a valid first run.
|
||||
const liveState = state.get(projectName);
|
||||
const registered = resolveProjectPath(projectName);
|
||||
if (!liveState && !registered) {
|
||||
res.statusCode = 404;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({
|
||||
error: `unknown project: ${projectName}`,
|
||||
hint: "Add it to ~/.config/agent-projects.conf (TabName|/absolute/path), or POST a worker.* event first.",
|
||||
}));
|
||||
return;
|
||||
}
|
||||
const projectState: ProjectState = liveState ?? {
|
||||
project: projectName,
|
||||
lastEventTs: new Date().toISOString(),
|
||||
recentOutcomes: [],
|
||||
};
|
||||
const decision = decide({
|
||||
project: projectState,
|
||||
queueHead: typeof parsed.queueHead === "string" ? parsed.queueHead : undefined,
|
||||
autonomy: parsed.autonomy as Autonomy | undefined,
|
||||
});
|
||||
|
||||
// Wait actions never dispatch; same for any action where the autonomy
|
||||
// gate said hold. Return the proposal so a confirm-mode UI can render
|
||||
// the countdown + auto-fire button.
|
||||
if (decision.action.kind === "wait" || !decision.autoExecute) {
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ dispatched: false, decision }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Auto-execute: emit a bridge.dispatch event with a fresh run id.
|
||||
const runId = randomUUID();
|
||||
// Resolve the project's filesystem path so the rendered prompt reads
|
||||
// "Work on the project at /home/g/dev/<x>" instead of the project
|
||||
// name as fallback. Caller-supplied wins; otherwise look up the
|
||||
// existing ~/.config/agent-projects.conf SSOT.
|
||||
const projectPath =
|
||||
(typeof parsed.projectPath === "string" && parsed.projectPath) ||
|
||||
resolveProjectPath(projectName);
|
||||
// Pick up the user's prompt queue if present: caller-supplied (request
|
||||
// body) wins, else read /tmp/agent-queue-<tab> — the file mirror the
|
||||
// cloud /api/beacon/queue/[tab] PUT writes (best-effort) for bash-hook
|
||||
// and home/ compat. Either source flows through buildPromptForDispatch
|
||||
// → renderTaskForAdapter → renderQueueBlock so the dispatched prompt
|
||||
// body shows the agent what's pending. Empty/missing queue → no block.
|
||||
const queue: string[] = (() => {
|
||||
if (Array.isArray(parsed.queue)) {
|
||||
return parsed.queue.filter((s: unknown): s is string => typeof s === "string");
|
||||
}
|
||||
try {
|
||||
const file = path.join("/tmp", `agent-queue-${projectName.toLowerCase()}`);
|
||||
const raw = fs.readFileSync(file, "utf8");
|
||||
const arr = JSON.parse(raw);
|
||||
return Array.isArray(arr) ? arr.filter((s: unknown): s is string => typeof s === "string") : [];
|
||||
} catch { return []; }
|
||||
})();
|
||||
const prompt = buildPromptForDispatch(decision, projectState, projectPath, queue);
|
||||
const intent = decision.action.intent;
|
||||
// Adapter resolution: caller-supplied wins (lets the UI override per
|
||||
// dispatch), otherwise fall back to the project's declared adapter
|
||||
// from agent-projects.conf's 3rd field. Worker defaults to "claude"
|
||||
// downstream if both are absent.
|
||||
const adapter: Adapter | undefined =
|
||||
(typeof parsed.adapter === "string" && (ADAPTERS as readonly string[]).includes(parsed.adapter)
|
||||
? (parsed.adapter as Adapter)
|
||||
: undefined)
|
||||
?? resolveProjectAdapter(projectName);
|
||||
const dispatched = appendEvent({
|
||||
kind: "bridge.dispatch",
|
||||
project: projectName,
|
||||
intent,
|
||||
prompt,
|
||||
runId,
|
||||
autonomy: (parsed.autonomy as Autonomy | undefined) ?? "confirm",
|
||||
adapter,
|
||||
reason: decision.action.reason,
|
||||
confidence: decision.confidence,
|
||||
});
|
||||
// Eagerly project so a concurrent /api/dispatch reads the post-state
|
||||
// and decide() returns "wait" instead of firing a second dispatch.
|
||||
// tailLog will re-apply the same event when fs.watch fires; that's
|
||||
// idempotent for bridge.dispatch (just overwrites currentRun).
|
||||
state = applyEvent(state, dispatched);
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ dispatched: true, decision, runId }));
|
||||
} catch (e) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ error: String(e) }));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
res.statusCode = 404;
|
||||
res.setHeader("Content-Type", "text/plain");
|
||||
res.end("Not Found");
|
||||
});
|
||||
|
||||
/**
|
||||
* Build the dispatch prompt for a decision.
|
||||
*
|
||||
* M7: replaces the M6 stub. Reuses the existing src/lib/orchestration
|
||||
* renderer via home/render.ts (single SSOT for prompt text). If the
|
||||
* decision carries an explicit prompt string (queue-drain case), that's
|
||||
* passed through as a 'custom' intent so the queue item itself becomes
|
||||
* the prompt body — same behavior as today's queue→intent="custom" flip.
|
||||
*/
|
||||
function buildPromptForDispatch(
|
||||
decision: Decision,
|
||||
project: ProjectState,
|
||||
projectPath?: string,
|
||||
queue?: string[],
|
||||
): string {
|
||||
if (decision.action.kind === "wait") {
|
||||
// Caller is supposed to short-circuit on wait — never dispatch one.
|
||||
throw new Error("buildPromptForDispatch called on a wait decision");
|
||||
}
|
||||
const intentRaw = decision.action.intent;
|
||||
// Decision.action.intent is a free-form string in the home types; gate
|
||||
// it against the canonical id set before handing to the renderer.
|
||||
const intent =
|
||||
(ORCHESTRATION_TASK_INTENT_IDS as readonly string[]).includes(intentRaw)
|
||||
? (intentRaw as OrchestrationTaskIntentId)
|
||||
: "next_best";
|
||||
// Queue-drain case: the queue item IS the prompt. Pass it through as
|
||||
// intent="custom" so renderTaskForAdapter echoes it verbatim. The
|
||||
// remaining queue (everything after the drained head) still flows so
|
||||
// the agent sees what's coming after this run.
|
||||
if (decision.action.kind === "dispatch" && decision.action.prompt) {
|
||||
return renderPromptForDispatch({
|
||||
project: project.project,
|
||||
projectPath,
|
||||
intent: "custom",
|
||||
customInstructions: decision.action.prompt,
|
||||
queue,
|
||||
});
|
||||
}
|
||||
return renderPromptForDispatch({
|
||||
project: project.project,
|
||||
projectPath,
|
||||
intent,
|
||||
queue,
|
||||
});
|
||||
}
|
||||
|
||||
// Bind to 127.0.0.1 only so the same-machine fast-path /api/inject endpoint
|
||||
// is unreachable from the LAN. Cross-origin browser callers reach it via
|
||||
// fetch("http://localhost:3001/...") with the CORS allow-list above.
|
||||
server.listen(PORT, "127.0.0.1", () => {
|
||||
console.log(`[home] ${APP_NAME} brain listening on http://127.0.0.1:${PORT}`);
|
||||
console.log(`[home] tailing ${LOG_PATH}`);
|
||||
});
|
||||
|
||||
const shutdown = (signal: string) => {
|
||||
console.log(`[home] ${signal} — shutting down`);
|
||||
handle.close();
|
||||
server.close(() => process.exit(0));
|
||||
};
|
||||
process.on("SIGINT", () => shutdown("SIGINT"));
|
||||
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||
@@ -1,74 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start the home/ stack — server (Brain) + watcher (Bridge) + worker (Consumer).
|
||||
# Logs go to /tmp/${APP_SLUG}-home.log so you can tail one file to see all
|
||||
# three. Ctrl-C kills the whole stack cleanly.
|
||||
#
|
||||
# Use: bash scripts/home-start.sh
|
||||
# (UI at http://localhost:3001)
|
||||
#
|
||||
# Tail logs in another terminal:
|
||||
# tail -f /tmp/${APP_SLUG}-home.log
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck source=_brand.sh
|
||||
source "$SCRIPT_DIR/_brand.sh"
|
||||
|
||||
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
LOG_FILE="$(_brand_tmp 'home.log')"
|
||||
PIDS=()
|
||||
|
||||
log() { echo "[home-start] $(date '+%H:%M:%S') $*"; }
|
||||
|
||||
# Truncate the log on each restart so old runs don't accumulate.
|
||||
: > "$LOG_FILE"
|
||||
log "logs → $LOG_FILE"
|
||||
|
||||
# Refuse to start if any port:3001 is already taken — prevents the
|
||||
# double-launch foot-gun where two server.ts processes silently race on
|
||||
# the same log file.
|
||||
if curl -sf --max-time 0.5 http://localhost:3001/api/health >/dev/null 2>&1; then
|
||||
log "ERROR: something is already serving localhost:3001 — refusing to start"
|
||||
log " (curl http://localhost:3001/api/health if you want to see what)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
shutdown() {
|
||||
log "shutdown requested — stopping ${#PIDS[@]} process(es)"
|
||||
for pid in "${PIDS[@]}"; do
|
||||
kill "$pid" 2>/dev/null || true
|
||||
done
|
||||
# Give them ~1s to exit gracefully, then SIGKILL the stragglers.
|
||||
sleep 1
|
||||
for pid in "${PIDS[@]}"; do
|
||||
kill -9 "$pid" 2>/dev/null || true
|
||||
done
|
||||
exit 0
|
||||
}
|
||||
trap shutdown SIGINT SIGTERM EXIT
|
||||
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
# Each process tags its output so the merged log is readable when grepped.
|
||||
# --start is required by all three since 2026-05 — naked `npx tsx home/X.ts`
|
||||
# now exits with a usage banner so accidental one-shots don't leave orphans.
|
||||
launch() {
|
||||
local name="$1" cmd="$2"
|
||||
( exec npx tsx "$cmd" --start 2>&1 | sed -u "s/^/[${name}] /" >> "$LOG_FILE" ) &
|
||||
PIDS+=("$!")
|
||||
log "started $name (pid $!) → $cmd --start"
|
||||
}
|
||||
|
||||
launch server home/server.ts
|
||||
launch watcher home/watcher.ts
|
||||
launch worker home/worker.ts
|
||||
|
||||
log "${#PIDS[@]} process(es) running — Ctrl-C to stop"
|
||||
log "tail -f $LOG_FILE"
|
||||
|
||||
# Wait for any child to exit. If one dies, take the whole stack down so the
|
||||
# user gets a clear signal instead of a half-broken loop.
|
||||
wait -n
|
||||
log "a child process exited — taking the stack down"
|
||||
shutdown
|
||||
@@ -1,139 +1,30 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { gzipSync } from "node:zlib";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* Serves a gzipped tarball of the local helper runtime so a new customer can
|
||||
* install the agent fleet without cloning the repo:
|
||||
* GET /api/agent/daemon
|
||||
*
|
||||
* scripts/fleetcrown-daemon.sh — main polling loop
|
||||
* scripts/_brand.sh — brand SSOT (APP_NAME / APP_SLUG / APP_DOMAIN)
|
||||
* scripts/agent-hook-lib.sh — zellij inject_prompt + shared helpers
|
||||
* scripts/agent-hook-bridge.sh — agent CLI bridge
|
||||
* Used to serve a gzipped tarball of the bash daemon (~3000 lines across
|
||||
* fleetcrown-daemon.sh / agent-hook-bridge.sh / agent-hook-lib.sh + a
|
||||
* Python beacon stack) so a new customer could install the local helper
|
||||
* runtime in one command. Retired in Session 4 of killing-the-bash-daemon
|
||||
* (2026-06-11). The bash stack has been replaced by Fleet Runner desktop
|
||||
* (Electron app) which customers download from /download as a signed
|
||||
* native installer per platform — no bash, no Python beacon, no systemd.
|
||||
*
|
||||
* Together ~1500 lines of bash. They are the local execution surface.
|
||||
*
|
||||
* Tarball is built in pure Node — the first version of this route used
|
||||
* spawn("tar", ...) and 500'd on Vercel because the runtime image may not
|
||||
* carry the tar binary (or spawn can't reach it). The ustar format is
|
||||
* trivial enough (one 512-byte header per file + content padded to 512,
|
||||
* then 1024 zero bytes as end-of-archive) that doing it ourselves avoids
|
||||
* the system-binary dependency entirely.
|
||||
*
|
||||
* Files extract at the destination root (no `scripts/` prefix) so the
|
||||
* agent CLI writes them straight into ~/.local/share/fleetcrown/.
|
||||
*
|
||||
* Public (no auth) — matches the matcher exception in src/proxy.ts.
|
||||
* next.config.ts includes the source files in this route's
|
||||
* outputFileTracingIncludes so they land in the Vercel deployment bundle.
|
||||
* Kept as a 410 Gone for existing installer scripts that may still POST
|
||||
* here. The Location header points at /download so a redirected browser
|
||||
* lands on the Fleet Runner download CTA.
|
||||
*/
|
||||
const FILES = [
|
||||
// Core daemon + shared brand/zellij helpers + bridge entry point.
|
||||
"fleetcrown-daemon.sh",
|
||||
"fleet",
|
||||
"_brand.sh",
|
||||
"_agents.sh",
|
||||
"agent-hook-lib.sh",
|
||||
"agent-hook-bridge.sh",
|
||||
// Per-agent task runners. Claude uses an inline command (no runner); codex
|
||||
// and gemini require these wrappers — without them the daemon hard-fails
|
||||
// when dispatching either agent. The bridge expects $SCRIPT_DIR/run-X-task.sh.
|
||||
"run-codex-task.sh",
|
||||
"run-gemini-task.sh",
|
||||
// systemd installer — the agent CLI's --install flag spawns this so a new
|
||||
// customer's daemon survives shell exit. Uses $SCRIPT_DIR for service
|
||||
// WorkingDirectory + ExecStart, which resolves correctly under the flat
|
||||
// ~/.local/share/fleetcrown/ layout (no PROJECT_DIR/.. assumption is hit on
|
||||
// the env-var token path that the CLI feeds in).
|
||||
"install-fleetcrown-daemon.sh",
|
||||
// Python helpers referenced by agent-hook-bridge.sh. All are wrapped in
|
||||
// `|| true` / `2>/dev/null` in the bridge so absence degrades gracefully —
|
||||
// but real customers want the full experience (audio beacon, idle detection,
|
||||
// notifications). beacon imports _beacon_config so both ship together.
|
||||
"beacon.py",
|
||||
"_beacon_config.py",
|
||||
"get-idle-secs.py",
|
||||
"notify-choice.py",
|
||||
"sync-agent-runtime-config.py",
|
||||
// Audio transcription is invoked by fleetcrown-daemon.sh for recorded prompt
|
||||
// commands and must travel with the flat installed runtime.
|
||||
"transcribe.py",
|
||||
] as const;
|
||||
|
||||
export async function GET() {
|
||||
const scriptsDir = path.join(process.cwd(), "scripts");
|
||||
|
||||
try {
|
||||
const tarball = await buildTarball(scriptsDir, FILES);
|
||||
return new NextResponse(new Uint8Array(tarball), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/gzip",
|
||||
"Cache-Control": "public, max-age=300, s-maxage=300",
|
||||
"Content-Disposition": 'attachment; filename="fleetcrown-daemon.tar.gz"',
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("[agent/daemon] build failed:", (e as Error)?.message, (e as Error)?.stack);
|
||||
return NextResponse.json(
|
||||
{ error: "Daemon bundle unavailable", detail: (e as Error)?.message },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a ustar gzip archive in memory. No external binaries, no extra
|
||||
* deps — just Node builtins. ~50 lines of format-spec implementation.
|
||||
*/
|
||||
async function buildTarball(dir: string, files: readonly string[]): Promise<Buffer> {
|
||||
const chunks: Buffer[] = [];
|
||||
for (const name of files) {
|
||||
const content = await readFile(path.join(dir, name));
|
||||
chunks.push(ustarHeader(name, content.length));
|
||||
chunks.push(padTo512(content));
|
||||
}
|
||||
chunks.push(Buffer.alloc(1024)); // end-of-archive: two zeroed 512-byte blocks
|
||||
return gzipSync(Buffer.concat(chunks));
|
||||
}
|
||||
|
||||
/**
|
||||
* ustar header (512 bytes). Mode 0755 for everything — the .sh files are
|
||||
* either run directly or sourced; making the non-executables executable
|
||||
* too is harmless. The agent CLI re-chmods the two main executables on
|
||||
* extraction regardless.
|
||||
*
|
||||
* Checksum is the sum of all header bytes treating the checksum field
|
||||
* itself as 8 ASCII spaces; written as 6-digit octal + NUL + space.
|
||||
*/
|
||||
function ustarHeader(name: string, size: number): Buffer {
|
||||
const h = Buffer.alloc(512);
|
||||
h.write(name, 0, Math.min(name.length, 99), "utf8");
|
||||
writeOctal(h, 100, 8, 0o755);
|
||||
writeOctal(h, 108, 8, 0);
|
||||
writeOctal(h, 116, 8, 0);
|
||||
writeOctal(h, 124, 12, size);
|
||||
writeOctal(h, 136, 12, Math.floor(Date.now() / 1000));
|
||||
h.write(" ", 148, 8, "ascii"); // checksum placeholder = 8 spaces
|
||||
h.write("0", 156, 1, "ascii"); // typeflag: regular file
|
||||
h.write("ustar\0", 257, 6, "ascii");
|
||||
h.write("00", 263, 2, "ascii");
|
||||
|
||||
let sum = 0;
|
||||
for (let i = 0; i < 512; i++) sum += h[i];
|
||||
h.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii");
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
function writeOctal(buf: Buffer, offset: number, len: number, value: number): void {
|
||||
// Format: zero-padded octal of (len-1) digits + trailing NUL.
|
||||
buf.write(value.toString(8).padStart(len - 1, "0") + "\0", offset, len, "ascii");
|
||||
}
|
||||
|
||||
function padTo512(buf: Buffer): Buffer {
|
||||
const remainder = buf.length % 512;
|
||||
if (remainder === 0) return buf;
|
||||
return Buffer.concat([buf, Buffer.alloc(512 - remainder)]);
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: "The bash daemon installer was retired on 2026-06-11. Download Fleet Runner from /download instead.",
|
||||
next: "/download",
|
||||
},
|
||||
{
|
||||
status: 410,
|
||||
headers: { Location: "/download" },
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
/**
|
||||
* POST /api/system/daemon { action: "start" | "restart" | "stop" }
|
||||
* GET /api/system/daemon (returns current state)
|
||||
*
|
||||
* Controls the fleetcrown-daemon.service systemd user unit. Local-only —
|
||||
* Vercel cloud has no daemon to control, so the
|
||||
* route 403s when isRuntimeAvailable() is false. This is the one-click
|
||||
* recovery path the user surfaced 2026-05-31: until now, when the daemon
|
||||
* went offline the only recovery was a terminal command, which is
|
||||
* product-fatal for the "fleet control" value prop.
|
||||
*
|
||||
* Security: the route shells out to systemctl. We hard-code the unit-name
|
||||
* candidate list + action whitelist; no user input is interpolated into
|
||||
* the shell command. RUNTIME_AVAILABLE is the local-machine gate (Vercel
|
||||
* never sets it, so cloud users can never reach the shell-out path).
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { exec } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { readJsonBody, z } from "@/lib/api/route-helpers";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
|
||||
const execp = promisify(exec);
|
||||
|
||||
const DaemonAction = z.object({
|
||||
action: z.enum(["start", "restart", "stop", "status"]),
|
||||
});
|
||||
|
||||
const DAEMON_UNIT = "fleetcrown-daemon.service";
|
||||
|
||||
// Resolved unit is cached after the first lookup. systemd unit installation is
|
||||
// a one-time setup event; this cache stays valid for the life of the process.
|
||||
let _resolvedUnit: string | null = null;
|
||||
|
||||
async function getUnit(): Promise<string> {
|
||||
if (_resolvedUnit) return _resolvedUnit;
|
||||
try {
|
||||
await execp(`systemctl --user cat ${DAEMON_UNIT}`, { timeout: 2000 });
|
||||
} catch { /* default to canonical so errors reference the only supported unit */ }
|
||||
_resolvedUnit = DAEMON_UNIT;
|
||||
return _resolvedUnit;
|
||||
}
|
||||
|
||||
async function systemctlState(): Promise<"active" | "inactive" | "failed" | "unknown"> {
|
||||
try {
|
||||
const { stdout } = await execp(`systemctl --user is-active ${await getUnit()}`, { timeout: 5000 });
|
||||
const s = stdout.trim();
|
||||
if (s === "active" || s === "inactive" || s === "failed") return s;
|
||||
return "unknown";
|
||||
} catch (e: unknown) {
|
||||
const stdout = (e as { stdout?: string })?.stdout?.toString().trim();
|
||||
if (stdout === "inactive" || stdout === "failed") return stdout;
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
if (!isRuntimeAvailable()) {
|
||||
return NextResponse.json({ error: "Daemon control unavailable on cloud — runs only on the local install." }, { status: 403 });
|
||||
}
|
||||
const userId = await getApiUserId();
|
||||
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
const state = await systemctlState();
|
||||
return NextResponse.json({ state, unit: await getUnit() });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!isRuntimeAvailable()) {
|
||||
return NextResponse.json({
|
||||
error: "Daemon control unavailable on cloud — runs only on the local install. Start the daemon from your machine.",
|
||||
}, { status: 403 });
|
||||
}
|
||||
const userId = await getApiUserId();
|
||||
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
const dataOrResp = await readJsonBody(req, DaemonAction);
|
||||
if (dataOrResp instanceof NextResponse) return dataOrResp;
|
||||
|
||||
const { action } = dataOrResp;
|
||||
const unit = await getUnit();
|
||||
|
||||
// "status" is just a GET in POST clothing — no side effect.
|
||||
if (action === "status") {
|
||||
return NextResponse.json({ state: await systemctlState(), unit });
|
||||
}
|
||||
|
||||
try {
|
||||
await execp(`systemctl --user ${action} ${unit}`, { timeout: 10000 });
|
||||
// systemctl returns immediately; give the unit a beat to settle so the
|
||||
// state we report back is post-action, not pre-action.
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
const state = await systemctlState();
|
||||
return NextResponse.json({ ok: true, action, state, unit });
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: `systemctl ${action} ${unit} failed: ${message}`,
|
||||
state: await systemctlState(),
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,13 @@ export async function GET() {
|
||||
|
||||
const checks: DoctorCheck[] = [];
|
||||
|
||||
for (const unit of ["fleetcrown-app.service", "fleetcrown-beacon-window.service", "fleetcrown-daemon.service"]) {
|
||||
// Session 4 of killing-the-bash-daemon: only the local Next.js prod wrapper
|
||||
// remains as a FleetCrown systemd unit. Fleet Runner desktop is a regular
|
||||
// Electron app the user launches from their tray menu — it has no
|
||||
// systemd unit to probe (its process tree appears under app-fleet-
|
||||
// runner@.service if the user enabled systemd integration, but that's
|
||||
// an OS-level convenience, not a FleetCrown surface).
|
||||
for (const unit of ["fleetcrown-app.service"]) {
|
||||
try {
|
||||
const [active, enabled] = await Promise.all([
|
||||
shell(`systemctl --user is-active ${unit}`).catch(() => "inactive"),
|
||||
@@ -109,16 +115,25 @@ export async function GET() {
|
||||
legacyUnits ? legacyUnits.split("\n").slice(0, 3).join("; ") : "No active unit files listed.",
|
||||
));
|
||||
|
||||
// Session 4 of killing-the-bash-daemon retired the bash bridge that the
|
||||
// Stop hook used to exec. The hook is now expected to be a no-op (or
|
||||
// absent) — Fleet Runner's embedded watcher (home/watcher.ts) detects the
|
||||
// status:ready transition by filesystem mtime and triggers dispatch via
|
||||
// its own TS module (desktop/src/main/dispatch.ts). A hook that still
|
||||
// points at the deleted bridge is broken; flag it.
|
||||
const stopHook = `${homedir()}/.claude/hooks/stop.sh`;
|
||||
const notificationHook = `${homedir()}/.claude/hooks/notification.sh`;
|
||||
const hookTarget = ".local/share/fleetcrown-beacon/agent-hook-bridge.sh";
|
||||
const stopOk = existsSync(stopHook) && readFileSync(stopHook, "utf8").includes(hookTarget);
|
||||
const notificationOk = existsSync(notificationHook) && readFileSync(notificationHook, "utf8").includes(hookTarget);
|
||||
const deadBridgeTarget = ".local/share/fleetcrown-beacon/agent-hook-bridge.sh";
|
||||
const stopExists = existsSync(stopHook);
|
||||
const stopReferencesDeadBridge = stopExists && readFileSync(stopHook, "utf8").includes(deadBridgeTarget);
|
||||
checks.push(check(
|
||||
"hooks",
|
||||
"Claude hooks",
|
||||
stopOk && notificationOk ? "pass" : "fail",
|
||||
stopOk && notificationOk ? "stop and notification hooks target FleetCrown." : "One or more hooks do not target the FleetCrown bridge.",
|
||||
"Claude Stop hook",
|
||||
!stopReferencesDeadBridge ? "pass" : "fail",
|
||||
!stopExists
|
||||
? "No stop.sh installed — Fleet Runner's filesystem watcher triggers dispatch instead."
|
||||
: stopReferencesDeadBridge
|
||||
? "stop.sh still points at the retired bash bridge — rewrite to `exit 0` or remove the file entirely."
|
||||
: "stop.sh is a no-op (correct post-migration state).",
|
||||
));
|
||||
|
||||
const token = readTokenFile();
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* One-click daemon lifecycle controls for the local install (RUNTIME_AVAILABLE=true).
|
||||
* Solves the recurring "daemon offline, no UI to recover" complaint surfaced
|
||||
* 2026-05-31: until now the only way to start the helper after a crash/sleep
|
||||
* was a terminal command, which broke the "fleet control" value prop.
|
||||
*
|
||||
* Cloud users see a disabled tooltip — there's no remote daemon to control.
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import { Play, RotateCw, Square, Loader2, Check, AlertTriangle } from "lucide-react";
|
||||
import { postJson } from "@/lib/api/fetch";
|
||||
|
||||
type DaemonState = "active" | "inactive" | "failed" | "unknown";
|
||||
|
||||
export function DaemonControls({
|
||||
runtimeAvailable,
|
||||
currentState,
|
||||
onAfter,
|
||||
}: {
|
||||
/** True on local installs only — cloud renders disabled buttons. */
|
||||
runtimeAvailable: boolean;
|
||||
/** Pre-fetched state to label the primary action correctly (Start vs Restart). */
|
||||
currentState: DaemonState;
|
||||
/** Caller refreshes its view after an action lands. */
|
||||
onAfter?: () => void;
|
||||
}) {
|
||||
const [busy, setBusy] = useState<null | "start" | "restart" | "stop">(null);
|
||||
const [outcome, setOutcome] = useState<null | { kind: "ok"; state: DaemonState; action: string } | { kind: "error"; message: string }>(null);
|
||||
|
||||
const act = async (action: "start" | "restart" | "stop") => {
|
||||
setBusy(action);
|
||||
setOutcome(null);
|
||||
try {
|
||||
const res = await postJson("/api/system/daemon", { action });
|
||||
const json = await res.json() as { ok?: boolean; state?: DaemonState; error?: string };
|
||||
if (json.ok && json.state) {
|
||||
setOutcome({ kind: "ok", state: json.state, action });
|
||||
onAfter?.();
|
||||
} else {
|
||||
setOutcome({ kind: "error", message: json.error ?? `${action} failed` });
|
||||
}
|
||||
} catch (e) {
|
||||
setOutcome({ kind: "error", message: e instanceof Error ? e.message : String(e) });
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const cloudTooltip = "Daemon control runs on your local install only — the cloud has no helper process to start.";
|
||||
const disabled = !runtimeAvailable;
|
||||
const startLabel = currentState === "active" ? "Running" : "Start daemon";
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act("start")}
|
||||
disabled={disabled || busy !== null || currentState === "active"}
|
||||
title={disabled ? cloudTooltip : "Start the local daemon (systemctl --user start fleetcrown-daemon or equivalent)"}
|
||||
className="ui-btn-secondary ui-btn-xs inline-flex items-center gap-1.5 disabled:opacity-40"
|
||||
>
|
||||
{busy === "start" ? <Loader2 className="h-3 w-3 animate-spin" /> : <Play className="h-3 w-3" />}
|
||||
{currentState === "active" ? "Running" : startLabel}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act("restart")}
|
||||
disabled={disabled || busy !== null}
|
||||
title={disabled ? cloudTooltip : "Restart the local daemon (useful after editing daemon.env)"}
|
||||
className="ui-btn-secondary ui-btn-xs inline-flex items-center gap-1.5 disabled:opacity-40"
|
||||
>
|
||||
{busy === "restart" ? <Loader2 className="h-3 w-3 animate-spin" /> : <RotateCw className="h-3 w-3" />}
|
||||
Restart
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => act("stop")}
|
||||
disabled={disabled || busy !== null || currentState !== "active"}
|
||||
title={disabled ? cloudTooltip : "Stop the local daemon — autopilot won't fire until restarted"}
|
||||
className="ui-btn-ghost ui-btn-xs inline-flex items-center gap-1.5 text-text-muted disabled:opacity-40"
|
||||
>
|
||||
{busy === "stop" ? <Loader2 className="h-3 w-3 animate-spin" /> : <Square className="h-3 w-3" />}
|
||||
Stop
|
||||
</button>
|
||||
|
||||
{outcome?.kind === "ok" && (
|
||||
<span className="inline-flex items-center gap-1 text-micro text-status-positive">
|
||||
<Check className="h-3 w-3" /> {outcome.action} → {outcome.state}
|
||||
</span>
|
||||
)}
|
||||
{outcome?.kind === "error" && (
|
||||
<span className="inline-flex items-center gap-1 text-micro text-status-negative" title={outcome.message}>
|
||||
<AlertTriangle className="h-3 w-3" /> failed
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { X, Radio, WifiOff, Sparkles, Download, Terminal, Cpu, Loader2 } from "l
|
||||
import { timeAgo } from "@/lib/dates";
|
||||
import { APP_NAME } from "@/config/brand";
|
||||
import { getJson, postJson } from "@/lib/api/fetch";
|
||||
import { DaemonControls } from "./DaemonControls";
|
||||
import "@/components/desktop/types"; // declare global window.fleetRunner
|
||||
|
||||
type DaemonState = "active" | "inactive" | "failed" | "unknown";
|
||||
@@ -34,7 +33,6 @@ export function DaemonStatusBanner({
|
||||
onRefresh,
|
||||
}: Props) {
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
const [unitState, setUnitState] = useState<DaemonState>("unknown");
|
||||
// Detect Fleet Runner so we can short-circuit the "Install Fleet Runner"
|
||||
// CTA and replace it with a one-click "Pair this app" button when the
|
||||
// user is already running inside the desktop shell.
|
||||
@@ -43,17 +41,6 @@ export function DaemonStatusBanner({
|
||||
const [pairError, setPairError] = useState<string | null>(null);
|
||||
const [pairedTokenLabel, setPairedTokenLabel] = useState<string | null>(null);
|
||||
|
||||
// Probe systemd unit state on mount + after every successful control
|
||||
// action. Decoupled from daemonOffline (which is "is the daemon pushing
|
||||
// updates?") so the button labels reflect whether the unit is loaded but
|
||||
// not pushing vs truly stopped. Local-only — cloud 403s the GET.
|
||||
useEffect(() => {
|
||||
if (!runtimeAvailable) return;
|
||||
getJson<{ state: DaemonState }>("/api/system/daemon")
|
||||
.then((r) => setUnitState(r.state))
|
||||
.catch(() => setUnitState("unknown"));
|
||||
}, [runtimeAvailable]);
|
||||
|
||||
useEffect(() => {
|
||||
setInsideFleetRunner(typeof window !== "undefined" && !!window.fleetRunner);
|
||||
}, []);
|
||||
@@ -100,9 +87,6 @@ export function DaemonStatusBanner({
|
||||
: null;
|
||||
|
||||
const refreshAfterAction = () => {
|
||||
getJson<{ state: DaemonState }>("/api/system/daemon")
|
||||
.then((r) => setUnitState(r.state))
|
||||
.catch(() => {});
|
||||
onRefresh?.();
|
||||
};
|
||||
|
||||
@@ -243,24 +227,18 @@ export function DaemonStatusBanner({
|
||||
<p className="text-text-secondary leading-relaxed">
|
||||
The helper on your computer stopped sending updates. All agent commands are safely queued until it reconnects.
|
||||
</p>
|
||||
<DaemonControls
|
||||
runtimeAvailable={runtimeAvailable}
|
||||
currentState={unitState}
|
||||
onAfter={refreshAfterAction}
|
||||
/>
|
||||
{!runtimeAvailable && (
|
||||
<div className="space-y-2 text-xs text-text-muted">
|
||||
<p>
|
||||
You're on the cloud install — daemon control runs only from your local machine.
|
||||
Open {APP_NAME} at <code className="rounded bg-surface-overlay px-1">http://localhost:3000</code> to start/restart the helper.
|
||||
</p>
|
||||
<p>
|
||||
Token expired or migrated DB?{" "}
|
||||
<Link href="/settings" className="text-accent underline">Mint a fresh ck_* token</Link>{" "}
|
||||
and re-paste it into Fleet Runner / your CLI installer.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2 text-xs text-text-muted">
|
||||
<p>
|
||||
Launch Fleet Runner from your tray / app menu to bring it back online. Closed it by accident?{" "}
|
||||
<Link href="/download" className="text-accent underline">Re-install Fleet Runner</Link>
|
||||
{" "}or check its log for the connection error.
|
||||
</p>
|
||||
<p>
|
||||
Token expired or migrated DB?{" "}
|
||||
<Link href="/settings" className="text-accent underline">Mint a fresh ck_* token</Link>{" "}
|
||||
and re-paste it into Fleet Runner.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -223,63 +223,13 @@ export function useControlData(): ControlDataHook {
|
||||
return () => clearTimeout(id);
|
||||
}, [lastTabResultsAt]);
|
||||
|
||||
// Try the same-machine fast path first: when the user's home/ daemon is
|
||||
// listening on localhost:3001, route inject directly there and skip
|
||||
// Vercel + Postgres + daemon-polling (7 hops → 3). The fast path needs a
|
||||
// resolved customPrompt; promptKey-only dispatches still go cloud-side
|
||||
// where the key→prompt resolver lives.
|
||||
//
|
||||
// Failure modes that fall through to the cloud path:
|
||||
// - no daemon (connection refused / DNS / timeout)
|
||||
// - daemon responded {ok:false} — the reason already carries the
|
||||
// actionable detail; we re-throw it so the caller can render it
|
||||
// without a cloud round-trip
|
||||
// - dispatch carries only a promptKey (no resolved text) — local
|
||||
// daemon can't expand it without the cloud prompt registry
|
||||
const tryLocalInject = async (tab: string, customPrompt: string): Promise<{ ok: true } | { ok: false; reason: string } | null> => {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 600);
|
||||
const r = await fetch("http://127.0.0.1:3001/api/inject", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ project: tab, prompt: customPrompt }),
|
||||
signal: ctrl.signal,
|
||||
});
|
||||
clearTimeout(timer);
|
||||
if (!r.ok) return null;
|
||||
const body = await r.json().catch(() => null);
|
||||
if (!body || typeof body !== "object") return null;
|
||||
if (body.ok === true) return { ok: true };
|
||||
if (body.ok === false && typeof body.reason === "string") return { ok: false, reason: body.reason };
|
||||
return null;
|
||||
} catch {
|
||||
// No local daemon (most common case for cloud-only users), or it timed
|
||||
// out. Either way, cloud path takes over silently.
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const inject = async (tab: string, promptKey?: string, customPrompt?: string): Promise<{ mode: "direct" | "queued" }> => {
|
||||
// Local fast path: only fires when we have resolved prompt text (no
|
||||
// promptKey-only dispatch) AND no per-card adapter override beyond the
|
||||
// default — the local daemon picks the running adapter by process scan.
|
||||
if (customPrompt && !promptKey) {
|
||||
const localResult = await tryLocalInject(tab, customPrompt);
|
||||
if (localResult?.ok === true) {
|
||||
setTimeout(refresh, REFRESH_AFTER_DISPATCH_MS);
|
||||
return { mode: "direct" };
|
||||
}
|
||||
if (localResult?.ok === false) {
|
||||
// The reason is the same actionable string the cloud path would
|
||||
// eventually surface — throwing here saves the cloud round-trip
|
||||
// when we already know exactly what went wrong.
|
||||
throw new Error(localResult.reason);
|
||||
}
|
||||
// Fall through to cloud — local daemon unreachable or non-JSON reply.
|
||||
}
|
||||
|
||||
// Same-machine fast path (POST localhost:3001/api/inject → home/server.ts
|
||||
// → bash inject_prompt) was retired in Session 4 of killing-the-bash-
|
||||
// daemon (2026-06-11). Every inject now goes through the cloud
|
||||
// /api/inject endpoint; Fleet Runner desktop polls /api/control/commands
|
||||
// and types the resulting prompt into zellij. Same end-state, one
|
||||
// transport instead of two, no bash anywhere.
|
||||
const res = await postJson("/api/inject", { tab, promptKey, customPrompt, adapter: data?.agentConfig.agent ?? selectedAgent });
|
||||
if (!res.ok) await throwApiError(res, `HTTP ${res.status}`);
|
||||
const body = await res.json().catch(() => ({}));
|
||||
|
||||
Reference in new issue
Block a user