mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 05:17:01 +01:00
feat(autopilot): collapse 5 modes to off|on; delete strategist + beacon popup
Session 3 of killing-the-bash-daemon plan (/home/g/.claude/plans/
structured-baking-kazoo.md). Collapses the five-tier auto_inject_mode
ladder (off|queue_only|beacon|next_best|strategist) to binary off|on
and removes the dead complexity that protected the upper tiers.
What the modes meant (now retired):
off — manual, every dispatch is a click
queue_only — drain the queue, then stop
beacon — popup with countdown auto-pick (default for new users)
next_best — auto-fire canned template silently
strategist — Groq composes a fresh prompt from context
What "on" means now: when status:ready arrives, fire the queue head if
non-empty, else the canned next_best template. Safety rails (status:
working/blocked, blockers, no-op fuse, health/tests gate) all still
apply — being "on" doesn't override the agent's "not done" signal.
Most users only ever toggled between off and "fire when ready"; the
intermediate tiers added cognitive load without proportionate value.
DB migration applied to both local and Hetzner prod in this commit:
UPDATE beacon_settings SET auto_inject_mode = CASE WHEN
auto_inject_mode='off' THEN 'off' ELSE 'on' END
UPDATE entities SET auto_inject_mode_override = (same CASE)
ALTER TABLE ... ADD CONSTRAINT CHECK IN ('off','on')
ALTER TABLE beacon_settings ALTER COLUMN auto_inject_mode
SET DEFAULT 'on'
0 beacon_settings rows existed (both envs), 21 entities updated on
prod, 1324 on local. Constraints added cleanly.
Code deltas:
- src/config/beacon.ts — AUTO_INJECT_MODE_VALUES is ["off","on"].
LEGACY_AUTO_INJECT_MODE_VALUES + normalizeAutoInjectMode helper
kept for tolerant reads of any unmigrated row.
- src/lib/constants/control.ts — DEFAULT_AUTO_INJECT_MODE = "on".
- src/db/schema/beacon-settings.ts — default "on".
- src/lib/orchestration/dispatch-gates.ts — simplified to off/on
decision; no fall-through to a composer. Safety rails preserved.
- src/app/api/control/dispatch/route.ts — 361 → 160 LoC. Deleted
buildPrompt, callGroq, parseGroqResponse, OrangeCat fetch, the
strategist branch, and the gitBranch/recentCommits/mission
decision inputs. DispatchResult.source union dropped "groq" +
"fallback"; DispatchAction dropped "composed".
- scripts/test/dispatch-gates.ts — rewrote for binary modes;
11/11 pass.
Popup deletion (the L3 "beacon" mode's UI surface):
- src/app/beacon/{layout,[id]/{page,BeaconClient},live/{page,
BeaconLiveClient}}.tsx — the popup React tree
- src/app/api/beacon/{[id],cancel,sse,window/{hide,show}}/route.ts
— popup-specific API routes
KEPT: /api/beacon/queue (Fleet Runner uses it), /api/beacon/recent,
/api/beacon/transcribe, top-level /api/beacon/route.ts (other
consumers besides the popup import cancelActiveBeaconSessions).
UI updates (mode collapse fans through):
- AutomationPolicyControl.tsx — 2 dots not 5
- ControlFleetStatus.tsx — 2 hint strings
- ProjectCard.tsx — automation labels for off/on only
- use-project-card-actions.ts — strategist "composed" path removed
Verification: tsc clean, test:home 97/97, test:dispatch-gates 11/11,
test:control-presenter 19/19, lint clean (8 pre-existing warnings).
scripts/agent-hook-bridge.sh shows as dirty in the working tree from
earlier system-level edits today; intentionally left out of this
commit. It (and the rest of the bash scripts) gets deleted in
Session 4.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
b39a05b406
commit
2391c6f735
21 files changed
+219
-1494
No files matched your search
@@ -1,11 +1,14 @@
|
||||
/**
|
||||
* Inline self-tests for autopilot defaults — keeps the new-user experience
|
||||
* locked to the autopilot policy across the schema, queries, constants, and
|
||||
* shell/Python fallbacks.
|
||||
* and the SSOT chain (constant → schema → queries → UI hook → settings UI)
|
||||
* aligned after the 2026-06-11 mode collapse. The bash bridge has been
|
||||
* retired (Session 1-2 of killing-the-bash-daemon); tests that asserted
|
||||
* on bash mechanics moved out with it.
|
||||
* Run: npm run test:autopilot-defaults
|
||||
*/
|
||||
import { readFileSync } from "fs";
|
||||
import { DEFAULT_AUTO_INJECT_MODE } from "@/lib/constants/control";
|
||||
import { AUTO_INJECT_MODE_VALUES, normalizeAutoInjectMode } from "@/config/beacon";
|
||||
|
||||
function assert(condition: boolean, message: string): void {
|
||||
if (!condition) throw new Error(message);
|
||||
@@ -19,16 +22,38 @@ function runTests(): void {
|
||||
console.log(` ✓ ${label}`);
|
||||
};
|
||||
|
||||
// 2026-05-31: default flipped from "strategist" (L5 Mission, loose cannon)
|
||||
// to "beacon" (L3, popup + countdown auto-pick). The right starting trust
|
||||
// level for the five-level ladder Manual/Queue/Beacon/Continuous/Mission.
|
||||
check("DEFAULT_AUTO_INJECT_MODE is 'beacon'", () => {
|
||||
assert(DEFAULT_AUTO_INJECT_MODE === "beacon", `expected beacon, got ${DEFAULT_AUTO_INJECT_MODE}`);
|
||||
// ── Default + enum invariants ────────────────────────────────────────────
|
||||
|
||||
check("DEFAULT_AUTO_INJECT_MODE is 'on'", () => {
|
||||
// 2026-06-11 — collapsed from beacon (L3 popup) to binary on. New users
|
||||
// get fire-when-ready by default; safety rails (status:working, blockers,
|
||||
// health, no-op fuse) still apply.
|
||||
assert(DEFAULT_AUTO_INJECT_MODE === "on", `expected on, got ${DEFAULT_AUTO_INJECT_MODE}`);
|
||||
});
|
||||
|
||||
check("AUTO_INJECT_MODE_VALUES is exactly ['off', 'on']", () => {
|
||||
assert(AUTO_INJECT_MODE_VALUES.length === 2, `expected 2 values, got ${AUTO_INJECT_MODE_VALUES.length}`);
|
||||
assert(AUTO_INJECT_MODE_VALUES[0] === "off", "first value must be 'off'");
|
||||
assert(AUTO_INJECT_MODE_VALUES[1] === "on", "second value must be 'on'");
|
||||
});
|
||||
|
||||
check("normalizeAutoInjectMode collapses legacy values", () => {
|
||||
assert(normalizeAutoInjectMode("off") === "off", "off → off");
|
||||
assert(normalizeAutoInjectMode("on") === "on", "on → on");
|
||||
assert(normalizeAutoInjectMode("queue_only") === "on", "queue_only → on");
|
||||
assert(normalizeAutoInjectMode("beacon") === "on", "beacon → on");
|
||||
assert(normalizeAutoInjectMode("next_best") === "on", "next_best → on");
|
||||
assert(normalizeAutoInjectMode("strategist") === "on", "strategist → on");
|
||||
assert(normalizeAutoInjectMode(null) === "on", "null → on");
|
||||
assert(normalizeAutoInjectMode(undefined) === "on", "undefined → on");
|
||||
assert(normalizeAutoInjectMode("garbage") === "on", "unknown → on (safe default)");
|
||||
});
|
||||
|
||||
// ── SSOT chain — every layer reads the same constant ────────────────────
|
||||
|
||||
check("Drizzle schema column default matches", () => {
|
||||
const schema = readFileSync("src/db/schema/beacon-settings.ts", "utf8");
|
||||
assert(/default\("beacon"\)/.test(schema), "beacon-settings.ts schema must default to 'beacon'");
|
||||
assert(/default\("on"\)/.test(schema), "beacon-settings.ts schema must default to 'on'");
|
||||
});
|
||||
|
||||
check("Queries DEFAULTS sources the constant (no drift)", () => {
|
||||
@@ -41,8 +66,8 @@ function runTests(): void {
|
||||
const route = readFileSync("src/app/api/control/dispatch/route.ts", "utf8");
|
||||
assert(/DEFAULT_AUTO_INJECT_MODE/.test(route),
|
||||
"dispatch route must use DEFAULT_AUTO_INJECT_MODE when no settings row exists");
|
||||
assert(!/settings\?\.auto_inject_mode\s*\?\?\s*"queue_only"/.test(route),
|
||||
"dispatch route must not drift back to queue_only as the implicit default");
|
||||
assert(!/"queue_only"|"beacon"|"next_best"|"strategist"/.test(route),
|
||||
"dispatch route must not reference any retired mode value");
|
||||
});
|
||||
|
||||
check("Coercer returns the constant for unknown values", () => {
|
||||
@@ -51,10 +76,10 @@ function runTests(): void {
|
||||
"coerceAutoInjectMode must return DEFAULT_AUTO_INJECT_MODE on miss");
|
||||
});
|
||||
|
||||
check("Dispatch Groq fallback uses nextbest when queue empty", () => {
|
||||
const route = readFileSync("src/app/api/control/dispatch/route.ts", "utf8");
|
||||
assert(/queue\.length > 0 \? "queue" : "nextbest"/.test(route),
|
||||
"Groq fallback must return nextbest when queue is empty");
|
||||
check("Dispatch route returns nextbest on empty queue when on", () => {
|
||||
const gates = readFileSync("src/lib/orchestration/dispatch-gates.ts", "utf8");
|
||||
assert(/queueLength > 0 \? "queue" : "nextbest"/.test(gates),
|
||||
"dispatch-gates must return nextbest when queue is empty");
|
||||
});
|
||||
|
||||
check("Automation policy hook seeds from DEFAULT_AUTO_INJECT_MODE", () => {
|
||||
@@ -69,110 +94,13 @@ function runTests(): void {
|
||||
"BeaconSettings must seed from DEFAULT_AUTO_INJECT_MODE — never an inline literal");
|
||||
});
|
||||
|
||||
check("Python offline fallback returns 'beacon'", () => {
|
||||
const py = readFileSync("scripts/_beacon_config.py", "utf8");
|
||||
assert(/get\(.auto_inject_mode., .beacon.\)/.test(py),
|
||||
"_beacon_config.py get_auto_inject_mode must default to 'beacon'");
|
||||
});
|
||||
|
||||
check("Shell fallback (settings JSON missing) returns 'beacon'", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-bridge.sh", "utf8");
|
||||
const matches = sh.match(/auto_inject_mode/g) ?? [];
|
||||
assert(matches.length >= 2, "agent-hook-bridge.sh must read auto_inject_mode in both code paths");
|
||||
// The two bash fallback echoes must say beacon (one for the JSON-parse path, one for the Python-fallback path).
|
||||
const beaconFallbacks = (sh.match(/echo\s+beacon/g) ?? []).length;
|
||||
assert(beaconFallbacks >= 2, `expected ≥2 'echo beacon' fallbacks, got ${beaconFallbacks}`);
|
||||
});
|
||||
|
||||
check("patch_project_state uses portable ISO date (not milliseconds)", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-bridge.sh", "utf8");
|
||||
assert(!/iso_now=\$\(date --iso-8601=milliseconds\)/.test(sh),
|
||||
"patch_project_state must not call date --iso-8601=milliseconds — GNU date rejects it and set -e kills the stop hook before autopilot");
|
||||
assert(/patch_project_state[\s\S]*date -u \+%Y-%m-%dT%H:%M:%S/.test(sh),
|
||||
"patch_project_state must use portable UTC ISO timestamp");
|
||||
});
|
||||
|
||||
check("Stop hook queue-empty falls through to next_best", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-bridge.sh", "utf8");
|
||||
assert(/queue action but no queue item — falling through to next_best/.test(sh),
|
||||
"autopilot must fall through to next_best when dispatch says queue but queue is empty");
|
||||
});
|
||||
|
||||
check("autopilot reads DB queue via beacon API", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-bridge.sh", "utf8");
|
||||
assert(/_fetch_prompt_queue_json/.test(sh), "_fetch_prompt_queue_json helper must exist");
|
||||
assert(/\/api\/beacon\/queue\//.test(sh), "autopilot must fetch authoritative DB queue");
|
||||
});
|
||||
|
||||
check("Stop hook loads daemon.env for production URL and token", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-bridge.sh", "utf8");
|
||||
assert(/_load_daemon_env/.test(sh), "hook must load daemon.env (fleetcrown + legacy cockpit)");
|
||||
assert(/fleetcrown\/daemon\.env/.test(sh), "hook must read ~/.config/fleetcrown/daemon.env");
|
||||
assert(/COCKPIT_BASE_URL|FLEETCROWN_BASE_URL|APP_BASE_URL/.test(sh),
|
||||
"hook must honor production base URL env vars");
|
||||
assert(/APP\|FLEETCROWN\|COCKPIT/.test(sh),
|
||||
"token helper must read daemon token from daemon.env with brand prefixes");
|
||||
});
|
||||
|
||||
check("Daemon autopilot watchdog backs up Stop hook", () => {
|
||||
const sh = readFileSync("scripts/fleetcrown-daemon.sh", "utf8");
|
||||
assert(/_autopilot_watchdog/.test(sh), "daemon must include autopilot watchdog");
|
||||
assert(/agent-hook-bridge\.sh" autopilot/.test(sh), "watchdog must delegate to hook bridge");
|
||||
});
|
||||
|
||||
check("Hook bridge exposes autopilot CLI mode", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-bridge.sh", "utf8");
|
||||
assert(/autopilot\)/.test(sh), "agent-hook-bridge must support autopilot mode");
|
||||
});
|
||||
|
||||
check("Stop hook runs autopilot before patch_project_state", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-bridge.sh", "utf8");
|
||||
const stopBlock = sh.slice(sh.indexOf("handle_stop()"), sh.indexOf("handle_notification()"));
|
||||
const autopilotIdx = stopBlock.indexOf("autopilot_dispatch_and_inject");
|
||||
const patchIdx = stopBlock.indexOf('patch_project_state "$TAB_NAME" "readyAt"');
|
||||
assert(autopilotIdx >= 0 && patchIdx >= 0 && autopilotIdx < patchIdx,
|
||||
"autopilot must run immediately after ready sentinel — before patch_project_state");
|
||||
});
|
||||
|
||||
check("Autopilot queues inject via /api/inject when daemon token present", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-bridge.sh", "utf8");
|
||||
assert(/queue_inject_via_api/.test(sh), "queue_inject_via_api helper must exist");
|
||||
assert(/\/api\/inject/.test(sh), "autopilot must queue through /api/inject");
|
||||
});
|
||||
|
||||
check("Inject route accepts daemon bearer token", () => {
|
||||
const route = readFileSync("src/app/api/inject/route.ts", "utf8");
|
||||
assert(/getApiUserId/.test(route), "/api/inject must use getApiUserId for daemon auth");
|
||||
assert(!/getSessionUserId/.test(route), "/api/inject must not require browser session only");
|
||||
});
|
||||
|
||||
check("Daemon watchdog detects session handoff without Stop hook", () => {
|
||||
const sh = readFileSync("scripts/fleetcrown-daemon.sh", "utf8");
|
||||
assert(/ready_source="handoff"/.test(sh), "watchdog must detect status:ready handoff files");
|
||||
assert(/handoff:\$\{ready_at\}/.test(sh), "handoff dedupe key must prevent re-fire loops");
|
||||
});
|
||||
|
||||
check("inject_prompt resolves suffixed Zellij tab names", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-lib.sh", "utf8");
|
||||
assert(/_resolve_live_tab_name/.test(sh), "live tab resolver must exist");
|
||||
assert(/_find_session_for_tab[\s\S]*_resolve_live_tab_name/.test(sh),
|
||||
"_find_session_for_tab must use live tab resolution");
|
||||
});
|
||||
|
||||
check("Stop hook is autopilot — no popup race, no choice-file polling", () => {
|
||||
const sh = readFileSync("scripts/agent-hook-bridge.sh", "utf8");
|
||||
assert(!/beacon_launch/.test(sh), "beacon_launch (Chrome --app popup) must be removed from the bridge");
|
||||
assert(!/notify-choice\.py/.test(sh), "notify-choice.py (KDE action buttons) must not be called");
|
||||
assert(!/_choice_file/.test(sh), "the two-layer choice-file race must be gone");
|
||||
assert(/autopilot_dispatch_and_inject/.test(sh), "autopilot_dispatch_and_inject helper must exist");
|
||||
assert(/push_notify_stop/.test(sh), "push_notify_stop helper (Web Push) must exist");
|
||||
assert(/\/api\/control\/dispatch/.test(sh), "autopilot path must POST /api/control/dispatch");
|
||||
assert(/status: ready \| working/.test(sh), "autopilot prompts must require the status handoff field");
|
||||
const stopCalls = sh.match(/autopilot_dispatch_and_inject\s+"\$TAB_NAME"/g) ?? [];
|
||||
assert(stopCalls.length >= 1, "handle_stop must invoke autopilot_dispatch_and_inject");
|
||||
});
|
||||
|
||||
console.log(`\n${passed}/${passed} passed`);
|
||||
console.log(`\n${passed} passed`);
|
||||
}
|
||||
|
||||
runTests();
|
||||
@@ -1,10 +1,13 @@
|
||||
/**
|
||||
* Inline tests for the dispatch-gate decisions. These gates short-circuit
|
||||
* /api/control/dispatch BEFORE any Groq call and BEFORE any auto-injection.
|
||||
* They are the safety primitives the user trusts: "if I write status:working,
|
||||
* autopilot stays out of my way." Live-incident regression coverage for
|
||||
* 2026-05-31 where the autopilot fired into the user's keystrokes mid-typing
|
||||
* despite the session handoff saying status:working.
|
||||
* /api/control/dispatch BEFORE any auto-injection. They are the safety
|
||||
* primitives the user trusts: "if I write status:working, autopilot stays
|
||||
* out of my way." Live-incident regression coverage for 2026-05-31 where
|
||||
* the autopilot fired into the user's keystrokes mid-typing despite the
|
||||
* session handoff saying status:working.
|
||||
*
|
||||
* The 5-tier autopilot ladder collapsed to off|on on 2026-06-11; tests
|
||||
* exercise the simpler logic. The strategist composer path is gone.
|
||||
*
|
||||
* Run: npm run test:dispatch-gates
|
||||
*/
|
||||
@@ -22,11 +25,13 @@ function runTests(): void {
|
||||
console.log(` ✓ ${label}`);
|
||||
};
|
||||
|
||||
// ── Safety gates (must fire regardless of mode) ────────────────────────
|
||||
|
||||
check("status:working short-circuits before any other gate", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "working",
|
||||
blockerCount: 0,
|
||||
mode: "strategist",
|
||||
mode: "on",
|
||||
queueLength: 5,
|
||||
streakSuffix: "",
|
||||
});
|
||||
@@ -35,11 +40,11 @@ function runTests(): void {
|
||||
assert(result!.source === "status_gate", `expected source=status_gate, got ${result!.source}`);
|
||||
});
|
||||
|
||||
check("status:working overrides queue_only mode (user-intent wins)", () => {
|
||||
check("status:working overrides on mode + queue (user-intent wins)", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "working",
|
||||
blockerCount: 0,
|
||||
mode: "queue_only",
|
||||
mode: "on",
|
||||
queueLength: 3,
|
||||
streakSuffix: "",
|
||||
});
|
||||
@@ -50,7 +55,7 @@ function runTests(): void {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "blocked",
|
||||
blockerCount: 0,
|
||||
mode: "strategist",
|
||||
mode: "on",
|
||||
queueLength: 5,
|
||||
streakSuffix: "",
|
||||
});
|
||||
@@ -63,7 +68,7 @@ function runTests(): void {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 1,
|
||||
mode: "strategist",
|
||||
mode: "on",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
@@ -76,7 +81,7 @@ function runTests(): void {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "strategist",
|
||||
mode: "on",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
noOpCount: 3,
|
||||
@@ -90,13 +95,15 @@ function runTests(): void {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 3,
|
||||
mode: "strategist",
|
||||
mode: "on",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result!.reason.includes("3 pending blocker"), "reason must surface the actual count");
|
||||
});
|
||||
|
||||
// ── Mode gates (binary off / on) ───────────────────────────────────────
|
||||
|
||||
check("mode=off returns mode_gate when status and blockers are clean", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
@@ -109,69 +116,50 @@ function runTests(): void {
|
||||
assert(result?.action === "off", "mode=off yields action=off");
|
||||
});
|
||||
|
||||
check("mode=queue_only with empty queue yields action=off (idle)", () => {
|
||||
check("mode=on with queue items fires action=queue", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "queue_only",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result?.action === "off", "queue_only + empty queue = idle");
|
||||
assert(result?.reason.includes("queue is empty"), "reason must explain empty queue");
|
||||
});
|
||||
|
||||
check("mode=queue_only with queue fires action=queue", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "queue_only",
|
||||
mode: "on",
|
||||
queueLength: 2,
|
||||
streakSuffix: " [last 5: ✓✓✓]",
|
||||
});
|
||||
assert(result?.action === "queue", "queue_only + items = fire queue head");
|
||||
assert(result?.action === "queue", "on + items = fire queue head");
|
||||
assert(result?.source === "mode_gate", `expected source=mode_gate, got ${result?.source}`);
|
||||
assert(result?.reason.includes("[last 5: ✓✓✓]"), "streak suffix must be appended");
|
||||
});
|
||||
|
||||
check("mode=next_best returns canned action with streak suffix", () => {
|
||||
check("mode=on with empty queue fires action=nextbest", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "next_best",
|
||||
mode: "on",
|
||||
queueLength: 0,
|
||||
streakSuffix: " [last 5: ✗✓]",
|
||||
});
|
||||
assert(result?.action === "nextbest", "legacy mode = canned next_best");
|
||||
assert(result?.action === "nextbest", "on + empty queue = canned next_best");
|
||||
assert(result?.source === "empty_queue", `expected source=empty_queue, got ${result?.source}`);
|
||||
assert(result?.reason.includes("queue empty"), "reason must explain empty queue");
|
||||
assert(result?.reason.includes("[last 5: ✗✓]"), "streak suffix appended");
|
||||
});
|
||||
|
||||
check("mode=strategist with clean state yields null (fall through to Groq)", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 0,
|
||||
mode: "strategist",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result === null, "no gate fired → null → route proceeds to Groq composition");
|
||||
});
|
||||
|
||||
check("empty status string is treated permissively (preserves legacy behavior)", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "",
|
||||
blockerCount: 0,
|
||||
mode: "strategist",
|
||||
mode: "on",
|
||||
queueLength: 0,
|
||||
streakSuffix: "",
|
||||
});
|
||||
assert(result === null, "missing status (legacy clients) does not block — preserves existing behavior");
|
||||
// Empty status falls through to mode handling — autopilot fires.
|
||||
assert(result?.action === "nextbest", "missing status (legacy clients) does not block — autopilot fires");
|
||||
});
|
||||
|
||||
check("status:ready with blockers still blocks (safety beats happy-path)", () => {
|
||||
const result = evaluateDispatchGates({
|
||||
status: "ready",
|
||||
blockerCount: 2,
|
||||
mode: "strategist",
|
||||
mode: "on",
|
||||
queueLength: 5,
|
||||
streakSuffix: "",
|
||||
});
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { readJsonBody, z } from "@/lib/api/route-helpers";
|
||||
import { readBeaconSession } from "@/app/api/beacon/route";
|
||||
import { updateBeaconChoice } from "@/db/queries/beacon-sessions";
|
||||
import { parseSessionText } from "@/lib/session-content";
|
||||
import { appendProjectDevLog } from "@/db/queries/user-projects";
|
||||
|
||||
const RespondBody = z.object({
|
||||
choice: z.string().min(1).max(2000),
|
||||
});
|
||||
|
||||
async function appendDevLog(projectName: string, content: string): Promise<void> {
|
||||
if (!content.trim()) return;
|
||||
const parsed = parseSessionText(content);
|
||||
if (!parsed.done.length && !parsed.next.length) return;
|
||||
|
||||
const userId = await getSessionUserId();
|
||||
if (!userId) return; // unauthenticated — skip logging, don't fail the beacon response
|
||||
await appendProjectDevLog(userId, projectName, {
|
||||
date: new Date().toISOString(),
|
||||
done: parsed.done.join("; "),
|
||||
next: parsed.next.join("; "),
|
||||
tests: parsed.tests,
|
||||
todos: parsed.todos,
|
||||
health: parsed.health || "good",
|
||||
});
|
||||
}
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const session = await readBeaconSession(id);
|
||||
if (!session) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
return NextResponse.json(session);
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const dataOrResp = await readJsonBody(req, RespondBody);
|
||||
if (dataOrResp instanceof NextResponse) return dataOrResp;
|
||||
|
||||
const updated = await updateBeaconChoice(id, dataOrResp.choice);
|
||||
if (!updated) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
// Persist session state to project dev log (fire-and-forget — never blocks the beacon response)
|
||||
appendDevLog(updated.project, updated.sessionContent).catch((err) => console.error("[beacon] devlog append failed:", err));
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { readJsonBody, z } from "@/lib/api/route-helpers";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { cancelActiveBeaconSessions } from "@/app/api/beacon/route";
|
||||
|
||||
const Body = z.object({ tab: z.string().max(200) });
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const userId = await getApiUserId();
|
||||
if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
const body = await readJsonBody(req, Body);
|
||||
if (body instanceof NextResponse) return body;
|
||||
await cancelActiveBeaconSessions(userId, body.tab);
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
// Beacon popup SSE — Change 4 (DB-backed).
|
||||
//
|
||||
// Pre-Change-4: scanned /tmp/<APP_SLUG>-beacon every 150ms for new JSON
|
||||
// files and pushed them as SSE frames. Now: queries the DB on the same
|
||||
// cadence and pushes only this user's pending sessions. Same protocol on
|
||||
// the wire, just durable + user-scoped storage underneath.
|
||||
//
|
||||
// Polling is preserved (vs LISTEN/NOTIFY push) to keep the diff small.
|
||||
// A v2 step adds a NOTIFY trigger on beacon_sessions; the bridge already
|
||||
// has the LISTEN plumbing, so the SSE here would degrade to a single
|
||||
// initial fetch + bus-driven pushes.
|
||||
|
||||
import { execSync } from "child_process";
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { parseProjectsConf } from "@/lib/agent-config";
|
||||
import { getDefaultUser } from "@/db/queries/users";
|
||||
import { getLatestPendingSession, type BeaconSession } from "@/db/queries/beacon-sessions";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const POLL_MS = 150;
|
||||
const KEEPALIVE_MS = 20_000;
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const sessionUserId = await getSessionUserId();
|
||||
const defaultUser = !sessionUserId && isRuntimeAvailable() ? await getDefaultUser() : null;
|
||||
const userId = sessionUserId ?? defaultUser?.id ?? null;
|
||||
if (!userId) {
|
||||
return new Response("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let keepaliveTimer: ReturnType<typeof setInterval> | null = null;
|
||||
// Track the last session id we've pushed so we don't replay it every
|
||||
// poll while the user is sitting on the popup.
|
||||
let lastPushedId: string | null = null;
|
||||
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const send = (chunk: string) => {
|
||||
if (closed) return;
|
||||
try {
|
||||
controller.enqueue(encoder.encode(chunk));
|
||||
} catch {
|
||||
closed = true;
|
||||
}
|
||||
};
|
||||
|
||||
send(": keepalive\n\n");
|
||||
|
||||
function enrichAndPush(session: BeaconSession) {
|
||||
// Enrich with git branch on local-runtime nodes so the popup
|
||||
// shows what branch the agent was operating on. Identical
|
||||
// logic to the pre-Change-4 file-based version.
|
||||
if (isRuntimeAvailable() && !session.gitBranch) {
|
||||
try {
|
||||
const projects = parseProjectsConf();
|
||||
const match = projects.find((p) => p.tab.toLowerCase() === session.project.toLowerCase());
|
||||
if (match) {
|
||||
session.gitBranch = execSync("git rev-parse --abbrev-ref HEAD", {
|
||||
cwd: match.dir, encoding: "utf-8", timeout: 2000,
|
||||
}).trim() || null;
|
||||
}
|
||||
} catch { /* not a git repo or dir missing */ }
|
||||
}
|
||||
send(`data: ${JSON.stringify(session)}\n\n`);
|
||||
lastPushedId = session.id;
|
||||
}
|
||||
|
||||
async function pollOnce() {
|
||||
if (closed) return;
|
||||
try {
|
||||
const session = await getLatestPendingSession(userId!);
|
||||
if (session && session.id !== lastPushedId) {
|
||||
enrichAndPush(session);
|
||||
}
|
||||
} catch {
|
||||
// DB error during this tick — keep the stream alive; next tick may succeed.
|
||||
}
|
||||
}
|
||||
|
||||
// Initial deliver: surface any pending row at connect time. void to
|
||||
// avoid blocking the readable-stream start() handler.
|
||||
void pollOnce();
|
||||
|
||||
pollTimer = setInterval(() => { void pollOnce(); }, POLL_MS);
|
||||
keepaliveTimer = setInterval(() => send(": keepalive\n\n"), KEEPALIVE_MS);
|
||||
},
|
||||
|
||||
cancel() {
|
||||
closed = true;
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
if (keepaliveTimer) clearInterval(keepaliveTimer);
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { spawnSync } from "child_process";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { APP_SLUG } from "@/config/brand";
|
||||
|
||||
// WM_CLASS the pre-warmed beacon window is launched with. Must match
|
||||
// scripts/fleetcrown-beacon-window.sh:BEACON_WM_CLASS (also derived from
|
||||
// APP_SLUG) and the same constant in window/show/route.ts.
|
||||
const BEACON_WM_CLASS = `${APP_SLUG}-beacon`;
|
||||
|
||||
/**
|
||||
* Hide the pre-warmed beacon window so the user never sees an empty "Standby"
|
||||
* placeholder. Called by BeaconLiveClient when there's no active session.
|
||||
*
|
||||
* Uses windowunmap (X11 invisibility). windowmove to negative coordinates
|
||||
* doesn't work under KDE Plasma Wayland — KWin clamps offscreen positions
|
||||
* back onto the visible screen. unmap is the only reliable hide on this stack.
|
||||
* The window stays alive in memory and SSE-connected; the next show endpoint
|
||||
* windowmaps it back.
|
||||
*/
|
||||
export async function POST() {
|
||||
if (!isRuntimeAvailable()) return NextResponse.json({ ok: false, reason: "no-runtime" }, { status: 503 });
|
||||
|
||||
// Match only the actual beacon app window — brave creates ~2 internal splash
|
||||
// subwindows tagged with the same WM_CLASS, but only the page window has a
|
||||
// "Beacon" title. Skipping the others avoids unmapping invisible splashes.
|
||||
const search = spawnSync(
|
||||
"xdotool",
|
||||
["search", "--class", BEACON_WM_CLASS, "--name", "Beacon"],
|
||||
{ timeout: 1500 },
|
||||
);
|
||||
if (search.status !== 0) {
|
||||
return NextResponse.json({ ok: false, reason: "xdotool-or-window-missing" });
|
||||
}
|
||||
const wids = search.stdout.toString().trim().split("\n").filter(Boolean);
|
||||
if (wids.length === 0) {
|
||||
return NextResponse.json({ ok: false, reason: "no-matching-window" });
|
||||
}
|
||||
|
||||
// Chain into one xdotool invocation — fork+exec is the dominant cost, so
|
||||
// batching cuts the hide latency from ~250ms to ~30ms.
|
||||
const args: string[] = [];
|
||||
for (const wid of wids) args.push("windowunmap", wid);
|
||||
spawnSync("xdotool", args, { timeout: 2000 });
|
||||
|
||||
return NextResponse.json({ ok: true, wids });
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { spawnSync } from "child_process";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { APP_SLUG } from "@/config/brand";
|
||||
|
||||
// WM_CLASS the pre-warmed beacon window is launched with. Must match
|
||||
// scripts/fleetcrown-beacon-window.sh:BEACON_WM_CLASS (also derived from
|
||||
// APP_SLUG) and the same constant in window/hide/route.ts.
|
||||
const BEACON_WM_CLASS = `${APP_SLUG}-beacon`;
|
||||
|
||||
/**
|
||||
* Show the pre-warmed beacon window — maps it, moves it on-screen, raises
|
||||
* and activates it. Called by BeaconLiveClient's useEffect when a session
|
||||
* becomes active.
|
||||
*
|
||||
* Targets the fleetcrown-beacon-window.service chromium instance specifically
|
||||
* via WM_CLASS=fleetcrown-beacon, so a user's regular browser tab at the same
|
||||
* URL is never moved. No-ops cleanly if xdotool isn't installed or if no
|
||||
* matching window exists.
|
||||
*
|
||||
* All xdotool operations are chained into a single process invocation:
|
||||
* spawning a fresh xdotool per command was costing ~1s wall-clock for the
|
||||
* full sequence — chained, the whole show takes ~50ms (PyQt-equivalent).
|
||||
*/
|
||||
|
||||
// Cache the primary screen width for the lifetime of the process. The screen
|
||||
// can change at runtime (monitor hot-plug), so re-resolve once an hour to
|
||||
// stay correct without paying the spawnSync cost on every show.
|
||||
let cachedScreenW = 0;
|
||||
let screenWAtMs = 0;
|
||||
function getScreenWidth(): number {
|
||||
if (Date.now() - screenWAtMs < 3_600_000 && cachedScreenW > 0) return cachedScreenW;
|
||||
const geo = spawnSync("xdotool", ["getdisplaygeometry"], { timeout: 1500 });
|
||||
const w = parseInt(geo.stdout.toString().trim().split(/\s+/)[0] || "1920", 10) || 1920;
|
||||
cachedScreenW = w;
|
||||
screenWAtMs = Date.now();
|
||||
return w;
|
||||
}
|
||||
|
||||
export async function POST() {
|
||||
if (!isRuntimeAvailable()) return NextResponse.json({ ok: false, reason: "no-runtime" }, { status: 503 });
|
||||
|
||||
// Match the actual /beacon/live app window only. `--class ${APP_SLUG}-beacon`
|
||||
// would also match brave's internal splash subwindows (typically 2–3 of them);
|
||||
// chaining windowmap --sync + windowactivate --sync across all of them was
|
||||
// costing ~3s on KDE Plasma Wayland because each --sync waits for KWin to
|
||||
// confirm.
|
||||
const search = spawnSync(
|
||||
"xdotool",
|
||||
["search", "--class", BEACON_WM_CLASS, "--name", "Beacon"],
|
||||
{ timeout: 1500 },
|
||||
);
|
||||
if (search.status !== 0) {
|
||||
return NextResponse.json({ ok: false, reason: "xdotool-or-window-missing" });
|
||||
}
|
||||
const wids = search.stdout.toString().trim().split("\n").filter(Boolean);
|
||||
if (wids.length === 0) {
|
||||
return NextResponse.json({ ok: false, reason: "no-matching-window" });
|
||||
}
|
||||
|
||||
const x = String(Math.max(0, getScreenWidth() - 600));
|
||||
|
||||
// Order matters: move BEFORE map. If the window is unmapped (hidden), moving
|
||||
// it is instant (~42ms) and the compositor fires no animation. Mapping a
|
||||
// pre-positioned window then takes ~0ms vs mapping-then-moving which triggers
|
||||
// a 150-200ms KWin compositor slide-in. Measured: old order ~380ms, new ~36ms.
|
||||
const args: string[] = [];
|
||||
for (const wid of wids) {
|
||||
args.push("windowmove", wid, x, "80");
|
||||
args.push("windowmap", wid);
|
||||
args.push("windowactivate", wid);
|
||||
args.push("windowraise", wid);
|
||||
}
|
||||
spawnSync("xdotool", args, { timeout: 2000 });
|
||||
|
||||
return NextResponse.json({ ok: true, wids });
|
||||
}
|
||||
@@ -1,28 +1,34 @@
|
||||
/**
|
||||
* POST /api/control/dispatch
|
||||
*
|
||||
* Strategist layer (v2, 2026-05-20): decides whether to drain the queue,
|
||||
* fire the canned next_best template, OR compose a context-aware prompt
|
||||
* body from session handoff + queue tail + recent commits + outcome
|
||||
* streak. The composed path is the answer to "the agent's auto-injected
|
||||
* prompts are dumb" — see content/thoughts/strategist-and-prompt-quality.md.
|
||||
* Tells the caller (Fleet Runner desktop, or any client that triggers on
|
||||
* status:ready) what to fire next when an agent reports done. After the
|
||||
* 2026-06-11 mode collapse (killing-the-bash-daemon, Session 3) this is a
|
||||
* thin decision layer:
|
||||
*
|
||||
* Returns quickly (< 1.5s on Groq free tier; composed bodies add latency
|
||||
* proportional to maxTokens). Falls back to QUEUE when Groq is unavailable.
|
||||
* off → action:off (autopilot disabled)
|
||||
* on → action:queue if queue non-empty, else action:nextbest
|
||||
*
|
||||
* Safety rails are layered on TOP of the mode (in evaluateDispatchGates):
|
||||
* status:working/blocked, pending blockers, no-op fuse, and the explicit
|
||||
* health/tests-failing gate here all short-circuit to action:off.
|
||||
*
|
||||
* The previous Groq composer ("strategist mode") was removed in the same
|
||||
* commit. It produced clever but inconsistent prompts on a path most users
|
||||
* never opted into; the queue + canned next_best path is what they actually
|
||||
* use. The composer can come back as an opt-in /control button if needed,
|
||||
* not as part of the auto-fire path.
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { readJsonBody, z } from "@/lib/api/route-helpers";
|
||||
import { callGroqText } from "@/lib/groq";
|
||||
import { getApiUserId } from "@/lib/session";
|
||||
import { logDebug } from "@/db/queries/debug-logs";
|
||||
import { getRecentOutcomes, type RecentOutcome } from "@/db/queries/orchestration-runs";
|
||||
import { getBeaconSettings } from "@/db/queries/beacon-settings";
|
||||
import { getProjectAutopilotOverride } from "@/db/queries/projects";
|
||||
import { DEFAULT_AUTO_INJECT_MODE } from "@/lib/constants/control";
|
||||
import { evaluateDispatchGates } from "@/lib/orchestration/dispatch-gates";
|
||||
import type { AutoInjectMode } from "@/config/beacon";
|
||||
import { getOrangeCatContext, renderOrangeCatContext } from "@/lib/integrations/orangecat-context";
|
||||
import { promptFingerprint, recordControlAuditEvent } from "@/db/queries/control-audit-events";
|
||||
|
||||
// Compact display: ✓ for success, ✗ for error/hang/timeout, ~ for partial, ✕ for user_abort.
|
||||
@@ -44,177 +50,36 @@ const HandoffSchema = z.object({
|
||||
health: z.string().default(""),
|
||||
tests: z.string().default(""),
|
||||
todos: z.string().default(""),
|
||||
/** Agent's self-reported lifecycle. "working" means the agent is mid-task and
|
||||
* the autopilot must NOT inject anything. "ready" means handoff is final and
|
||||
* the strategist may pick the next task. Empty string is legacy / unknown
|
||||
* (treated permissively as "ready" so existing behavior is preserved). */
|
||||
/** Agent's self-reported lifecycle. "working"/"blocked" → autopilot must
|
||||
* NOT inject. "ready" → autopilot may fire. Empty is legacy/unknown
|
||||
* (treated permissively as ready). */
|
||||
status: z.string().default(""),
|
||||
});
|
||||
|
||||
const DispatchBody = z.object({
|
||||
handoff: HandoffSchema,
|
||||
queue: z.array(z.string().trim().min(1)).max(20),
|
||||
/** Count of files in ~/.claude/sessions/<P>.blockers/pending/ as reported by
|
||||
* the local daemon. Any value > 0 short-circuits dispatch — a blocker file
|
||||
* is a human-action gate and autopilot has to wait until it clears. */
|
||||
/** Count of files in ~/.claude/sessions/<P>.blockers/pending/ as reported
|
||||
* by the caller. >0 short-circuits dispatch — human-action gate. */
|
||||
blockerCount: z.number().int().nonnegative().default(0),
|
||||
noOpCount: z.number().int().nonnegative().default(0),
|
||||
projectName: z.string().optional(),
|
||||
projectKey: z.string().optional(),
|
||||
gitBranch: z.string().optional(),
|
||||
recentCommits: z.array(z.string()).max(5).optional(),
|
||||
/** Project mission / charter from profile — fed to strategist so composed
|
||||
* next-best prompts are aware of the user's larger intent, not just the
|
||||
* immediate handoff. */
|
||||
mission: z.string().optional(),
|
||||
/** Optional context kept on the wire for audit/log purposes only — the
|
||||
* decision logic no longer reads these. Removed in the 2026-06-11
|
||||
* simplification: gitBranch, recentCommits, mission. The bash bridge
|
||||
* may still send them; they are silently ignored. */
|
||||
});
|
||||
|
||||
export type DispatchAction = "queue" | "nextbest" | "composed" | "off";
|
||||
export type DispatchAction = "queue" | "nextbest" | "off";
|
||||
|
||||
export type DispatchResult = {
|
||||
action: DispatchAction;
|
||||
reason: string;
|
||||
/** Which inference path produced the decision. */
|
||||
source: "groq" | "health_gate" | "empty_queue" | "fallback" | "mode_gate" | "status_gate" | "blocker_gate";
|
||||
/** Strategist-composed prompt body when action="composed". The caller
|
||||
* injects this as a custom prompt instead of firing the canned
|
||||
* next_best template. Absent for queue / nextbest / off paths. */
|
||||
prompt?: string;
|
||||
source: "health_gate" | "empty_queue" | "mode_gate" | "status_gate" | "blocker_gate";
|
||||
};
|
||||
|
||||
// ── Prompt construction ────────────────────────────────────────────────────
|
||||
|
||||
function buildPrompt(
|
||||
handoff: z.infer<typeof HandoffSchema>,
|
||||
queue: string[],
|
||||
projectName?: string,
|
||||
gitBranch?: string,
|
||||
recentCommits?: string[],
|
||||
recentOutcomes?: RecentOutcome[],
|
||||
mission?: string,
|
||||
orangeCatContext?: string,
|
||||
): string {
|
||||
const projectCtx = [
|
||||
projectName ? `Project: ${projectName}` : "",
|
||||
gitBranch ? `Branch: ${gitBranch}` : "",
|
||||
mission && mission.trim() ? `Mission: ${mission.trim()}` : "",
|
||||
].filter(Boolean).join(" | ");
|
||||
|
||||
// Strip leading hash so the model focuses on message content, not SHAs.
|
||||
// Raw format from GitState: "abc1234 2025-05-14: feat(x): add thing"
|
||||
const commitsSection = recentCommits && recentCommits.length > 0
|
||||
? `\nRecent commits (newest first):\n${recentCommits.slice(0, 3).map((c) => ` • ${c.replace(/^[0-9a-f]+ /, "")}`).join("\n")}\n`
|
||||
: "";
|
||||
|
||||
// Outcome streak — most recent first. ✓=success ~=partial ✗=error/hang ✕=user_abort.
|
||||
const outcomesSection = recentOutcomes && recentOutcomes.length > 0
|
||||
? `\nRecent run outcomes (most recent first): ${streakLine(recentOutcomes)}\n`
|
||||
: "";
|
||||
|
||||
// Commercial context from OrangeCat (services/products the actor lists),
|
||||
// surfaced so the strategist can prefer revenue-adjacent moves when handoff
|
||||
// signals are weak. Empty when no OC key configured or the actor has no
|
||||
// commercial state — strategist proceeds with FC-only context as before.
|
||||
const orangeCatSection = orangeCatContext ?? "";
|
||||
|
||||
const queueList = queue
|
||||
.slice(0, 5)
|
||||
.map((item, i) => `${i + 1}. ${item}`)
|
||||
.join("\n");
|
||||
const queueOverflow = queue.length > 5 ? `\n(+${queue.length - 5} more items)` : "";
|
||||
|
||||
return `You are a dispatch strategist for an AI coding agent workflow.
|
||||
${projectCtx ? `\n${projectCtx}\n` : ""}${commitsSection}${outcomesSection}${orangeCatSection}
|
||||
The agent just finished a work session. Handoff summary:
|
||||
done: ${handoff.done || "(none)"}
|
||||
next: ${handoff.next || "(none)"}
|
||||
health: ${handoff.health || "unknown"}
|
||||
tests: ${handoff.tests || "unknown"}
|
||||
todos: ${handoff.todos || "(none)"}
|
||||
|
||||
The queue has ${queue.length} pending task${queue.length === 1 ? "" : "s"}:
|
||||
${queueList}${queueOverflow}
|
||||
|
||||
Decide one of three actions:
|
||||
|
||||
1. ACTION: QUEUE — fire queue item 1 verbatim. Prefer when the first queue item is contextually related to what was just done, OR when health is good and there is no strong continuity signal.
|
||||
|
||||
2. ACTION: NEXTBEST — fire the canned next_best template (generic "verify health, fix typecheck, execute session next, find adjacent broken thing"). Only choose this when both queue and handoff.next are weak signals AND there's no specific direction emerging from commits/outcomes.
|
||||
|
||||
3. ACTION: COMPOSED — you write a fresh prompt body that names exactly what the agent should do right now, drawing on the handoff's "next", the queue tail, the last commit, the outcome streak, AND the project mission (if present). The composed body must stay aligned with the mission while executing the highest-impact immediate step. Prefer this when handoff.next is specific (e.g. "fix login flow", "ship migration 0011") or when a queue item plus commit history together point at one clear move. The body should sound like a teammate's next-step note — concrete verbs, named files or features where possible, ≤2000 characters.
|
||||
|
||||
Respond in this format (no extra text):
|
||||
|
||||
ACTION: <QUEUE | NEXTBEST | COMPOSED>
|
||||
REASON: one sentence on why this action is right now
|
||||
PROMPT: <only when ACTION is COMPOSED — the full prompt body the agent will receive. Omit this line otherwise.>`;
|
||||
}
|
||||
|
||||
// ── Groq call ─────────────────────────────────────────────────────────────
|
||||
|
||||
async function callGroq(prompt: string): Promise<{ action: DispatchAction; reason: string; prompt?: string }> {
|
||||
// maxTokens bumped from 100 → 1500 so the strategist has room for the
|
||||
// COMPOSED body (≤2000 chars ≈ ~500 tokens, plus 50 for ACTION + REASON
|
||||
// and a safety margin). Temperature stays low so the composer sticks to
|
||||
// the named context rather than improvising.
|
||||
const text = await callGroqText(prompt, { maxTokens: 1500, temperature: 0.2, timeoutMs: 15_000 });
|
||||
return parseGroqResponse(text);
|
||||
}
|
||||
|
||||
function parseGroqResponse(text: string): { action: DispatchAction; reason: string; prompt?: string } {
|
||||
const lines = text.split("\n");
|
||||
|
||||
let action: DispatchAction = "queue";
|
||||
let reason = "Continuing with queue order.";
|
||||
let promptBody: string | undefined;
|
||||
// Collecting the PROMPT: body across multiple lines (it can be a paragraph).
|
||||
let inPrompt = false;
|
||||
const promptLines: string[] = [];
|
||||
|
||||
for (const rawLine of lines) {
|
||||
const line = rawLine.trim();
|
||||
if (!line && !inPrompt) continue;
|
||||
|
||||
const upper = line.toUpperCase();
|
||||
if (upper.startsWith("ACTION:")) {
|
||||
const val = upper.replace("ACTION:", "").trim();
|
||||
if (val === "NEXTBEST") action = "nextbest";
|
||||
else if (val === "COMPOSED") action = "composed";
|
||||
else action = "queue";
|
||||
inPrompt = false;
|
||||
continue;
|
||||
}
|
||||
if (line.toLowerCase().startsWith("reason:")) {
|
||||
reason = line.slice("reason:".length).trim();
|
||||
inPrompt = false;
|
||||
continue;
|
||||
}
|
||||
if (line.toLowerCase().startsWith("prompt:")) {
|
||||
promptLines.push(line.slice("prompt:".length).trim());
|
||||
inPrompt = true;
|
||||
continue;
|
||||
}
|
||||
if (inPrompt) {
|
||||
// Continuation of multi-line PROMPT body.
|
||||
promptLines.push(rawLine);
|
||||
}
|
||||
}
|
||||
|
||||
if (promptLines.length > 0) {
|
||||
promptBody = promptLines.join("\n").trim();
|
||||
}
|
||||
|
||||
// Sanity: if Groq said COMPOSED but didn't actually emit a body, downgrade
|
||||
// to NEXTBEST so the caller doesn't dispatch an empty custom prompt.
|
||||
if (action === "composed" && (!promptBody || promptBody.length < 10)) {
|
||||
action = "nextbest";
|
||||
promptBody = undefined;
|
||||
}
|
||||
|
||||
return { action, reason, prompt: promptBody };
|
||||
}
|
||||
|
||||
// ── Route handler ──────────────────────────────────────────────────────────
|
||||
// ── Route handler ─────────────────────────────────────────────────────────
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const userId = await getApiUserId();
|
||||
@@ -223,10 +88,8 @@ export async function POST(req: NextRequest) {
|
||||
const dataOrResp = await readJsonBody(req, DispatchBody);
|
||||
if (dataOrResp instanceof NextResponse) return dataOrResp;
|
||||
|
||||
const { handoff, queue, blockerCount, noOpCount, projectName, projectKey, gitBranch, recentCommits, mission } = dataOrResp;
|
||||
const { handoff, queue, blockerCount, noOpCount, projectName, projectKey } = dataOrResp;
|
||||
|
||||
// Recent outcomes for this project — feeds Groq and is surfaced in the reason.
|
||||
// Safe-defaults: if the lookup fails, dispatch still proceeds.
|
||||
let recentOutcomes: RecentOutcome[] = [];
|
||||
if (projectKey) {
|
||||
recentOutcomes = await getRecentOutcomes(userId, projectKey, { limit: 5 }).catch(() => []);
|
||||
@@ -234,17 +97,8 @@ export async function POST(req: NextRequest) {
|
||||
const streak = streakLine(recentOutcomes);
|
||||
const streakSuffix = streak ? ` [last 5: ${streak}]` : "";
|
||||
|
||||
// Auto-inject mode resolution (per-project override → user default):
|
||||
//
|
||||
// Pre-v0.7: a single user-level mode applied to every project; users
|
||||
// dogfooding multi-project workflows asked for per-project pause/resume.
|
||||
// Now each entities row carries an optional auto_inject_mode_override —
|
||||
// when set, it wins; when null, fall back to the user's beacon_settings
|
||||
// value. This is also how the "pause this project's autopilot" UI on
|
||||
// ProjectCard does its work (it writes "off" to the override).
|
||||
//
|
||||
// Both the project override lookup and the user-settings lookup fail-safe
|
||||
// to the default mode so a transient DB hiccup doesn't kill dispatch.
|
||||
// Per-project override wins over user-level setting. Either lookup
|
||||
// fail-safes to the default so a transient DB hiccup doesn't kill dispatch.
|
||||
const settings = await getBeaconSettings(userId).catch(() => null);
|
||||
const userMode = (settings?.auto_inject_mode ?? DEFAULT_AUTO_INJECT_MODE) as AutoInjectMode;
|
||||
let mode: AutoInjectMode = userMode;
|
||||
@@ -254,7 +108,7 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
const recordAndReturn = (result: DispatchResult) => {
|
||||
const fingerprint = promptFingerprint(result.prompt);
|
||||
const fingerprint = promptFingerprint(undefined);
|
||||
recordControlAuditEvent({
|
||||
userId,
|
||||
projectKey: projectKey ?? projectName ?? null,
|
||||
@@ -275,33 +129,15 @@ export async function POST(req: NextRequest) {
|
||||
meta: {
|
||||
tests: handoff.tests,
|
||||
todos: handoff.todos,
|
||||
hasMission: Boolean(mission?.trim()),
|
||||
recentCommits: recentCommits?.slice(0, 5) ?? [],
|
||||
streak,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(result satisfies DispatchResult);
|
||||
};
|
||||
|
||||
const gated = evaluateDispatchGates({
|
||||
status: handoff.status,
|
||||
blockerCount,
|
||||
mode,
|
||||
queueLength: queue.length,
|
||||
streakSuffix,
|
||||
noOpCount,
|
||||
});
|
||||
if (gated) return recordAndReturn(gated);
|
||||
|
||||
// mode === "strategist" — fall through to Groq composition.
|
||||
|
||||
// No queue items + strategist mode: still call Groq to compose from
|
||||
// handoff + commits + outcomes. The strategist's value is highest
|
||||
// exactly when the queue is empty and the user wants a smart nudge.
|
||||
// (Previously this short-circuited to nextbest, which was the bug
|
||||
// Cursor's audit named.)
|
||||
|
||||
// Hard health gate (duplicate of client-side check — defence in depth).
|
||||
// Hard health gate — defence in depth. If health is critical or tests are
|
||||
// failing, force the agent into recovery (next_best canned template) so
|
||||
// it stays focused on fixing what's broken instead of switching concerns.
|
||||
const health = handoff.health.toLowerCase();
|
||||
const tests = handoff.tests.toLowerCase();
|
||||
if (health.includes("critical") || tests.includes("fail")) {
|
||||
@@ -312,50 +148,17 @@ export async function POST(req: NextRequest) {
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch the actor's commercial state from OrangeCat in parallel with
|
||||
// anything else that might run before Groq. The fetcher caches 5min and
|
||||
// races a 1.5s timeout, so this never delays the strategist by more than
|
||||
// the OC API's quickest response. Returns null silently when no
|
||||
// ORANGECAT_API_KEY is configured.
|
||||
const orangeCatContext = await getOrangeCatContext()
|
||||
.then(renderOrangeCatContext)
|
||||
.catch(() => "");
|
||||
|
||||
// Groq composition. Even with an empty queue, the strategist composes
|
||||
// from session next, recent commits, and outcome streak.
|
||||
const prompt = buildPrompt(handoff, queue, projectName, gitBranch, recentCommits, recentOutcomes, mission, orangeCatContext);
|
||||
|
||||
try {
|
||||
const { action, reason, prompt: composedPrompt } = await callGroq(prompt);
|
||||
return recordAndReturn({
|
||||
action,
|
||||
reason: `${reason}${streakSuffix}`,
|
||||
source: "groq",
|
||||
...(composedPrompt ? { prompt: composedPrompt } : {}),
|
||||
});
|
||||
} catch (e) {
|
||||
// Groq unavailable, key invalid, or timeout — surface the actual cause so
|
||||
// the user knows whether to top up credits / rotate the key / wait it out.
|
||||
// Without this the UI just said "Groq unavailable" with no hint to action.
|
||||
const raw = e instanceof Error ? e.message : String(e);
|
||||
const hint = /\b401\b|invalid.api.key/i.test(raw) ? "key invalid"
|
||||
: /\b429\b/.test(raw) ? "rate-limited"
|
||||
: /\b5\d\d\b/.test(raw) ? "Groq server error"
|
||||
: /timeout|abort/i.test(raw) ? "Groq timed out"
|
||||
: raw;
|
||||
console.error("[dispatch] groq fallback:", raw);
|
||||
logDebug({
|
||||
source: "api/control/dispatch",
|
||||
level: "warn",
|
||||
message: `Groq fallback (${hint}): ${raw}`,
|
||||
meta: { userId, projectKey, hint, queueLen: queue.length },
|
||||
});
|
||||
return recordAndReturn({
|
||||
action: queue.length > 0 ? "queue" : "nextbest",
|
||||
reason: queue.length > 0
|
||||
? `Groq unavailable (${hint}) — using queue order.${streakSuffix}`
|
||||
: `Groq unavailable (${hint}) — falling back to next_best.${streakSuffix}`,
|
||||
source: "fallback",
|
||||
});
|
||||
}
|
||||
// Mode + safety gates produce the actual decision. Always returns a
|
||||
// DispatchResult now that strategist composition is gone.
|
||||
const decision = evaluateDispatchGates({
|
||||
status: handoff.status,
|
||||
blockerCount,
|
||||
mode,
|
||||
queueLength: queue.length,
|
||||
streakSuffix,
|
||||
noOpCount,
|
||||
});
|
||||
// evaluateDispatchGates never returns null after the collapse — it owns
|
||||
// the off/on decision completely. The non-null assertion is safe.
|
||||
return recordAndReturn(decision!);
|
||||
}
|
||||
@@ -1,513 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useCallback, useRef } from "react";
|
||||
import {
|
||||
Loader2, Check, ExternalLink, Repeat2, GitBranch,
|
||||
} from "lucide-react";
|
||||
import { useMicComposer } from "@/hooks/use-mic-composer";
|
||||
import { usePromptQueue } from "@/hooks/use-prompt-queue";
|
||||
import { useAutoContinue } from "@/hooks/use-auto-continue";
|
||||
import { useAutomationPolicy } from "@/hooks/use-automation-policy";
|
||||
import { PromptInput } from "@/components/control/prompt-input";
|
||||
import { QueueList } from "@/components/control/queue-list";
|
||||
import { ProjectPromptLibrary } from "@/components/control/ProjectPromptLibrary";
|
||||
import { ReadyBanner } from "@/components/control/ready-banner";
|
||||
import { buildSessionHandoffFromBeaconSession, SessionHandoff } from "@/components/control/SessionHandoff";
|
||||
import { getJson, patchJson, postJson } from "@/lib/api/fetch";
|
||||
import { PROMPT_STYLE, CUSTOM_CHOICE_PREFIX, SWITCH_CHOICE_PREFIX } from "@/lib/constants/control";
|
||||
import { parseSessionText } from "@/lib/session-content";
|
||||
import { beaconComposingKey } from "@/lib/control-storage";
|
||||
import { getAdapterLabel } from "@/config/control-intents";
|
||||
import type { BeaconSession } from "@/app/api/beacon/route";
|
||||
import type { AgentPrompt } from "@/app/api/prompts/agent/route";
|
||||
import type { RecentCustomPrompt } from "@/db/queries/prompt-history";
|
||||
import type { DispatchResult } from "@/app/api/control/dispatch/route";
|
||||
|
||||
function agentLabel(agent: string | null | undefined): string {
|
||||
return agent ? getAdapterLabel(agent) : "agent";
|
||||
}
|
||||
|
||||
function SessionSummary({ content }: { content: string }) {
|
||||
if (!content.trim()) return null;
|
||||
return (
|
||||
<SessionHandoff
|
||||
data={buildSessionHandoffFromBeaconSession(parseSessionText(content))}
|
||||
surface="panel"
|
||||
microLabels
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── BeaconBody ─────────────────────────────────────────────────────────────
|
||||
|
||||
function BeaconBody({
|
||||
session,
|
||||
prompts,
|
||||
onSubmitted,
|
||||
onClose,
|
||||
}: {
|
||||
session: BeaconSession;
|
||||
prompts: AgentPrompt[];
|
||||
onSubmitted: (label: string) => void;
|
||||
onClose?: () => void;
|
||||
}) {
|
||||
const { queue, enqueue, remove, reorder, edit } = usePromptQueue(session.project);
|
||||
const { enabled: autoContinueEnabled, toggle: toggleAutoContinue } = useAutoContinue(session.project);
|
||||
const { mode: automationMode } = useAutomationPolicy();
|
||||
const [custom, setCustom] = useState("");
|
||||
const [inputFocused, setInputFocused] = useState(false);
|
||||
const [libraryOpen, setLibraryOpen] = useState(false);
|
||||
const [recentPrompts, setRecentPrompts] = useState<RecentCustomPrompt[]>([]);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const promptsRef = useRef<AgentPrompt[]>([]);
|
||||
const submitRef = useRef<(choice: string) => Promise<boolean>>(async () => false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => { promptsRef.current = prompts; }, [prompts]);
|
||||
|
||||
const { listening, processing, micError, toggleMic, waveformBars, recordingSeconds, maxRecordingSeconds, wrapSend, wrapEnqueue } = useMicComposer({
|
||||
custom,
|
||||
onAppend: (newText) => { setCustom(newText); inputRef.current?.focus(); },
|
||||
onSendAfterRecording: (text) => submitRef.current(`${CUSTOM_CHOICE_PREFIX}${text}`),
|
||||
onEnqueueAfterRecording: enqueue,
|
||||
});
|
||||
|
||||
const isComposing = custom.trim().length > 0 || inputFocused || listening || processing;
|
||||
|
||||
// Mirror composing state to localStorage so ReadyBanner's auto-fire respects it cross-window.
|
||||
useEffect(() => {
|
||||
try {
|
||||
if (isComposing) {
|
||||
localStorage.setItem(beaconComposingKey(session.project), "1");
|
||||
} else {
|
||||
localStorage.removeItem(beaconComposingKey(session.project));
|
||||
}
|
||||
} catch {}
|
||||
return () => {
|
||||
try { localStorage.removeItem(beaconComposingKey(session.project)); } catch {}
|
||||
};
|
||||
}, [isComposing, session.project]);
|
||||
|
||||
useEffect(() => {
|
||||
getJson<RecentCustomPrompt[]>(`/api/beacon/recent?project=${encodeURIComponent(session.project)}`)
|
||||
.then(setRecentPrompts)
|
||||
.catch(() => {});
|
||||
}, [session.project]);
|
||||
|
||||
// Resize the popup window to fit content after layout settles.
|
||||
useEffect(() => {
|
||||
if (prompts.length === 0) return;
|
||||
const t = setTimeout(() => {
|
||||
const h = Math.min(document.documentElement.scrollHeight + 2, 900);
|
||||
try {
|
||||
const right = window.screenLeft + window.outerWidth;
|
||||
const bottom = window.screenTop + window.outerHeight;
|
||||
window.resizeTo(520, h);
|
||||
window.moveTo(right - 520, Math.max(bottom - h, 16));
|
||||
} catch { /* blocked in non-popup windows */ }
|
||||
}, 120);
|
||||
return () => clearTimeout(t);
|
||||
}, [prompts.length, queue.length, recentPrompts.length]);
|
||||
|
||||
const dismiss = useCallback(() => { if (onClose) onClose(); else window.close(); }, [onClose]);
|
||||
|
||||
const submit = useCallback(async (choice: string): Promise<boolean> => {
|
||||
const all = promptsRef.current;
|
||||
let label = "";
|
||||
if (choice.startsWith(CUSTOM_CHOICE_PREFIX)) {
|
||||
label = choice.slice(CUSTOM_CHOICE_PREFIX.length).trim();
|
||||
} else if (choice.startsWith(SWITCH_CHOICE_PREFIX)) {
|
||||
label = `Switch to ${agentLabel(choice.slice(SWITCH_CHOICE_PREFIX.length))}`;
|
||||
} else {
|
||||
const slot = parseInt(choice);
|
||||
const matched = all.find((p) => p.slot === slot) ?? all.find((p) => p.key === choice);
|
||||
label = matched ? `${matched.icon} ${matched.label}` : choice;
|
||||
}
|
||||
setSubmitError(null);
|
||||
try {
|
||||
const response = await patchJson(`/api/beacon/${session.id}`, { choice });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
onSubmitted(label);
|
||||
setTimeout(() => dismiss(), 400);
|
||||
return true;
|
||||
} catch {
|
||||
setSubmitError("Could not send your instruction. It is still available to retry.");
|
||||
return false;
|
||||
}
|
||||
}, [session.id, onSubmitted, dismiss]);
|
||||
|
||||
useEffect(() => { submitRef.current = submit; }, [submit]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (document.activeElement === inputRef.current) return;
|
||||
if (e.key === "Escape") { dismiss(); return; }
|
||||
const n = parseInt(e.key);
|
||||
if (!isNaN(n) && n >= 1 && n <= 9) {
|
||||
const all = [
|
||||
...promptsRef.current.filter((p) => p.style === "primary"),
|
||||
...promptsRef.current.filter((p) => p.style === "action"),
|
||||
];
|
||||
const target = all.find((p) => p.slot === n) ?? all[n - 1];
|
||||
if (target) submitRef.current(String(target.slot ?? target.key));
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [dismiss]);
|
||||
|
||||
const handleSendCustom = () => wrapSend(() => {
|
||||
if (!custom.trim()) return;
|
||||
submit(`${CUSTOM_CHOICE_PREFIX}${custom.trim()}`);
|
||||
setCustom("");
|
||||
});
|
||||
|
||||
const handleEnqueue = () => wrapEnqueue(() => {
|
||||
if (!custom.trim()) return;
|
||||
enqueue(custom.trim());
|
||||
setCustom("");
|
||||
});
|
||||
|
||||
// Auto-fire logic: picks the right choice based on queue / capacity issue state.
|
||||
// Called by ReadyBanner when the countdown reaches zero (and auto-continue is on).
|
||||
//
|
||||
// Agent-driven gate: handoff.status must say "ready" before any auto-fire
|
||||
// happens. Anything else (empty, "working", any other value) suppresses.
|
||||
// Model-agnostic — any adapter that writes the standard handoff fields
|
||||
// gets the same gating. Capacity-issue (agent quota hit) bypasses since
|
||||
// that's a recovery dispatch the user explicitly asked for.
|
||||
const automaticContinuationEnabled = autoContinueEnabled && (
|
||||
automationMode === "strategist" ||
|
||||
automationMode === "next_best" ||
|
||||
(automationMode === "queue_only" && queue.length > 0)
|
||||
);
|
||||
const queuePolicyWaiting = automationMode === "queue_only" && autoContinueEnabled && queue.length === 0;
|
||||
|
||||
const handleAutoInject = useCallback(async () => {
|
||||
if (!automaticContinuationEnabled) return;
|
||||
// Beacon mode is handled by the stop hook; strategist paths only here.
|
||||
// BeaconSession carries raw sessionContent — parse it here to extract
|
||||
// the handoff status. Capacity-issue dispatches bypass since the user
|
||||
// explicitly asked for the agent switch.
|
||||
const handoff = parseSessionText(session.sessionContent);
|
||||
const status = (handoff.status ?? "").toLowerCase();
|
||||
if (status !== "ready" && !session.capacityIssue) return;
|
||||
const all = promptsRef.current;
|
||||
const primary = all.find((p) => p.style === "primary");
|
||||
let removesQueueHead = false;
|
||||
let choice = session.capacityIssue && session.nextAgent
|
||||
? `${SWITCH_CHOICE_PREFIX}${session.nextAgent}`
|
||||
: queue.length > 0
|
||||
? `${CUSTOM_CHOICE_PREFIX}${queue[0]}`
|
||||
: primary ? primary.key : "next_best";
|
||||
|
||||
if (!session.capacityIssue) {
|
||||
const response = await postJson("/api/control/dispatch", {
|
||||
handoff: {
|
||||
done: handoff.done ?? "",
|
||||
next: handoff.next ?? "",
|
||||
health: handoff.health ?? "",
|
||||
tests: handoff.tests ?? "",
|
||||
todos: handoff.todos ?? "",
|
||||
status: handoff.status ?? "",
|
||||
},
|
||||
noOpCount: handoff.noOpCount ?? 0,
|
||||
blockerCount: 0,
|
||||
queue,
|
||||
projectName: session.project,
|
||||
projectKey: session.project,
|
||||
}).catch(() => null);
|
||||
if (response?.ok) {
|
||||
const decision = await response.json() as DispatchResult;
|
||||
if (decision.action === "off") return;
|
||||
if (decision.action === "composed" && decision.prompt) {
|
||||
choice = `${CUSTOM_CHOICE_PREFIX}${decision.prompt}`;
|
||||
} else if (decision.action === "queue" && queue[0]) {
|
||||
choice = `${CUSTOM_CHOICE_PREFIX}${queue[0]}`;
|
||||
removesQueueHead = true;
|
||||
} else {
|
||||
choice = primary ? primary.key : "next_best";
|
||||
}
|
||||
} else if (queue.length > 0) {
|
||||
removesQueueHead = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (await submitRef.current(choice) && removesQueueHead) remove(0);
|
||||
}, [automaticContinuationEnabled, session.sessionContent, session.capacityIssue, session.nextAgent, session.project, queue, remove]);
|
||||
|
||||
const morePrompts = prompts.filter((p) => p.style === "more");
|
||||
|
||||
const statusLabel = micError
|
||||
? micError
|
||||
: listening
|
||||
? "Recording - paused"
|
||||
: processing
|
||||
? "Transcribing..."
|
||||
: custom.trim()
|
||||
? "Enter sends · Alt+Enter queues"
|
||||
: inputFocused
|
||||
? "Focused - paused"
|
||||
: automationMode === "off"
|
||||
? "Manual mode - waiting for your instruction"
|
||||
: !autoContinueEnabled
|
||||
? "Automatic continuation paused for this project"
|
||||
: queuePolicyWaiting
|
||||
? "Continue queued work - add an instruction to the queue"
|
||||
: session.capacityIssue && session.nextAgent
|
||||
? `Switching to ${agentLabel(session.nextAgent)}`
|
||||
: queue.length > 0
|
||||
? `"${queue[0].length > 30 ? queue[0].slice(0, 28) + "…" : queue[0]}" queued`
|
||||
: "Auto-continue ready";
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{session.sessionContent && <SessionSummary content={session.sessionContent} />}
|
||||
|
||||
{queue.length > 0 && (
|
||||
<QueueList
|
||||
queue={queue}
|
||||
onSend={async (i) => { if (await submit(`${CUSTOM_CHOICE_PREFIX}${queue[i]}`)) remove(i); }}
|
||||
onRemove={remove}
|
||||
onReorder={reorder}
|
||||
onEdit={edit}
|
||||
/>
|
||||
)}
|
||||
|
||||
{session.nextAgent && (
|
||||
<div className={session.capacityIssue ? "ui-panel rounded-xl border-status-warning/40 p-3" : "ui-panel rounded-xl p-3"}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className={session.capacityIssue ? "ui-tag ui-tag-warning" : "ui-tag ui-tag-neutral"}>
|
||||
{session.capacityIssue ? "capacity issue" : "fallback ready"}
|
||||
</span>
|
||||
<span className="text-sm text-text-secondary">
|
||||
{agentLabel(session.currentAgent)} → {agentLabel(session.nextAgent)}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => submit(`${SWITCH_CHOICE_PREFIX}${session.nextAgent}`)}
|
||||
className="ui-btn-secondary mt-3 w-full justify-start gap-2"
|
||||
>
|
||||
<Repeat2 className="h-4 w-4" />
|
||||
Switch to {agentLabel(session.nextAgent)} and continue
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{submitError && <p className="ui-box-error text-sm">{submitError}</p>}
|
||||
|
||||
{/* ReadyBanner is the SSOT for the countdown, auto-continue toggle, and primary/action buttons. */}
|
||||
{prompts.length > 0 && (
|
||||
<ReadyBanner
|
||||
tab={session.project}
|
||||
prompts={prompts}
|
||||
onSend={(key) => submit(key)}
|
||||
onDismiss={dismiss}
|
||||
onAutoInject={handleAutoInject}
|
||||
autoContinueEnabled={automaticContinuationEnabled}
|
||||
onToggleAutoContinue={automationMode === "off" || queuePolicyWaiting ? undefined : toggleAutoContinue}
|
||||
paused={isComposing}
|
||||
nextQueueItem={queue.length > 0 ? queue[0] : undefined}
|
||||
queueTotal={queue.length}
|
||||
title="Agent ready"
|
||||
inactiveLabel={queuePolicyWaiting ? "Queue empty" : undefined}
|
||||
countdownSeconds={session.countdownSeconds}
|
||||
/>
|
||||
)}
|
||||
|
||||
{morePrompts.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 px-5">
|
||||
{morePrompts.map((p) => (
|
||||
<button key={p.key} onClick={() => submit(String(p.slot ?? p.key))} className={PROMPT_STYLE.more}>
|
||||
{p.icon} {p.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<PromptInput
|
||||
custom={custom}
|
||||
listening={listening}
|
||||
processing={processing}
|
||||
micError={micError}
|
||||
sending={null}
|
||||
placeholder="Custom prompt…"
|
||||
showQueue
|
||||
waveformBars={waveformBars}
|
||||
recordingSeconds={recordingSeconds}
|
||||
maxRecordingSeconds={maxRecordingSeconds}
|
||||
autoContinueEnabled={automationMode === "off" ? false : autoContinueEnabled}
|
||||
statusLabel={statusLabel}
|
||||
textareaRef={inputRef}
|
||||
onCustomChange={setCustom}
|
||||
onCustomFocusChange={setInputFocused}
|
||||
onSendCustom={handleSendCustom}
|
||||
onEnqueue={handleEnqueue}
|
||||
onToggleAutoContinue={automationMode === "off" ? undefined : toggleAutoContinue}
|
||||
toggleMic={toggleMic}
|
||||
/>
|
||||
|
||||
{recentPrompts.length > 0 && (
|
||||
<div className="space-y-1.5 px-5">
|
||||
<p className="ui-kicker">Reuse recent prompts</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{recentPrompts
|
||||
.filter((r) => {
|
||||
const t = r.customPrompt.toLowerCase();
|
||||
if (t.startsWith("setup (run, read outputs)")) return false;
|
||||
if (t.includes("picked ") && t.includes(" (t")) return false;
|
||||
return true;
|
||||
})
|
||||
.map((r) => (
|
||||
<button
|
||||
key={r.customPrompt}
|
||||
onClick={() => setCustom(r.customPrompt)}
|
||||
title={r.customPrompt}
|
||||
className="ui-chip-truncate-label"
|
||||
>
|
||||
{r.count > 1 && <span className="mr-1.5">used {r.count}×</span>}
|
||||
{r.customPrompt.length > 60 ? r.customPrompt.slice(0, 60) + "…" : r.customPrompt}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ProjectPromptLibrary
|
||||
projectName={session.project}
|
||||
open={libraryOpen}
|
||||
onOpenChange={setLibraryOpen}
|
||||
// Universal fill-first rule (2026-05-31): library picks fill the
|
||||
// composer textarea so the user previews/edits before sending.
|
||||
// Was: submit(CUSTOM_CHOICE_PREFIX + prompt) which silently sent the
|
||||
// same click that would have FILLED the textarea on /control.
|
||||
onSelect={(prompt) => { setCustom(prompt); inputRef.current?.focus(); }}
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── BeaconPageClient ────────────────────────────────────────────────────────
|
||||
// Receives initialSession from the server component. Prompts are still fetched
|
||||
// client-side (they require auth); if the fetch fails they remain empty and
|
||||
// auto-continue is disabled until prompts load.
|
||||
|
||||
export function BeaconPageClient({
|
||||
initialSession,
|
||||
onClose,
|
||||
}: {
|
||||
initialSession: BeaconSession;
|
||||
onClose?: () => void;
|
||||
}) {
|
||||
const session = initialSession;
|
||||
const [prompts, setPrompts] = useState<AgentPrompt[]>([]);
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
const [submittedLabel, setSubmittedLabel] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
getJson<AgentPrompt[]>("/api/prompts/agent").then(setPrompts).catch(() => {});
|
||||
}, []);
|
||||
|
||||
// Poll every 500ms to close/reset if another client already injected a choice.
|
||||
useEffect(() => {
|
||||
if (submitted) return;
|
||||
const interval = setInterval(async () => {
|
||||
try {
|
||||
const data = await getJson<BeaconSession>(`/api/beacon/${session.id}`);
|
||||
if (data.choice !== null) { if (onClose) { onClose(); } else { window.close(); } }
|
||||
} catch { /* network error or 401 — ignore */ }
|
||||
}, 500);
|
||||
return () => clearInterval(interval);
|
||||
}, [session.id, submitted, onClose]);
|
||||
|
||||
if (submitted) {
|
||||
return (
|
||||
<div className="min-h-screen bg-surface-base p-4 sm:p-5">
|
||||
<div className="ui-card-header mb-0">
|
||||
<div className="ui-card-header-main flex items-center gap-2.5">
|
||||
<span className="block h-2.5 w-2.5 shrink-0 rounded-full border border-status-positive bg-status-positive" />
|
||||
<span className="text-sm font-semibold text-text-primary">{session.project}</span>
|
||||
<span className="ui-tag ui-tag-positive">dispatched</span>
|
||||
</div>
|
||||
<div className="ui-card-actions">
|
||||
<button
|
||||
onClick={() => window.open(`${window.location.origin}/control`, "_blank")}
|
||||
className="ui-icon-action"
|
||||
title="Open Control panel"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 border-t border-border-subtle pt-4 space-y-3">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-status-positive/15">
|
||||
<Check className="h-4 w-4 text-status-positive" />
|
||||
</div>
|
||||
<p className="text-sm font-medium text-text-primary">{submittedLabel || "Agent running…"}</p>
|
||||
</div>
|
||||
<p className="text-xs text-text-tertiary">
|
||||
Watch progress in the Control panel — this window will close shortly.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-surface-base p-4 sm:p-5">
|
||||
<div className="ui-card-header">
|
||||
<div className="ui-card-header-main">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<span className="block h-2.5 w-2.5 shrink-0 rounded-full border border-status-positive bg-status-positive" />
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="truncate text-sm font-semibold text-text-primary">{session.project}</span>
|
||||
<span className="ui-tag ui-tag-positive">Ready</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ui-control-card-header-meta mt-2">
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full border border-border-subtle bg-surface-raised px-2.5 py-1 text-xs text-text-tertiary">
|
||||
{getAdapterLabel(session.currentAgent ?? "claude")} ready
|
||||
</span>
|
||||
{session.gitBranch && (
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full border border-border-subtle bg-surface-raised px-2.5 py-1 text-xs text-text-tertiary">
|
||||
<GitBranch className="h-3 w-3 shrink-0" />
|
||||
{session.gitBranch}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ui-card-actions shrink-0 self-start">
|
||||
<button
|
||||
onClick={() => window.open(`${window.location.origin}/control`, "_blank")}
|
||||
className="ui-icon-action"
|
||||
title="Open Control panel"
|
||||
>
|
||||
<ExternalLink className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border-subtle pt-4">
|
||||
<BeaconBody
|
||||
session={session}
|
||||
prompts={prompts}
|
||||
onSubmitted={(label) => { setSubmitted(true); setSubmittedLabel(label); }}
|
||||
onClose={onClose}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Loading state used while the server reads the session.
|
||||
export function BeaconLoading() {
|
||||
return (
|
||||
<div className="flex h-64 items-center justify-center bg-surface-base">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-text-muted" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { execSync } from "child_process";
|
||||
import { readBeaconSession } from "@/app/api/beacon/route";
|
||||
import { BeaconPageClient, BeaconLoading } from "./BeaconClient";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { parseProjectsConf } from "@/lib/agent-config";
|
||||
|
||||
// Reads the beacon session from the filesystem on the server, so the initial
|
||||
// page render includes the full session content without any client-side API call.
|
||||
export default async function BeaconPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const session = await readBeaconSession(id);
|
||||
|
||||
if (!session) {
|
||||
return <BeaconLoading />;
|
||||
}
|
||||
|
||||
// Enrich with git branch when running locally — server has filesystem access.
|
||||
let gitBranch: string | null = null;
|
||||
if (isRuntimeAvailable() && !session.gitBranch) {
|
||||
try {
|
||||
const projects = parseProjectsConf();
|
||||
const match = projects.find((p) => p.tab.toLowerCase() === session.project.toLowerCase());
|
||||
if (match) {
|
||||
gitBranch = execSync("git rev-parse --abbrev-ref HEAD", {
|
||||
cwd: match.dir,
|
||||
encoding: "utf-8",
|
||||
timeout: 2000,
|
||||
}).trim() || null;
|
||||
}
|
||||
} catch { /* not a git repo or dir not found */ }
|
||||
}
|
||||
|
||||
return <BeaconPageClient initialSession={{ ...session, gitBranch: session.gitBranch ?? gitBranch }} />;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
export const metadata: Metadata = { title: "Beacon" };
|
||||
export default function BeaconLayout({ children }: { children: React.ReactNode }) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { ArrowRight } from "lucide-react";
|
||||
import type { BeaconSession } from "@/app/api/beacon/route";
|
||||
import { BeaconPageClient } from "@/app/beacon/[id]/BeaconClient";
|
||||
import { APP_NAME } from "@/config/brand";
|
||||
import { NAV } from "@/config/navigation";
|
||||
|
||||
export function BeaconLiveClient({ initialSession = null }: { initialSession?: BeaconSession | null }) {
|
||||
const [session, setSession] = useState<BeaconSession | null>(initialSession);
|
||||
const esRef = useRef<EventSource | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
function connect() {
|
||||
const es = new EventSource("/api/beacon/sse");
|
||||
esRef.current = es;
|
||||
|
||||
es.onmessage = (e) => {
|
||||
try {
|
||||
const incoming = JSON.parse(e.data as string) as BeaconSession;
|
||||
setSession(incoming);
|
||||
} catch { /* ignore malformed */ }
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
es.close();
|
||||
setTimeout(connect, 2000);
|
||||
};
|
||||
}
|
||||
|
||||
connect();
|
||||
return () => esRef.current?.close();
|
||||
}, []);
|
||||
|
||||
// Reactive window show/hide — the pre-warmed window spawns off-screen and
|
||||
// only moves on-screen when there's an actual session to display. This is
|
||||
// what makes the popup feel PyQt-instant: the user never sees an empty
|
||||
// "Standby" placeholder, only the fully populated Ready UI. The endpoints
|
||||
// no-op gracefully when xdotool isn't installed or the pre-warm window
|
||||
// isn't running (e.g., when this page is opened in a regular browser tab).
|
||||
const hasSession = !!session;
|
||||
useEffect(() => {
|
||||
const action = hasSession ? "show" : "hide";
|
||||
fetch(`/api/beacon/window/${action}`, { method: "POST", keepalive: true }).catch(() => {});
|
||||
}, [hasSession]);
|
||||
|
||||
const handleClose = () => {
|
||||
const closingId = session?.id;
|
||||
setTimeout(() => {
|
||||
setSession((prev) => (prev?.id === closingId ? null : prev));
|
||||
}, 1500);
|
||||
};
|
||||
|
||||
if (!session) {
|
||||
return (
|
||||
<div className="flex h-screen flex-col items-center justify-center gap-6 bg-surface-base p-8 select-none">
|
||||
<Image src="/icon.svg" alt={APP_NAME} width={56} height={56} className="opacity-60" />
|
||||
<div className="text-center">
|
||||
<p className="text-sm font-medium text-text-secondary">No agent session waiting</p>
|
||||
<p className="mt-1 text-xs text-text-tertiary">This window will fill in the moment one stops.</p>
|
||||
</div>
|
||||
<Link href={NAV.control.href} className="ui-btn-pill-positive">
|
||||
Open Control panel <ArrowRight className="h-3.5 w-3.5" />
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <BeaconPageClient key={session.id} initialSession={session} onClose={handleClose} />;
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { getSessionUserId } from "@/lib/session";
|
||||
import { readLatestPendingSession } from "@/app/api/beacon/route";
|
||||
import { BeaconLiveClient } from "./BeaconLiveClient";
|
||||
import { isRuntimeAvailable } from "@/lib/runtime";
|
||||
import { getDefaultUser } from "@/db/queries/users";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function BeaconLivePage() {
|
||||
// Cookie-scoped in cloud. On the local runtime, the pre-warmed beacon window
|
||||
// uses an isolated browser profile and may not have the user's auth cookie,
|
||||
// so fall back to the local default user only on that machine.
|
||||
const sessionUserId = await getSessionUserId();
|
||||
const defaultUser = !sessionUserId && isRuntimeAvailable() ? await getDefaultUser() : null;
|
||||
const userId = sessionUserId ?? defaultUser?.id ?? null;
|
||||
const initial = userId ? await readLatestPendingSession(userId) : null;
|
||||
return <BeaconLiveClient initialSession={initial} />;
|
||||
}
|
||||
@@ -5,42 +5,21 @@ import { AUTO_INJECT_MODES, type AutoInjectMode } from "@/config/beacon";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* Per-mode visual state. Color + tooltip make the dispatch behavior
|
||||
* unmistakable at a glance — the root frustration the user surfaced
|
||||
* 2026-05-31 ("what are these random injections / this is dysfunctional")
|
||||
* was that the autopilot's current mode wasn't visible enough to know what
|
||||
* a click anywhere on /control was going to do next.
|
||||
*
|
||||
* off → gray dot · "Manual — you dispatch every prompt"
|
||||
* queue_only → amber dot · "Queue — drain your written list, stop when empty"
|
||||
* beacon → cyan dot, animated · "Beacon — popup + countdown auto-pick"
|
||||
* next_best → blue dot, animated · "Continuous — auto-fires next-best, no popup"
|
||||
* strategist → green dot, animated · "Mission — Groq composes from full context"
|
||||
* Per-mode visual state. After the 2026-06-11 collapse autopilot is binary:
|
||||
* gray dot (off) or pulsing accent dot (on). Color + tooltip make the
|
||||
* dispatch behavior unmistakable at a glance — the user can tell from the
|
||||
* /control top bar whether the next status:ready is going to fire something
|
||||
* or sit idle.
|
||||
*/
|
||||
const MODE_STYLE: Record<AutoInjectMode, { dotClass: string; tooltip: string; pulse: boolean }> = {
|
||||
off: {
|
||||
dotClass: "bg-text-tertiary",
|
||||
tooltip: "Manual (L1) — FleetCrown dispatches nothing. You type every prompt in /control and click Send. Total control; zero surprises.",
|
||||
tooltip: "Autopilot off — FleetCrown dispatches nothing. You type every prompt in /control and click Send.",
|
||||
pulse: false,
|
||||
},
|
||||
queue_only: {
|
||||
dotClass: "bg-status-warning",
|
||||
tooltip: "Queue (L2) — when the agent finishes, FleetCrown fires the next item from YOUR queue. Stops when queue is empty. Your plan, executed in order.",
|
||||
pulse: false,
|
||||
},
|
||||
beacon: {
|
||||
dotClass: "bg-accent-text",
|
||||
tooltip: "Beacon (L3) — prepares the next action and shows a handoff popup. If you are away, the countdown can auto-submit that prepared action.",
|
||||
pulse: true,
|
||||
},
|
||||
next_best: {
|
||||
on: {
|
||||
dotClass: "bg-accent-primary",
|
||||
tooltip: "Continuous (L4) — drains your queue, then sends the canned next-best recovery/progress template without a popup.",
|
||||
pulse: true,
|
||||
},
|
||||
strategist: {
|
||||
dotClass: "bg-status-positive",
|
||||
tooltip: "Mission (L5) — composes from handoff, queue, mission, recent commits, and outcomes, then dispatches without asking.",
|
||||
tooltip: "Autopilot on — when an agent finishes, FleetCrown fires the queue head (or the canned next_best template if the queue is empty). Status:working, blockers, and health gates still apply.",
|
||||
pulse: true,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -14,13 +14,10 @@ import {
|
||||
} from "@/lib/control-states";
|
||||
|
||||
// Single-line hint shown under the fleet chips when this mode is active.
|
||||
// Five-level trust ladder (2026-05-31): Manual / Queue / Beacon / Continuous / Mission.
|
||||
const getAutomationHint = (name: string): Record<AutoInjectMode, string> => ({
|
||||
off: "Manual — agents stop when a task ends; you dispatch every next step.",
|
||||
queue_only: "Queue — agents drain your written queue, then stop.",
|
||||
beacon: "Beacon — popup with smart choices on every handoff; countdown auto-picks if you're away.",
|
||||
next_best: "Continuous — agents auto-run the canned next-best step on every handoff.",
|
||||
strategist: `Mission — ${name} composes context-aware prompts from project mission, goals, and history.`,
|
||||
// Binary autopilot since the 2026-06-11 collapse.
|
||||
const getAutomationHint = (_name: string): Record<AutoInjectMode, string> => ({
|
||||
off: "Off — agents stop when a task ends; you dispatch every next step from /control.",
|
||||
on: "On — agents drain your queue, then auto-fire next_best when the queue is empty. Status:working, blockers, and health gates still apply.",
|
||||
});
|
||||
|
||||
type Props = {
|
||||
|
||||
@@ -46,7 +46,7 @@ export function ProjectCard({
|
||||
runtimeStateKnown = true,
|
||||
daemonSyncStale = false,
|
||||
snapshot,
|
||||
automationMode = "queue_only",
|
||||
automationMode = "on",
|
||||
countdownSeconds,
|
||||
}: {
|
||||
project: ProjectState;
|
||||
@@ -136,24 +136,21 @@ export function ProjectCard({
|
||||
: snapshot?.display ?? getProjectDisplayState(project, zellijTabs, nowS, false, runtimeStateKnown);
|
||||
const isReadyNow = display.isReady || display.isOrchestrationReady;
|
||||
useProjectLifecycleSync(project.tab, isReadyNow);
|
||||
const automaticContinuationEnabled = autoContinueEnabled && (
|
||||
automationMode === "strategist" ||
|
||||
automationMode === "next_best" ||
|
||||
(automationMode === "queue_only" && queue.length > 0)
|
||||
);
|
||||
const queuePolicyWaiting = automationMode === "queue_only" && autoContinueEnabled && queue.length === 0;
|
||||
// After the 2026-06-11 collapse autopilot is binary. "on" continues when
|
||||
// the agent self-reports ready; "off" never does. The queue is drained
|
||||
// head-first; nextbest fills in when the queue runs dry. Auto-continue
|
||||
// remains a per-project pause/resume toggle independent of the mode.
|
||||
const automaticContinuationEnabled = autoContinueEnabled && automationMode === "on";
|
||||
const tabOpenUntracked = display.tone === "idle" && display.tabOpen && !display.isRunning;
|
||||
const automationStatusLabel = tabOpenUntracked
|
||||
? "Tab open on your computer — focus the workspace to check the agent, or send a prompt below."
|
||||
: automationMode === "off"
|
||||
? "Manual: this project waits for your instruction."
|
||||
: !autoContinueEnabled
|
||||
? "Automatic continuation paused for this project."
|
||||
: queuePolicyWaiting
|
||||
? "Continue queued work: add an instruction to run it when the agent waits."
|
||||
: automationMode === "queue_only"
|
||||
? "Continue queued work: the next queued instruction will send when the agent waits."
|
||||
: "Autonomous: the next task may start when the agent waits.";
|
||||
? "Autopilot off: this project waits for your instruction."
|
||||
: !autoContinueEnabled
|
||||
? "Automatic continuation paused for this project."
|
||||
: queue.length > 0
|
||||
? "Autopilot on: the next queued instruction will send when the agent waits."
|
||||
: "Autopilot on: next_best will fire when the agent waits (queue is empty).";
|
||||
|
||||
const {
|
||||
sending, justSent, custom, setCustom, customFocused, setCustomFocused,
|
||||
@@ -299,13 +296,13 @@ export function ProjectCard({
|
||||
nextQueueItem={sessionHealthBlocksQueue() ? undefined : queue[0]}
|
||||
queueTotal={sessionHealthBlocksQueue() ? 0 : queue.length}
|
||||
healthBypass={sessionHealthBlocksQueue() && queue.length > 0 ? (project.session?.health?.toLowerCase().includes("critical") ? "Health critical" : "Tests failing") : undefined}
|
||||
dispatchReason={!sessionHealthBlocksQueue() && preloadedDispatch?.source === "groq" ? preloadedDispatch.reason : undefined}
|
||||
dispatchReason={undefined}
|
||||
onDismiss={() => setDismissed(true)}
|
||||
onSend={send}
|
||||
onAutoInject={runtimeAvailable !== false ? handleAutoInject : undefined}
|
||||
onToggleAutoContinue={automationMode === "off" || queuePolicyWaiting ? undefined : toggleAutoContinue}
|
||||
onToggleAutoContinue={automationMode === "off" ? undefined : toggleAutoContinue}
|
||||
showKeyHints={isOnlyReady}
|
||||
inactiveLabel={queuePolicyWaiting ? "Queue empty" : undefined}
|
||||
inactiveLabel={undefined}
|
||||
countdownSeconds={countdownSeconds}
|
||||
/>
|
||||
{(display.isReady || display.isOrchestrationReady) && (
|
||||
|
||||
+28
-29
@@ -25,15 +25,14 @@ export const TRANSCRIPTION_PROVIDERS: readonly { value: TranscriptionProvider; l
|
||||
{ value: "local", label: "Local Whisper", note: "your machine's Whisper model — requires runtime, no Groq attempt" },
|
||||
];
|
||||
|
||||
// The five-level autopilot trust ladder. Each level adds one more thing
|
||||
// FleetCrown decides on your behalf — L1 (you decide everything) to L5 (full
|
||||
// AI-composed dispatch). Storage values keep legacy names ("off",
|
||||
// "queue_only", "next_best", "strategist") for migration safety; the UI
|
||||
// surfaces the new names (Manual, Queue, Beacon, Continuous, Mission) and
|
||||
// the new "beacon" value is the one being added 2026-05-31 to restore the
|
||||
// popup UX removed by commit 848da6c. Order in this array reflects the
|
||||
// trust ladder top-down (Manual → Mission); UI selector iterates this order.
|
||||
export const AUTO_INJECT_MODE_VALUES = ["off", "queue_only", "beacon", "next_best", "strategist"] as const;
|
||||
// Autopilot is binary. After the 2026-06-11 collapse (killing-the-bash-daemon
|
||||
// migration, Session 3), the five-tier ladder (off/queue_only/beacon/
|
||||
// next_best/strategist) is replaced by off|on. Most users only ever used "off"
|
||||
// or "fire-when-done"; the intermediate tiers were cognitive load without
|
||||
// proportionate value. Safety rails (status:working, blockers, no-op counter,
|
||||
// health gates) still apply at every level — being "on" doesn't override the
|
||||
// agent's "I'm not done" signal.
|
||||
export const AUTO_INJECT_MODE_VALUES = ["off", "on"] as const;
|
||||
export type AutoInjectMode = (typeof AUTO_INJECT_MODE_VALUES)[number];
|
||||
|
||||
export const AUTO_INJECT_MODES: readonly {
|
||||
@@ -43,31 +42,31 @@ export const AUTO_INJECT_MODES: readonly {
|
||||
}[] = [
|
||||
{
|
||||
value: "off",
|
||||
label: "Manual",
|
||||
description: "L1 · FleetCrown dispatches nothing. You type every prompt in /control and click Send. Total control; zero surprises.",
|
||||
label: "Off",
|
||||
description: "FleetCrown dispatches nothing. You type every prompt in /control and click Send.",
|
||||
},
|
||||
{
|
||||
value: "queue_only",
|
||||
label: "Queue",
|
||||
description: "L2 · When an agent finishes, FleetCrown fires the next item from YOUR queue. Stops when queue is empty. Your plan, executed in order.",
|
||||
},
|
||||
{
|
||||
value: "beacon",
|
||||
label: "Beacon",
|
||||
description: "L3 · When the agent finishes, FleetCrown prepares the next action and shows a handoff popup. If you are away, the countdown can auto-submit that prepared action.",
|
||||
},
|
||||
{
|
||||
value: "next_best",
|
||||
label: "Continuous",
|
||||
description: "L4 · Drains your queue, then sends the canned next-best recovery/progress template without a popup. Useful for routine cleanup; less context-aware than Mission.",
|
||||
},
|
||||
{
|
||||
value: "strategist",
|
||||
label: "Mission",
|
||||
description: "L5 · FleetCrown composes a prompt from the handoff, queue, project mission, recent commits, and outcomes, then dispatches it without asking. Highest autonomy; review results regularly.",
|
||||
value: "on",
|
||||
label: "On",
|
||||
description: "When an agent finishes, FleetCrown fires the queue head — or, if the queue is empty, the canned next_best recovery template. Status:working, blockers, and health gates still apply.",
|
||||
},
|
||||
];
|
||||
|
||||
/** Legacy modes from before the 2026-06-11 collapse. Read-only; used only
|
||||
* by the one-time migration UPDATE and for tolerant parsing of old stored
|
||||
* values. Do not reference from runtime decision code. */
|
||||
export const LEGACY_AUTO_INJECT_MODE_VALUES = ["queue_only", "beacon", "next_best", "strategist"] as const;
|
||||
export type LegacyAutoInjectMode = (typeof LEGACY_AUTO_INJECT_MODE_VALUES)[number];
|
||||
|
||||
/** Map any value (current or legacy) to the new 2-state space. Off stays off;
|
||||
* every other historical mode collapses to "on" because they all auto-fired
|
||||
* in some way. Use this when reading an old DB row or env var that hasn't
|
||||
* been migrated yet. */
|
||||
export function normalizeAutoInjectMode(raw: string | null | undefined): AutoInjectMode {
|
||||
if (raw === "off") return "off";
|
||||
return "on";
|
||||
}
|
||||
|
||||
export const POPUP_MODE_VALUES = ["web", "disabled"] as const;
|
||||
export type PopupMode = (typeof POPUP_MODE_VALUES)[number];
|
||||
|
||||
|
||||
@@ -9,16 +9,16 @@ export const beaconSettings = pgTable("beacon_settings", {
|
||||
minIdleSeconds: integer("min_idle_seconds").notNull().default(0),
|
||||
whisperModel: text("whisper_model").notNull().default("base"),
|
||||
transcriptionProvider: text("transcription_provider").notNull().default("auto"),
|
||||
// off | queue_only | beacon | next_best | strategist — the five-level
|
||||
// autopilot trust ladder (Manual / Queue / Beacon / Continuous / Mission).
|
||||
// Default is "beacon" (L3): popup with smart choices + countdown auto-pick
|
||||
// when the agent finishes. Right starting trust level — new users see
|
||||
// every dispatch through a popup before opting into Continuous (L4) or
|
||||
// Mission (L5). Was "strategist" (L5) until 2026-05-31 — flipped after
|
||||
// user feedback that L5 felt like a loose cannon (composed AI prompts
|
||||
// fired without consent step). Safety rails (status:working gate,
|
||||
// pending-blocker gate) apply at every level above off.
|
||||
autoInjectMode: text("auto_inject_mode").notNull().default("beacon"),
|
||||
// off | on — autopilot is binary after the 2026-06-11 collapse (see
|
||||
// src/config/beacon.ts and content/thoughts/killing-the-bash-daemon.md).
|
||||
// Default is "on": when an agent self-reports status:ready, FleetCrown
|
||||
// fires the queue head (or the canned next_best template if the queue
|
||||
// is empty). Safety rails (status:working/blocked, pending-blocker gate,
|
||||
// no-op fuse, health gate) all still apply. Legacy values queue_only |
|
||||
// beacon | next_best | strategist were migrated to "on" in the same
|
||||
// commit; coerceAutoInjectMode in src/db/queries/beacon-settings.ts
|
||||
// tolerates them for any row that escapes the UPDATE.
|
||||
autoInjectMode: text("auto_inject_mode").notNull().default("on"),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (t) => [
|
||||
index("idx_beacon_settings_user_id").on(t.userId),
|
||||
|
||||
@@ -251,19 +251,11 @@ export function useProjectCardActions({
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Strategist v1: when /api/control/dispatch composed a context-aware
|
||||
// body, inject that directly as a custom prompt instead of falling
|
||||
// back to the canned next_best template. Closes the "auto-inject is
|
||||
// generic and unrelated to what I last asked for" gap. The composed
|
||||
// body is constructed from session handoff, queue tail, recent
|
||||
// commits, and outcome streak by Groq — see /api/control/dispatch.
|
||||
if (action === "composed" && decision?.prompt && decision.prompt.length > 10) {
|
||||
setSending("custom");
|
||||
setDismissed(true);
|
||||
try { await onInject(project.tab, undefined, decision.prompt); }
|
||||
finally { setSending(null); }
|
||||
return;
|
||||
}
|
||||
// Strategist composer was removed in the 2026-06-11 collapse — no more
|
||||
// "composed" action coming back from dispatch. The dispatch route now
|
||||
// only returns "queue", "nextbest", or "off". If we get here it's
|
||||
// because the gate-evaluator picked nextbest (or the caller asked
|
||||
// without a queue head); fire the canned template.
|
||||
await sendIntent("next_best");
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [autoContinueEnabled, preloadedDispatch, queue, removeFromQueue, project.tab, project.agentRunning, project.currentPrompt, onInject, setDismissed, project.session?.status, project.session?.health, project.session?.tests]);
|
||||
|
||||
@@ -12,14 +12,11 @@ export const MAX_BEACON_COUNTDOWN_S = 300; // longest allowed beacon countd
|
||||
export const DEFAULT_BEACON_MIN_IDLE_S = 0; // 0 = always show popup regardless of keyboard activity
|
||||
export const MAX_BEACON_MIN_IDLE_S = 600; // 10 minutes max
|
||||
export const DEFAULT_POPUP_MODE = "web"; // "web" | "disabled" — "both"/"pyqt" coerced to "web" for legacy rows
|
||||
/** New-user autopilot policy. "beacon" (L3) is the right starting trust level:
|
||||
* popup with smart choices fires when an agent finishes, user picks (or
|
||||
* countdown auto-picks). Total agency without manual labor. Was "strategist"
|
||||
* (L5) until 2026-05-31 — strategist composed AI prompts directly which
|
||||
* shipped a loose-cannon behavior nobody had earned trust for. New users go
|
||||
* through the L1→L2→L3 trust ladder before upgrading to L4 Continuous or L5
|
||||
* Mission. Safety rails (status:working, blockers) still apply at every level. */
|
||||
export const DEFAULT_AUTO_INJECT_MODE = "beacon" as const;
|
||||
/** New-user autopilot policy. After the 2026-06-11 collapse the choice is
|
||||
* binary — "on" defaults to true so new users get the fire-when-ready
|
||||
* behavior immediately (still safety-gated by status:working, blockers,
|
||||
* health). Users who want to dispatch every prompt manually toggle off. */
|
||||
export const DEFAULT_AUTO_INJECT_MODE = "on" as const;
|
||||
|
||||
// Fleet query windows — used by getFleetSummary (today.ts) to classify agent states from DB only.
|
||||
// PROMPT_RUNNING_WINDOW_S: a started prompt older than this is considered stale (crashed without cleanup).
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
/**
|
||||
* Pre-Groq gates for the /api/control/dispatch route. Centralized so the
|
||||
* route handler stays focused on the strategist composition path and so
|
||||
* the gate invariants can be unit-tested without a running server.
|
||||
* Pre-decision safety gates for the /api/control/dispatch route. Centralized
|
||||
* so the route handler stays focused on the simple queue-vs-nextbest
|
||||
* decision and so the gate invariants can be unit-tested without a running
|
||||
* server.
|
||||
*
|
||||
* Gate precedence (first matching wins; all return action="off"):
|
||||
* Gate precedence (first matching wins):
|
||||
* 1. handoff.status === "working" or "blocked" — agent declared unavailable; never interrupt
|
||||
* 2. blockerCount > 0 — human-action gate is open; wait for clear
|
||||
* 3. noOpCount >= 3 — repeated no-op loop; require state change
|
||||
* 4. mode === "off" — user disabled autopilot in settings
|
||||
* Plus the non-off short-circuits:
|
||||
* 5. mode === "queue_only" — fire queue head or stay idle
|
||||
* 6. mode === "next_best" — fire the canned template
|
||||
* `null` means "no gate fired — proceed to strategist (Groq composition)".
|
||||
* 2. blockerCount > 0 — human-action gate is open; wait for clear
|
||||
* 3. noOpCount >= 3 — repeated no-op loop; require state change
|
||||
* 4. mode === "off" — user disabled autopilot
|
||||
* 5. mode === "on" — fire queue head if non-empty, else nextbest
|
||||
*
|
||||
* After the 2026-06-11 mode collapse there's no fall-through to a strategist
|
||||
* composer — the route returns whatever this function returns. The Groq
|
||||
* composition path was removed entirely; autopilot fires the user's queue
|
||||
* or the canned next_best template. Safety rails 1-3 are preserved.
|
||||
*/
|
||||
|
||||
import type { DispatchAction, DispatchResult } from "@/app/api/control/dispatch/route";
|
||||
@@ -61,32 +64,14 @@ export function evaluateDispatchGates(input: GateInput): DispatchResult | null {
|
||||
};
|
||||
}
|
||||
|
||||
if (mode === "queue_only") {
|
||||
const fired: DispatchAction = queueLength > 0 ? "queue" : "off";
|
||||
return {
|
||||
action: fired,
|
||||
reason: queueLength > 0
|
||||
? `Queue-only mode — firing queue item 1.${streakSuffix}`
|
||||
: "Queue-only mode and queue is empty — nothing to do.",
|
||||
source: "mode_gate",
|
||||
};
|
||||
}
|
||||
|
||||
if (mode === "next_best") {
|
||||
return {
|
||||
action: "nextbest",
|
||||
reason: `Legacy next_best mode (no strategist).${streakSuffix}`,
|
||||
source: "mode_gate",
|
||||
};
|
||||
}
|
||||
|
||||
// beacon (L3 popup + countdown) and strategist/Mission (L5) both fall through
|
||||
// to the Groq composer in the route. The beacon UI calls dispatch to decide
|
||||
// the auto-pick (queue head vs composed vs canned) when countdown fires.
|
||||
// strategist mode forces the composed path for full autonomy.
|
||||
if (mode === "beacon" || mode === "strategist") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return null;
|
||||
// mode === "on": fire queue head when present, otherwise the canned
|
||||
// next_best recovery template. No strategist composition, no Groq call.
|
||||
const fired: DispatchAction = queueLength > 0 ? "queue" : "nextbest";
|
||||
return {
|
||||
action: fired,
|
||||
reason: queueLength > 0
|
||||
? `Autopilot on — firing queue item 1.${streakSuffix}`
|
||||
: `Autopilot on, queue empty — firing next_best.${streakSuffix}`,
|
||||
source: queueLength > 0 ? "mode_gate" : "empty_queue",
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user