mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-05 13:37:18 +01:00
feat(control): run server-side agents in owned PTYs; autopilot clarity
Fixes the headless-box launch/dispatch failure at the root and clears up the overloaded "autopilot" vocabulary. Workstream A — PTY migration, Phase 1 (server-side only): - On a box with RUNTIME_AVAILABLE=true, zellij sessions are detached, so `action go-to-tab-name` blocked to the 6s timeout (spawnSync /bin/sh ETIMEDOUT) — every launch/dispatch into kivvi/revampit failed. Launch and inject now run the agent in a FleetCrown-owned PTY via the existing Executor (docs/architecture/agent-execution-platform.md step 3): no zellij focus, no attached-terminal dependency, viewable in the browser terminal. - New SSOT helper provisionAgentWorkspace() + writeInitialPromptWhenReady() (src/lib/agent-execution/launch.ts), shared by /api/workspaces and /api/agent/launch (DRY). - /api/inject + /api/control/tab-inject route to executor.write when a live PTY workspace exists, else fall back to zellij unchanged. Dispatch inherits it. Cloud/runner paths untouched. switch-agent stays on zellij (deferred). - desktop poller: catch-all translates a residual ETIMEDOUT into an actionable message so the raw spawn error never reaches the UI. Workstream B — autopilot clarity: - Rename the cron-jobs feature "Autopilot" -> "Scheduled Jobs" everywhere (new SSOT SCHEDULED_JOBS_LABEL; AutopilotCard -> ScheduledJobsCard; /system, nav, ProjectPromptsTab). DB table cron_jobs unchanged. - The real auto-inject toggle now owns the word "Autopilot" (label beside the Build all/Pause all control; settings section + hints; fixed stale Strategist/Groq copy). - next_best template: add the explicit "nothing high-impact remains -> status: blocked / awaiting_user, stop and hand back" brake — end development and wait for the human instead of inventing T2 busywork. Verified live: kivvi launch -> 200 + running PTY + real claude process (no ETIMEDOUT); inject -> mode:pty; tsc (src+desktop), eslint, test:home 97/97, autopilot-defaults/digest/auth all green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
bdf161acd1
commit
08bb9735fc
14 files changed
+219
-127
No files matched your search
@@ -518,7 +518,15 @@ async function handleCommand(
|
||||
}
|
||||
} catch (e) {
|
||||
ok = false
|
||||
error = (e as Error).message
|
||||
const raw = (e as Error).message ?? ''
|
||||
// A zellij `action` against a detached session blocks until our hard timeout
|
||||
// and surfaces as a cryptic "spawnSync /bin/sh ETIMEDOUT". Translate any such
|
||||
// timeout that escaped the per-command handlers into an actionable message so
|
||||
// the UI never shows the raw spawn error. (launchAgentInTab already does this
|
||||
// for its own path; this is the catch-all for focus/inject/close helpers.)
|
||||
error = /ETIMEDOUT|timed out|timeout/i.test(raw)
|
||||
? `Zellij didn't respond while handling "${command.type}" — the target session is likely detached. Attach it (zellij attach <session>) so Fleet Runner can drive it, then retry.`
|
||||
: raw
|
||||
}
|
||||
|
||||
// Drop the dedup sentinel on success so a re-served command (PATCH ack
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Suspense } from "react";
|
||||
import { PageLayout } from "@/components/ui/page-layout";
|
||||
import { SystemStats } from "@/components/system/SystemStats";
|
||||
import { AutopilotCard } from "@/components/system/AutopilotCard";
|
||||
import { ScheduledJobsCard } from "@/components/system/ScheduledJobsCard";
|
||||
import { MemorySummaryCard } from "@/components/system/MemorySummaryCard";
|
||||
import { RecentFailuresCard } from "@/components/system/RecentFailuresCard";
|
||||
import { FleetDoctorCard } from "@/components/system/FleetDoctorCard";
|
||||
@@ -24,7 +24,7 @@ export default async function SystemPage() {
|
||||
// boundary — caught live on fleetcrown.orangecat.ch/system showing
|
||||
// "Something went wrong" with the Server Components render error.
|
||||
// Defensive: fall back to an empty list so the rest of the page renders
|
||||
// (AutopilotCard handles empty initialJobs cleanly). The error is
|
||||
// (ScheduledJobsCard handles empty initialJobs cleanly). The error is
|
||||
// captured in console so postmortem still works.
|
||||
let jobs: Awaited<ReturnType<typeof listCronJobsForUser>> = [];
|
||||
try {
|
||||
@@ -35,11 +35,11 @@ export default async function SystemPage() {
|
||||
|
||||
return (
|
||||
<PullToRefresh>
|
||||
<PageLayout title="System" subtitle="Infrastructure health and Ivy autopilot">
|
||||
<PageLayout title="System" subtitle="Infrastructure health and scheduled jobs">
|
||||
<SystemStats />
|
||||
<FleetDoctorCard />
|
||||
<GlobalAutoContinueCard />
|
||||
<AutopilotCard initialJobs={jobs} />
|
||||
<ScheduledJobsCard initialJobs={jobs} />
|
||||
<Suspense fallback={<CardSkeleton />}>
|
||||
<MemorySummaryCard />
|
||||
</Suspense>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import fs from "fs";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { readJsonBody, z } from "@/lib/api/route-helpers";
|
||||
import { launchAgentInTab } from "@/lib/agent-runtime";
|
||||
import { provisionAgentWorkspace, writeInitialPromptWhenReady } from "@/lib/agent-execution/launch";
|
||||
import { listAgentRegistry } from "@/lib/agent-registry";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { enqueueLaunchAgentCommand } from "@/db/queries/pending-commands";
|
||||
import { persistProjectRuntimeIfNewer, prependProjectPrompt } from "@/db/queries/project-states";
|
||||
import { persistProjectRuntimeIfNewer } from "@/db/queries/project-states";
|
||||
import { stateFile } from "@/lib/agent-config";
|
||||
|
||||
const LaunchAgentBody = z.object({
|
||||
@@ -17,71 +17,6 @@ const LaunchAgentBody = z.object({
|
||||
initialPrompt: z.string().trim().max(4000).optional(),
|
||||
});
|
||||
|
||||
const AGENT_BASENAMES = new Set(["claude", "codex", "gemini", "openclaw", "grok"]);
|
||||
|
||||
function isCursorAgentArgv0(argv0: string): boolean {
|
||||
return argv0.includes(".local/bin/agent") || argv0.includes("/.cursor/");
|
||||
}
|
||||
|
||||
function isAgentRunningIn(dir: string): boolean {
|
||||
try {
|
||||
for (const entry of fs.readdirSync("/proc")) {
|
||||
if (!/^\d+$/.test(entry)) continue;
|
||||
try {
|
||||
const argv0 = fs.readFileSync(`/proc/${entry}/cmdline`, "utf8").split("\0")[0] ?? "";
|
||||
const basename = argv0.split("/").pop() ?? "";
|
||||
const isKnownAgent = AGENT_BASENAMES.has(basename)
|
||||
|| (basename === "agent" && isCursorAgentArgv0(argv0));
|
||||
if (!isKnownAgent) continue;
|
||||
if (fs.readlinkSync(`/proc/${entry}/cwd`) === dir) return true;
|
||||
} catch { /* skip */ }
|
||||
}
|
||||
} catch { /* /proc unavailable */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
function scheduleInjectAfterLaunch(userId: string, tab: string, dir: string, prompt: string): void {
|
||||
// The agent appearing in /proc does NOT mean its TUI is ready for keystrokes
|
||||
// — claude/grok take a beat to render their input box, and a single blind
|
||||
// inject at first-sighting races that render and is silently lost (observed:
|
||||
// identical launches where the prompt landed in one tab and vanished in
|
||||
// another). So: inject, then VERIFY the text actually shows up in the pane;
|
||||
// retry until it does. If it never lands within the window, drop the prompt
|
||||
// into the project's visible queue rather than losing it — a recoverable
|
||||
// failure beats a silent one. This writes the queue ONLY as a last resort, so
|
||||
// it does not double-deliver against a successful inject.
|
||||
const probe = prompt.replace(/\s+/g, " ").trim().slice(0, 24);
|
||||
const MAX_ATTEMPTS = 16; // ~48s — covers slow agent cold-starts
|
||||
let attempts = 0;
|
||||
const tick = async () => {
|
||||
attempts++;
|
||||
try {
|
||||
const { injectIntoTab, peekTab } = await import("@/lib/zellij");
|
||||
if (isAgentRunningIn(dir)) {
|
||||
// Already delivered (this or a prior attempt landed)? Stop — never double-send.
|
||||
if (probe && peekTab(tab).includes(probe)) return;
|
||||
injectIntoTab(tab, prompt);
|
||||
}
|
||||
} catch { /* retry below */ }
|
||||
if (attempts < MAX_ATTEMPTS) {
|
||||
setTimeout(tick, 3000);
|
||||
return;
|
||||
}
|
||||
// Window exhausted — confirm once more, then fall back to the visible queue.
|
||||
try {
|
||||
const { peekTab } = await import("@/lib/zellij");
|
||||
if (probe && peekTab(tab).includes(probe)) return;
|
||||
} catch { /* fall through to the queue fallback */ }
|
||||
try {
|
||||
await prependProjectPrompt(userId, tab, tab, prompt);
|
||||
console.error(`[agent/launch] inject never confirmed for "${tab}" — prompt queued for manual/auto delivery`);
|
||||
} catch (err) {
|
||||
console.error(`[agent/launch] inject + queue fallback both failed for "${tab}":`, err);
|
||||
}
|
||||
};
|
||||
setTimeout(tick, 3000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record the state transition the launch just caused, so the dashboard reflects
|
||||
* reality immediately instead of waiting for the next runtime observation to
|
||||
@@ -90,7 +25,7 @@ function scheduleInjectAfterLaunch(userId: string, tab: string, dir: string, pro
|
||||
* that read "is a tab live" (switch-agent, auto-continue) silently no-op.
|
||||
*
|
||||
* This writes the *display-state* mirror only — never the prompt-queue transport
|
||||
* (which would double-deliver against scheduleInjectAfterLaunch). The write is
|
||||
* (which would double-deliver against the initial-prompt write). The write is
|
||||
* guarded by runtimeObservedAt, so the next genuine observation supersedes it,
|
||||
* and isCurrentPromptStale's absent-agent grace self-heals if the launch failed.
|
||||
*/
|
||||
@@ -162,11 +97,16 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
try {
|
||||
launchAgentInTab(tab, dir, exactEntry.id, model);
|
||||
// Server-side launch runs the agent in a FleetCrown-owned PTY (not a zellij
|
||||
// pane): a headless box has no attached zellij client, so the old
|
||||
// go-to-tab-name puppeting blocked forever. The owned PTY is viewable in the
|
||||
// browser terminal and needs no attached human terminal. See
|
||||
// docs/architecture/agent-execution-platform.md (step 3).
|
||||
await provisionAgentWorkspace(userId, { projectKey: tab, dir, agent: exactEntry.id, model });
|
||||
const promptText = initialPrompt?.trim();
|
||||
await recordLaunchedState(userId, tab, exactEntry.id, promptText || `Starting ${exactEntry.label}…`);
|
||||
if (promptText) {
|
||||
scheduleInjectAfterLaunch(userId, tab, dir, promptText);
|
||||
writeInitialPromptWhenReady(userId, tab, promptText);
|
||||
}
|
||||
return NextResponse.json({ ok: true, tab, agent: exactEntry.id });
|
||||
} catch (err) {
|
||||
|
||||
@@ -3,6 +3,8 @@ import { readJsonBody, z } from "@/lib/api/route-helpers";
|
||||
import { enqueueInjectCommand } from "@/db/queries/pending-commands";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { executor } from "@/lib/agent-execution";
|
||||
import { workspaceIdFor } from "@/lib/agent-execution/ownership";
|
||||
|
||||
const Body = z.object({
|
||||
tab: z.string().trim().min(1).max(120),
|
||||
@@ -17,6 +19,21 @@ export async function POST(req: NextRequest) {
|
||||
if (dataOrResp instanceof NextResponse) return dataOrResp;
|
||||
const { tab, prompt } = dataOrResp;
|
||||
|
||||
// A FleetCrown-owned PTY agent is driven directly via the executor — no zellij.
|
||||
const wsId = workspaceIdFor(userId, tab);
|
||||
const wsHandle = isRuntimeAvailable() ? executor.get(wsId) : null;
|
||||
if (wsHandle && wsHandle.status !== "exited") {
|
||||
const { stateFile, clearHandshakeFiles } = await import("@/lib/agent-config");
|
||||
const fs = await import("fs");
|
||||
const nowS = Math.floor(Date.now() / 1000);
|
||||
fs.writeFileSync(stateFile.prompt(tab), JSON.stringify({
|
||||
key: "custom", label: prompt.slice(0, 40), startedAt: nowS, source: "inject", adapter: "unknown",
|
||||
}));
|
||||
clearHandshakeFiles(tab);
|
||||
executor.write(wsId, prompt.endsWith("\r") ? prompt : `${prompt}\r`);
|
||||
return NextResponse.json({ ok: true, mode: "pty", tab });
|
||||
}
|
||||
|
||||
if (isRuntimeAvailable()) {
|
||||
const [{ injectIntoTab, isUserTypingInTab }, { stateFile, clearHandshakeFiles }, fs] = await Promise.all([
|
||||
import("@/lib/zellij"),
|
||||
|
||||
+39
-18
@@ -4,6 +4,8 @@ import { ORCHESTRATION_ADAPTER_IDS, ORCHESTRATION_TASK_INTENT_IDS, type Orchestr
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { readJsonBody, z } from "@/lib/api/route-helpers";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { executor } from "@/lib/agent-execution";
|
||||
import { workspaceIdFor } from "@/lib/agent-execution/ownership";
|
||||
import { executeInject } from "@/lib/executor";
|
||||
import { createOrchestrationEvent } from "@/db/queries/orchestration-events";
|
||||
import { createOrchestrationRun } from "@/db/queries/orchestration-runs";
|
||||
@@ -93,6 +95,15 @@ export async function POST(req: NextRequest) {
|
||||
const projectPath: string | null = dbMatch.dirPath ?? null;
|
||||
const projectId: string | null = dbMatch.entityProjectId ?? null;
|
||||
|
||||
// Is this project backed by a live FleetCrown-owned PTY (server-side launch)?
|
||||
// The executor registry is the SSOT — a live handle means we drive the agent's
|
||||
// stdin directly and bypass every zellij concept (tab resolution, focus-dance,
|
||||
// the zsh user-typing hook). No live workspace → fall back to the legacy zellij
|
||||
// path unchanged (cloud mode never has one; injectFn is null there).
|
||||
const ptyWorkspaceId = workspaceIdFor(userId, canonical);
|
||||
const ptyHandle = isRuntimeAvailable() ? executor.get(ptyWorkspaceId) : null;
|
||||
const ptyBacked = !!ptyHandle && ptyHandle.status !== "exited";
|
||||
|
||||
// Honor the project's per-row agent preference when the caller didn't pin one.
|
||||
// Without this the runner defaults to "claude" for every project regardless
|
||||
// of agent_pref, so a Gemini project gets a Claude launch and a Cursor
|
||||
@@ -126,14 +137,18 @@ export async function POST(req: NextRequest) {
|
||||
getZellijTabs: (await import("@/lib/zellij")).getZellijTabs,
|
||||
}));
|
||||
|
||||
const activeTabs = await getZellijTabs();
|
||||
if (activeTabs.length > 0) {
|
||||
effectiveTab = resolveEffectiveTab(canonical, activeTabs);
|
||||
if (effectiveTab === canonical && !activeTabs.some((t) => t.toLowerCase() === canonical.toLowerCase())) {
|
||||
return NextResponse.json(
|
||||
{ error: `Tab "${canonical}" is not open in Zellij. Open it and try again.` },
|
||||
{ status: 422 },
|
||||
);
|
||||
// PTY-backed agents have no zellij tab — effectiveTab stays canonical and we
|
||||
// skip the "is the tab open in zellij" gate entirely.
|
||||
if (!ptyBacked) {
|
||||
const activeTabs = await getZellijTabs();
|
||||
if (activeTabs.length > 0) {
|
||||
effectiveTab = resolveEffectiveTab(canonical, activeTabs);
|
||||
if (effectiveTab === canonical && !activeTabs.some((t) => t.toLowerCase() === canonical.toLowerCase())) {
|
||||
return NextResponse.json(
|
||||
{ error: `Tab "${canonical}" is not open in Zellij. Open it and try again.` },
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,14 +200,19 @@ export async function POST(req: NextRequest) {
|
||||
const resolvedProjectPath = projectPath ?? canonical;
|
||||
const nowS = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Build the Zellij injection function — executor calls it only when ZELLIJ_SESSION_NAME
|
||||
// is present in this process (dev server inside Zellij). Otherwise it queues for the runner.
|
||||
const injectFn = isRuntimeAvailable()
|
||||
? async () => {
|
||||
const { injectIntoTab } = await import("@/lib/zellij");
|
||||
injectIntoTab(effectiveTab, prompt);
|
||||
}
|
||||
: null;
|
||||
// Build the local injection function. PTY-backed agents are driven directly via
|
||||
// the executor (write to the owned PTY's stdin); otherwise fall back to the
|
||||
// legacy zellij path. Null in cloud mode → executeInject queues for the runner.
|
||||
const injectFn = !isRuntimeAvailable()
|
||||
? null
|
||||
: ptyBacked
|
||||
? async () => {
|
||||
executor.write(ptyWorkspaceId, prompt.endsWith("\r") ? prompt : `${prompt}\r`);
|
||||
}
|
||||
: async () => {
|
||||
const { injectIntoTab } = await import("@/lib/zellij");
|
||||
injectIntoTab(effectiveTab, prompt);
|
||||
};
|
||||
|
||||
const trackableIntent = eventIntent !== "hard_stop" && eventIntent !== "close_session";
|
||||
if (!runId && trackableIntent && !isRuntimeAvailable()) {
|
||||
@@ -220,9 +240,10 @@ export async function POST(req: NextRequest) {
|
||||
|
||||
// If the user is actively at the ZSH prompt in this tab, skip injection to
|
||||
// avoid garbling whatever they're typing. Requires the fleetcrown-typing hooks
|
||||
// in ~/.zshrc (see scripts/install-fleetcrown-hooks.sh).
|
||||
// in ~/.zshrc (see scripts/install-fleetcrown-hooks.sh). This is a zellij-only
|
||||
// concept — a FleetCrown-owned PTY has no human at its prompt, so skip it.
|
||||
// Side effects (beacon cancel, /tmp state) run only after this gate passes.
|
||||
if (isRuntimeAvailable()) {
|
||||
if (isRuntimeAvailable() && !ptyBacked) {
|
||||
const { isUserTypingInTab } = await import("@/lib/zellij");
|
||||
if (isUserTypingInTab(effectiveTab)) {
|
||||
const fingerprint = promptFingerprint(prompt);
|
||||
|
||||
@@ -3,7 +3,8 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { z, readJsonBody } from "@/lib/api/route-helpers";
|
||||
import { executor } from "@/lib/agent-execution";
|
||||
import { workspaceIdFor } from "@/lib/agent-execution/ownership";
|
||||
import { buildAgentOptionLaunchCommand, isAgentId } from "@/lib/agent-registry";
|
||||
import { provisionAgentWorkspace } from "@/lib/agent-execution/launch";
|
||||
import { isAgentId } from "@/lib/agent-registry";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
|
||||
// node-pty (the LocalPtyExecutor) only runs in the Node runtime.
|
||||
@@ -38,30 +39,31 @@ export async function POST(req: NextRequest) {
|
||||
// Plain terminals omit cwd → open in $HOME. Agent launches always pass one.
|
||||
const cwd = data.cwd ?? homedir();
|
||||
|
||||
let command = data.command;
|
||||
let args = data.args;
|
||||
// Agent launch → reuse the SSOT provision helper (shared with /api/agent/launch).
|
||||
if (data.agent) {
|
||||
if (!isAgentId(data.agent)) {
|
||||
return NextResponse.json({ error: `Unknown agent: ${data.agent}` }, { status: 400 });
|
||||
}
|
||||
const launchCommand = buildAgentOptionLaunchCommand({ agent: data.agent, model: data.model }, cwd);
|
||||
// Login + interactive (-lic), NOT plain -c: the agent CLIs live on PATH only
|
||||
// after the profile/nvm chain loads (claude is in ~/.nvm/.../bin), and the
|
||||
// launch command's own `source ~/.bashrc` clobbers PATH non-interactively.
|
||||
// A login-interactive shell matches what a zellij pane gives the agent.
|
||||
command = "bash";
|
||||
args = ["-lic", launchCommand];
|
||||
}
|
||||
if (!command) {
|
||||
return NextResponse.json({ error: "Provide a command or an agent" }, { status: 400 });
|
||||
const handle = await provisionAgentWorkspace(userId, {
|
||||
projectKey: data.projectKey,
|
||||
dir: cwd,
|
||||
agent: data.agent,
|
||||
model: data.model,
|
||||
cols: data.cols,
|
||||
rows: data.rows,
|
||||
});
|
||||
return NextResponse.json({ ok: true, workspace: handle });
|
||||
}
|
||||
|
||||
const id = workspaceIdFor(userId, data.projectKey);
|
||||
// Plain shell (or explicit command) → provision directly.
|
||||
if (!data.command) {
|
||||
return NextResponse.json({ error: "Provide a command or an agent" }, { status: 400 });
|
||||
}
|
||||
const handle = await executor.provision({
|
||||
id,
|
||||
id: workspaceIdFor(userId, data.projectKey),
|
||||
cwd,
|
||||
command,
|
||||
args,
|
||||
command: data.command,
|
||||
args: data.args,
|
||||
cols: data.cols,
|
||||
rows: data.rows,
|
||||
});
|
||||
|
||||
@@ -15,8 +15,8 @@ import {
|
||||
// Binary autopilot since the 2026-06-11 collapse. Plain language only — no
|
||||
// internal template names (next_best) or handoff-field jargon (status:working).
|
||||
const AUTOMATION_HINTS: Record<AutoInjectMode, string> = {
|
||||
off: "Off — agents stop when a task ends; you dispatch every next step yourself.",
|
||||
on: "On — agents work through each project's queue, then pick the next-best task automatically. Busy agents, blockers, and failing health checks still pause dispatch.",
|
||||
off: "Autopilot off — agents stop when a task ends; you dispatch every next step yourself.",
|
||||
on: "Autopilot on — agents work through each project's queue, then pick the next-best task automatically. Busy agents, blockers, and failing health checks still pause dispatch.",
|
||||
};
|
||||
|
||||
type Props = {
|
||||
@@ -135,6 +135,9 @@ export function ControlFleetStatus({
|
||||
{runnerDetail && <span className="text-text-muted">· {runnerDetail}</span>}
|
||||
</div>
|
||||
<div className="ui-control-fleet-actions">
|
||||
{/* Name the control so the fleet-wide play/pause reads as "Autopilot"
|
||||
— the one place that word now means the auto-inject engine. */}
|
||||
<span className="ui-micro-label hidden text-text-tertiary sm:inline">Autopilot</span>
|
||||
<AutomationPolicyControl
|
||||
mode={automationMode}
|
||||
saving={automationSaving}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState } from "react";
|
||||
import { AlertTriangle, Bot, ChevronDown, ChevronUp, Loader2, Plus, ToggleLeft, ToggleRight, X, Zap } from "lucide-react";
|
||||
import { createCronJob, patchCronJob } from "@/lib/api/crons";
|
||||
import { SCHEDULED_JOB_LABEL, SCHEDULED_JOBS_LABEL } from "@/lib/crons-shared";
|
||||
import type { LinkedJob, ProjectData } from "./project-detail-types";
|
||||
import { NAV } from "@/config/navigation";
|
||||
|
||||
@@ -95,7 +96,7 @@ function NewJobForm({
|
||||
onClick={() => setOpen(true)}
|
||||
className="ui-btn-add-success"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" /> New autopilot job for this project
|
||||
<Plus className="h-3.5 w-3.5" /> New scheduled job for this project
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -103,7 +104,7 @@ function NewJobForm({
|
||||
return (
|
||||
<div className="rounded-lg border border-status-positive/20 bg-status-positive-subtle p-3 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="ui-micro-label text-status-positive/70">New Autopilot Job</div>
|
||||
<div className="ui-micro-label text-status-positive/70">New {SCHEDULED_JOB_LABEL}</div>
|
||||
<button onClick={() => setOpen(false)} className="text-text-muted hover:text-text-secondary"><X className="h-3.5 w-3.5" /></button>
|
||||
</div>
|
||||
<input placeholder="Job name" value={name} onChange={(e) => setName(e.target.value)}
|
||||
@@ -143,11 +144,11 @@ export function PromptsTab({
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2 ui-micro-label font-medium">
|
||||
<Bot className="h-3.5 w-3.5" />
|
||||
Autopilot Jobs {jobs.length > 0 && <span className="text-text-tertiary normal-case">({jobs.length})</span>}
|
||||
{SCHEDULED_JOBS_LABEL} {jobs.length > 0 && <span className="text-text-tertiary normal-case">({jobs.length})</span>}
|
||||
</div>
|
||||
|
||||
{jobs.length === 0 ? (
|
||||
<p className="text-xs text-text-secondary">No autopilot jobs linked to this project yet.</p>
|
||||
<p className="text-xs text-text-secondary">No scheduled jobs linked to this project yet.</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{jobs.map((job) => (
|
||||
|
||||
@@ -92,13 +92,13 @@ export function BeaconSettings() {
|
||||
) : (
|
||||
<div className="space-y-8">
|
||||
|
||||
{/* ─── Subgroup: Auto-inject behavior ─── */}
|
||||
{/* ─── Subgroup: Autopilot behavior ─── */}
|
||||
<div className="space-y-5">
|
||||
<h3 className="text-xs font-semibold uppercase tracking-wide text-text-tertiary">Auto-inject</h3>
|
||||
<h3 className="text-xs font-semibold uppercase tracking-wide text-text-tertiary">Autopilot</h3>
|
||||
|
||||
{/* ── Auto-inject mode ── */}
|
||||
{/* ── Autopilot mode ── */}
|
||||
<div className="space-y-2">
|
||||
<label className="ui-kicker">Auto-inject mode</label>
|
||||
<label className="ui-kicker">Autopilot mode</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{AUTO_INJECT_MODES.map((m) => (
|
||||
<button
|
||||
@@ -118,7 +118,7 @@ export function BeaconSettings() {
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-text-muted">
|
||||
Decides what gets injected when a session ends and the queue/handoff combine to suggest a next move. Strategist is the default and uses Groq; switch to Queue only if you want strictly explicit prompts, or Off to dispatch every prompt by hand.
|
||||
When an agent finishes a task, autopilot sends the next queued instruction — or, if the queue is empty, picks the next-best task automatically. It pauses on its own for busy agents, pending blockers, and failing health checks. Set it Off to dispatch every prompt by hand.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
+4
-4
@@ -6,7 +6,7 @@ import { Card, CardHeader } from "@/components/ui/card";
|
||||
import { EmptyState } from "@/components/ui/empty-state";
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import type { CronJob } from "@/lib/crons-shared";
|
||||
import { humanCronSchedule } from "@/lib/crons-shared";
|
||||
import { humanCronSchedule, SCHEDULED_JOBS_LABEL } from "@/lib/crons-shared";
|
||||
import { patchCronJob } from "@/lib/api/crons";
|
||||
import { JobDetail } from "./JobDetail";
|
||||
|
||||
@@ -84,7 +84,7 @@ function JobRow({
|
||||
);
|
||||
}
|
||||
|
||||
export function AutopilotCard({ initialJobs }: { initialJobs: CronJob[] }) {
|
||||
export function ScheduledJobsCard({ initialJobs }: { initialJobs: CronJob[] }) {
|
||||
const [jobs, setJobs] = useState(initialJobs);
|
||||
const [selected, setSelected] = useState<CronJob | null>(null);
|
||||
|
||||
@@ -134,7 +134,7 @@ export function AutopilotCard({ initialJobs }: { initialJobs: CronJob[] }) {
|
||||
<Card>
|
||||
<CardHeader
|
||||
icon={Bot}
|
||||
title="Autopilot"
|
||||
title={SCHEDULED_JOBS_LABEL}
|
||||
right={
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
{okCount > 0 && (
|
||||
@@ -154,7 +154,7 @@ export function AutopilotCard({ initialJobs }: { initialJobs: CronJob[] }) {
|
||||
/>
|
||||
|
||||
{jobs.length === 0 ? (
|
||||
<EmptyState>No autopilot jobs configured</EmptyState>
|
||||
<EmptyState>No scheduled jobs configured</EmptyState>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* Project-scoped job groups */}
|
||||
@@ -45,7 +45,7 @@ export const NAV = {
|
||||
projects: { id: "projects", label: "Projects", description: "Repo health & project context", href: "/projects", icon: FolderKanban, active: true, mobile: true },
|
||||
prompts: { id: "prompts", label: "Prompts", description: "Agent prompt library & scheduler", href: "/prompts", icon: Zap, active: true, mobile: false },
|
||||
activity: { id: "activity", label: "Activity", description: "Project status and event timeline", href: "/activity", icon: Newspaper, active: true, mobile: false },
|
||||
system: { id: "system", label: "System", description: "Runtime health & autopilot jobs", href: "/system", icon: Server, active: true, mobile: false },
|
||||
system: { id: "system", label: "System", description: "Runtime health & scheduled jobs", href: "/system", icon: Server, active: true, mobile: false },
|
||||
|
||||
memory: { id: "memory", label: "Memory", description: "Knowledge graph & entity activity", href: "/memory", icon: Brain, active: true, mobile: false },
|
||||
thoughts: { id: "thoughts", label: "Thoughts", description: "Essays on architecture & systems", href: "/thoughts", icon: BookOpen, active: true, mobile: false },
|
||||
|
||||
@@ -888,6 +888,8 @@ Self-throttle (decides whether to engage Pick at all — both directions share t
|
||||
|
||||
Backward (loop protection): If no-op-count ≥ 2 OR last 3 commits are all in the same dir with no real user message between turns → write status: blocked, block-reason: "low-value loop — need human direction" and STOP. Do not pick a task this turn. A loop that keeps firing into the same gravity well burns the founder's attention faster than any single bad pick. The autopilot is the founder's amplifier, not their replacement.
|
||||
|
||||
Stop (nothing high-impact remains — the most important brake): If Pick finds nothing in rules 0–8 (no pending blocker, no type/lint errors, no uncommitted work, no unactioned ask, no open T0/T1, no genuine adjacent-broken-thing) so the only candidate left is a T2 cleanup (rule 9), AND no real user message has arrived between turns → write status: blocked, block-reason: "awaiting_user — no high-impact work remains; <one-line summary of where the project stands>" and STOP. Do NOT manufacture T2 busywork to keep the loop alive. Ending development and handing back to the human IS the correct move when there is nothing genuinely worth doing — the founder picks the next direction. (A human who explicitly wants cleanup still gets it via rule 3 or a typed prompt; this brake only suppresses autopilot-invented T2 churn.)
|
||||
|
||||
Pick (first matching wins):
|
||||
0. Pending blocker file in ~/.claude/sessions/<P>.blockers/pending/ → cat its contents to the user, do not pick a task this turn. When the user confirms the ask is resolved, mv the file from pending/ to applied/.
|
||||
1. Type errors → fix.
|
||||
@@ -898,7 +900,7 @@ Pick (first matching wins):
|
||||
6. Open T1 in roadmap → smallest.
|
||||
7. Session-next names a non-T2-cleanup task → continue it.
|
||||
8. Find one adjacent broken thing (silent error, flow that doesn't close, feature half-wired). Fix it.
|
||||
9. Open T2 in roadmap → smallest.
|
||||
9. Open T2 in roadmap → smallest. But on autopilot with no human ask, the Stop brake above takes precedence — hand back rather than invent T2 churn.
|
||||
|
||||
Classify:
|
||||
T0 = broken in production OR data integrity at risk
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* provisionAgentWorkspace — the SSOT for "launch an agent in a FleetCrown-owned
|
||||
* PTY." Used by both /api/workspaces (the browser terminal) and /api/agent/launch
|
||||
* (Control's launch button on a self-hosted box). Builds the SAME login-interactive
|
||||
* shell + registry launch command the legacy zellij path used, so PATH/env/model
|
||||
* resolution is identical — only the substrate (an owned PTY vs a zellij pane) differs.
|
||||
*
|
||||
* Why this replaces zellij name-puppeting on the server: a zellij `action
|
||||
* go-to-tab-name` blocks forever on a detached session (a headless box has no
|
||||
* attached client), so launch timed out. Owning the PTY removes the dependency
|
||||
* on an attached human terminal entirely.
|
||||
*/
|
||||
import { executor } from "@/lib/agent-execution";
|
||||
import { workspaceIdFor } from "@/lib/agent-execution/ownership";
|
||||
import type { AgentEvent, Unsubscribe, WorkspaceHandle } from "@/lib/agent-execution/types";
|
||||
import { buildAgentOptionLaunchCommand, type AgentOption } from "@/lib/agent-registry";
|
||||
|
||||
export interface ProvisionAgentArgs {
|
||||
/** Project key — becomes the workspace id together with the user id. */
|
||||
projectKey: string;
|
||||
/** Working directory the agent runs in. */
|
||||
dir: string;
|
||||
/** A validated agent id (caller must have checked isAgentId / the registry). */
|
||||
agent: AgentOption;
|
||||
model?: string;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provision (or re-attach to) a FleetCrown-owned PTY running the given agent.
|
||||
* Idempotent per (user, projectKey): a live workspace is returned, never respawned.
|
||||
*/
|
||||
export async function provisionAgentWorkspace(
|
||||
userId: string,
|
||||
args: ProvisionAgentArgs,
|
||||
): Promise<WorkspaceHandle> {
|
||||
const launchCommand = buildAgentOptionLaunchCommand({ agent: args.agent, model: args.model }, args.dir);
|
||||
// Login + interactive (-lic), NOT plain -c: the agent CLIs live on PATH only
|
||||
// after the profile/nvm chain loads (claude is in ~/.nvm/.../bin), and the
|
||||
// launch command's own `source ~/.bashrc` clobbers PATH non-interactively.
|
||||
// A login-interactive shell matches what a zellij pane gives the agent.
|
||||
return executor.provision({
|
||||
id: workspaceIdFor(userId, args.projectKey),
|
||||
cwd: args.dir,
|
||||
command: "bash",
|
||||
args: ["-lic", launchCommand],
|
||||
cols: args.cols,
|
||||
rows: args.rows,
|
||||
});
|
||||
}
|
||||
|
||||
/** Settle window after the agent first shows life before pasting — lets the CLI
|
||||
* finish drawing its prompt so paste+enter is accepted instead of swallowed. */
|
||||
const SETTLE_MS = 2000;
|
||||
|
||||
/**
|
||||
* Write an initial prompt into a freshly-provisioned agent PTY once the agent is
|
||||
* actually up — keyed off the first running/idle event rather than a blind timer
|
||||
* (the keystrokes would otherwise land in the boot banner). A max-wait fallback
|
||||
* guarantees a silent agent still receives it. Fire-and-forget.
|
||||
*/
|
||||
export function writeInitialPromptWhenReady(
|
||||
userId: string,
|
||||
projectKey: string,
|
||||
prompt: string,
|
||||
maxWaitMs = 15000,
|
||||
): void {
|
||||
const id = workspaceIdFor(userId, projectKey);
|
||||
const text = prompt.endsWith("\r") ? prompt : `${prompt}\r`;
|
||||
let unsub: Unsubscribe = () => {};
|
||||
let sent = false;
|
||||
const send = () => {
|
||||
if (sent) return;
|
||||
sent = true;
|
||||
try { executor.write(id, text); } catch { /* workspace gone — nothing to do */ }
|
||||
unsub();
|
||||
clearTimeout(timer);
|
||||
};
|
||||
// subscribe replays buffered events synchronously; send is only ever invoked
|
||||
// via setTimeout, so `unsub`/`timer` are always assigned by the time it runs.
|
||||
unsub = executor.subscribe(id, 0, (e: AgentEvent) => {
|
||||
if (e.kind === "status" && (e.status === "running" || e.status === "idle")) {
|
||||
setTimeout(send, SETTLE_MS);
|
||||
}
|
||||
});
|
||||
const timer = setTimeout(send, maxWaitMs);
|
||||
}
|
||||
@@ -1,5 +1,15 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* User-facing display name for scheduled cron jobs. Internally these remain
|
||||
* "cron jobs" (table cron_jobs, /api/crons) — the UI calls them "Scheduled Jobs"
|
||||
* so the word "Autopilot" belongs to ONE thing only: the auto-inject engine (the
|
||||
* fleet Build all/Pause all toggle). SSOT for every heading/label that names this
|
||||
* feature. Prose sentences use the lowercase noun "scheduled job(s)".
|
||||
*/
|
||||
export const SCHEDULED_JOBS_LABEL = "Scheduled Jobs";
|
||||
export const SCHEDULED_JOB_LABEL = "Scheduled Job";
|
||||
|
||||
export const CreateCronBody = z.object({
|
||||
name: z.string().trim().min(1, "name is required"),
|
||||
scheduleExpr: z.string().trim().min(1, "scheduleExpr is required"),
|
||||
|
||||
Reference in new issue
Block a user