Commit Graph
1545 Commits
Author SHA1 Message Date
Mao NakamotoandClaude Opus 4.7 7293d3bf0f feat(activity): ingest local Claude Code chats into unified timeline
Before this commit, /activity only knew about prompts dispatched through
/control and runs spawned by orchestration. The much larger pool of
context — every time the founder typed into a local Claude Code session
in their terminal — sat invisible on disk in the JSONL transcripts the
CLI writes to ~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl. The
"god-level context-aware" ask is to fuse the two streams so /activity
becomes "everything you typed about this project anywhere," which is
what an agent fleet's activity view should always have been.

Mechanism:
  1. New table claude_code_history mirrors per-event metadata from the
     JSONL transcripts. (session_id, event_uuid) is UNIQUE so re-ingest
     is idempotent — incremental sync is just a re-run.
  2. scripts/ingest-claude-code-history.ts walks the projects dir,
     resolves cwd → user_projects.dir_path → projectKey, and inserts
     user + assistant turns with ON CONFLICT DO NOTHING. Backfilled the
     31,284 historical events on first run (FleetCrown 11.7k, revamp-it
     6.3k, OrangeCat 5.2k, etc.).
  3. digests.ts pulls the user-only slice into the digest timeline as
     a new "local_chat" kind, includes those events in per-project
     activity counts so the chip wall ranks projects honestly, and
     bumps MAX_TIMELINE_ITEMS 80→120 so a busy day fits without
     starving prompts/runs.

EventStream renders the new kind without changes — it was already
content-agnostic. A FilterCard toggle for "include/exclude local chats"
is a natural follow-up but the timeline is already useful as-is.

Schema applied to local Postgres via raw SQL because drizzle-kit push
wanted to interactively confirm an unrelated agent_tokens.token
constraint backfill. The schema file is the SSOT; this commit is the
source of truth a future migration tool will diff against.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-10 17:15:23 +02:00
Mao NakamotoandClaude Opus 4.7 83d07ef1bf fix(daemon): guard against double-execution on crash-reclaim
The 10-second STALE_CLAIM_SECONDS recovery in
reclaimStalePendingCommands closes the visible symptom of a daemon
crash mid-dispatch — the row becomes claimable again. But it opens a
worse failure: if the first daemon already typed keystrokes into the
terminal before crashing, the second daemon will replay execute_inject
and double-type. This is the actual race A1 was masking, not fixing.

Fix is a 23-line addition to the dispatch loop. Before entering the
case statement, write /tmp/<brand>-attempted-<id> with the current
timestamp. On every dispatch iteration, first check whether that file
exists — if it does, this row was already attempted by some earlier
process (this one or a crashed predecessor). Refuse to re-execute;
PATCH mark_done with a structured "abandoned mid-execution" reason so
the user sees what happened in /control and can retry explicitly. On
clean completion (after esac), remove the marker.

Why a /tmp marker instead of a DB column: tmpfs survives daemon
process death but not machine reboot. That matches the failure modes
we care about — a daemon crash leaves zellij + tmpfs intact (so the
keystrokes really did land, and we must NOT replay), while a machine
reboot wipes both (so the keystrokes never landed, and we MUST be
able to replay). Adding a column to pending_commands would persist
the marker across reboots and prevent legitimate replay.

No double-execution observed in production yet — this closes the
window before it bites. Pairs with Phase 2 (?types= filter) and
Phase 3 (runId sentinel) shipped in cdc042a.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-10 16:36:31 +02:00
Mao Nakamoto 8b9b07b67c fix: make prompt activity use one display source 2026-06-10 15:49:29 +02:00
Mao Nakamoto cdc042a131 feat: ship activity runtime parity fixes 2026-06-10 14:57:19 +02:00
Mao Nakamoto d84b880da9 feat(activity): unify digests history decisions 2026-06-09 18:42:34 +02:00
Mao Nakamoto 04fb546c91 test(smoke): cover digests route 2026-06-09 18:17:08 +02:00
Mao Nakamoto ea86905967 feat(control): per-project autopilot and digests 2026-06-09 18:09:09 +02:00
Mao NakamotoandClaude Opus 4.7 3f3b6c5557 feat(control): dispatch-confirmation chip on every action button
UX audit gap: Send / Test & fix / Quality / Commit / Next best all return
200 with zero visual confirmation — textarea clears, button reverts to
its label, and the user is left asking "did it actually do anything?"
The proven pattern already lives in ProjectStatusChips → focusWorkspace
("Tab switched ✓" for 2 seconds after success). Apply it everywhere.

  useProjectCardActions now exposes a `justSent: {id, at} | null` state
  set on confirmed-successful sendCustom / sendText / sendIntent / send.
  Auto-clears after 1500ms via a single useRef'd timer.

  PromptInput Send button flashes "Sent ✓" on a positive-tone background
  for that window.

  IntentButtonPanel primary CTA ("Next best") flips to "✓ Dispatched";
  secondary intent chips (Test & fix / Quality / Commit) and the More
  chips collapse their label to "✓" so the row stays compact.

No state-detection change — every button still does exactly what it did
before. Only the post-success label is new.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 15:46:04 +02:00
Mao NakamotoandClaude Opus 4.7 83489c6ed4 fix(home): emit Access-Control-Allow-Private-Network on CORS preflight
Chrome's Private Network Access requires the cross-origin target (the
local home/ daemon on 127.0.0.1) to opt in when the requesting page
is on a public network (cloud /control on https://fleetcrown.vercel.app).
Without this header the preflight silently aborts and the same-machine
fast path falls through to the cloud path 100% of the time even with the
daemon running.

This header is the documented spec opt-in
(https://developer.chrome.com/blog/private-network-access-preflight).
Chrome may still apply mixed-content gates on top of it for HTTPS pages
reaching plain-HTTP loopbacks; in that case the fast path only engages
from dev (http://localhost:3000/control) and the cloud path is
authoritative for production. Future work: terminate TLS on the local
daemon so the public→private hop becomes HTTPS→HTTPS and the gate
clears entirely.

curl-level preflight verified:
  Access-Control-Allow-Origin: https://fleetcrown.vercel.app
  Access-Control-Allow-Methods: POST, GET, OPTIONS
  Access-Control-Allow-Headers: Content-Type
  Access-Control-Allow-Private-Network: true

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 15:02:24 +02:00
Mao NakamotoandClaude Opus 4.7 f0d4795945 feat(states): finish SSOT — bash vocab + agent prompt context + daemon banner
Phase B + C + D of /home/g/.claude/plans/ethereal-crunching-clover.md.

B1. Generate bash state vocabulary from the TS SSOT
   - scripts/generate-bash-state-vocab.ts reads STATE_DEFINITIONS from
     src/lib/control-states.ts and emits scripts/control-states.generated.sh
     with FC_LABEL_<KEY>, FC_DESCRIPTION_<KEY>, FC_COUNTER_CATEGORY_<KEY>
     for every state.
   - Wired into package.json's prebuild step so every `npm run build`
     refreshes the file. Daemon sources it; new states propagate without
     hand-editing any bash.

B2. Agent prompt context reads STATE_DEFINITIONS[k].description
   - buildPromptWithSession(base, tab, projectStateDescription?) gained
     a third optional argument. When passed, prepends
     "Project state: <description>" before the session-state block — the
     same one-line WHY the human sees on the badge hover tooltip.
   - deriveProjectStateKey() in control-states.ts maps the raw signal
     set (agentRunning / tabOpen / sessionStatus / readyAt / lockAt /
     closingAt / closedAt) to a ProjectStateKey without dragging in the
     full presenter machinery.
   - Threaded into /api/inject (promptKey path) and the Claude +
     Codex/Gemini paths in /api/orchestration/run. The agent now reads
     the same words the user reads.

C. ControlFleetStatus migrated to DAEMON_STATE_DEFINITIONS
   - lib/control-states.ts gains a sibling SSOT for daemon-side states
     (setup_needed / offline / state_unknown / connected). Same shape:
     label, description, dotClass, problem hint.
   - ControlFleetStatus reads from it for the banner label + tooltip +
     problem CTA, dropping the hand-rolled `daemonNeverSeen ? "Setup
     needed" : daemonOffline ? "Daemon offline" : ...` tree.
   - "Setup needed" surfaces an "Install Fleet Runner" action chip
     linking to /download with the longer how-to on hover — same
     pattern the per-project badge uses.
   - DaemonStatusBanner (the rich 320-line install/recovery card) is
     left alone — its UX is distinct from the status indicator.

D. Cleanup
   - fleetcrown-daemon.sh now traps EXIT in addition to INT/TERM and
     kills its forked sibling daemons (the multi-source polling forks
     spawned for each FLEETCROWN_BASE_URLS entry). Was a defensive
     improvement; the observed "12+ stale daemons" turned out to be
     normal subshell tree.
   - .env.vercel.production renamed to .OLD so an accidental
     `vercel --prod` from CLI doesn't reupload the stale Neon URLs over
     the live Hetzner Postgres (memory/pattern_vercel_cli_env_local_override.md).
     .gitignore extended to keep the .OLD file out of git too.
   - DATABASE_URL + DATABASE_POOL_URL moved from a single-branch preview
     scope to all-preview, so future PRs build without the
     "DATABASE_URL is required" build crash we hit on the
     arch/control-stream-no-poll branch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 14:50:42 +02:00
Mao NakamotoandClaude Opus 4.7 2e420bda4c feat(inject): structured errors + cwd-fallback + same-machine fast path
Phase A of /home/g/.claude/plans/ethereal-crunching-clover.md. Three
independent changes share one goal: make /control inject actually
diagnosable + actually reliable on the common case.

A1. Surface real inject failure reasons
   - inject_prompt() emits a structured single-line reason via stderr on
     every failure path (no-tab, no-session, focus-timeout,
     write-chars-failed) instead of returning bare 1
   - Daemon callsites capture that stderr into a temp file and forward
     the reason to mark_done — the user sees "no zellij tab matches
     'revampit' — currently open: Kivvi, FleetCrown, OrangeCat, Revamp-It"
     instead of the previous generic "inject_prompt failed"
   - Applied to all 7 inject_prompt callsites in fleetcrown-daemon.sh

A2. Match agents by cwd, not just by tab name
   - New _resolve_live_tab_by_cwd() walks zellij dump-layout, reconstructs
     each pane's absolute cwd from the layout-level cwd + pane cwd, and
     returns the tab whose pane is rooted in the target project_dir
   - inject_prompt() takes an optional project_dir 3rd arg; when the
     name match fails (revampit vs Revamp-It vs revamp-it kind of bug),
     the cwd fallback fires
   - Daemon callsites thread project_dir through. Fixes the revampit
     dispatch we observed.

A3. Same-machine fast path
   - home/server.ts gains POST /api/inject. Spawns bash, sources
     agent-hook-lib.sh, calls inject_prompt directly. Returns
     {ok:true} or {ok:false, reason}. Binds 127.0.0.1 only so the
     LAN cannot reach it.
   - CORS allow-list permits https://fleetcrown.vercel.app and the local
     dev origins — every other origin's browser blocks the response.
   - src/hooks/use-control-data.ts::inject() tries the local fast path
     first with a 600ms abort timeout. Success returns; failure with a
     reason re-throws (caller renders); no-daemon falls through to the
     cloud path silently.
   - Result: 7 hops (browser → Vercel → DB → daemon poll → exec → focus
     → write) collapse to 3 (browser → home → exec) for the common case.
     Reliability follows from deletion.

Bonus: home/projects.ts::resolveProjectPath() now does a loose match
(strip hyphens + underscores) when the literal lookup misses. Lets the
cloud send "revampit" find the conf entry "revamp-it" without forcing a
rebrand. Tested with revampit; injection lands.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 14:22:34 +02:00
Mao NakamotoandClaude Opus 4.7 04ba2a7578 feat(control): SSOT for project states + actionable problem hints
Introduces src/lib/control-states.ts as the single source of truth for
project state vocabulary. Every consumer of the control surface (badge,
chip, summary counter, terminal-workspaces row, project rail, dot color,
hover tooltip, agent prompt context) reads from STATE_DEFINITIONS keyed
by ProjectStateKey. Adding a state requires exactly one literal edit;
the compiler then forces every downstream Record to remain exhaustive,
so drift between rows ("Waiting for instructions") and chips ("awaiting
input") is structurally impossible.

What this fixes
  - "The UI lies" report: same fact rendered with different wording in
    badge vs. summary chip. Now both read the SSOT label.
  - "Dot is gray, green, brown, whatever": three components each rolled
    their own dot color tree. All now derive from
    STATE_DEFINITIONS[k].dotClass. The palette is intentionally finite
    (4 meanings, 4 colors): accent+pulse for working, positive for
    handoff/completed/ready, warning for offline, muted for inert.
  - Problem states had no visible remediation. STATE_DEFINITIONS now
    carries a `problem: { hint, ctaLabel, ctaHref } | null` field;
    offline projects render an "Install Fleet Runner" action chip next
    to the badge linking to /download. The hint also shows on hover.
  - Every state badge in the control surface now has `title=` set to
    STATE_DEFINITIONS[k].description — the same one-line WHY that will
    later be passed to the agent prompt context so the agent reads the
    same words the human sees on screen.

Stages 1–3 of the iron-discipline plan are in this commit.

Bonus: src/lib/terminals/zellij.ts now throws actionable errors on
inject focus failure. The previous "did not gain focus within 1s — is
the tab open and zellij reachable?" left users guessing; the new
errors name the sessions actually running, the tabs found in each, and
the exact next step (open the tab, rename it, or reattach the session).

No behavioral change in state derivation — every state still derives
from the same input signals; the only difference is that the label,
dot color, tooltip, and problem hint are now sourced from one place.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 13:34:58 +02:00
Mao NakamotoandClaude Opus 4.7 9eeccc7b68 fix(control): rename 'Waiting for instructions' to 'Awaiting input'
The old label implied the project itself was dormant ("waiting for
instructions") when the actual underlying state is "agent process
detected, no recent handoff signal." It also disagreed with the
summary chip ("X awaiting input") that uses different wording for the
same fact.

Two consequences for a developer actively working on a project whose
Claude instance is at the prompt:
  - the row badge said "Waiting for instructions" (implies idle project)
  - the summary said "N awaiting input" (correct)
The user reasonably reads this as the UI lying.

Pick one honest, actionable phrase ("Awaiting input") and use it in
both places. No state-detection change — only wording.

The deeper truth gap (revampit's Claude isn't writing the
/tmp/agent-handoff-sent-* sentinel that would push the row to "Ready
for next step") is a separate hook-coverage issue that this rename
does not pretend to fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 12:46:48 +02:00
Mao NakamotoandClaude Opus 4.7 340ba56500 fix(postbuild): skip local standalone+systemd path on hosted CI
scripts/deploy-local.sh copies runtime assets into .next/standalone and
restarts a local systemd service. Both are wrong on Vercel (no standalone
output by default, no systemd), and any failure inside the script surfaces
as the confusing "Command npm run build exited with 1" on Vercel without
hinting at the postbuild as the culprit.

Bail at the top when VERCEL or CI is set so the build proceeds with just
next build, the way Vercel expects.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 12:05:23 +02:00
Mao NakamotoandClaude Opus 4.7 796f1f8290 fix(control): unblock prod queries + remove per-card polling
Two related fixes that together restore the /control page to a working state.

1. Missing migration 0030_session_block_reason.sql

Commit 729237c added session_block_reason + session_no_op_count to the
project_states schema without generating a SQL migration. Production
Postgres lacked both columns, so every SELECT on project_states crashed
with 42703 (errorMissingColumn). Symptom: /api/beacon/queue/<tab>
returning 500/503 in a tight loop, /api/control/stream emitting empty
project state, every project rendering "Offline · Live status
unavailable" on /control.

The migration is additive and idempotent.

2. Per-card polling → SSE-piped state

usePromptQueue and useAutoContinue each opened a per-card HTTP read loop
(setInterval @ 2 s and an on-mount fetch) against /api/beacon/queue/<tab>
and /api/control/auto-continue?tab=<tab>. With 21 projects on the page
that meant an N+1 request storm for state that the /api/control/stream
SSE endpoint can deliver as a single push.

Stream the data instead:
  - FastProjectState gains optional promptQueue / promptQueueRevision /
    autoContinueEnabled
  - /api/control/stream dbToFastState emits them from project_states
  - /api/control populates the same fields so the first paint matches the
    stream shape and no second mount-fetch is needed
  - useControlData.mergeProjectPatches forwards the fields onto each
    ProjectState
  - usePromptQueue / useAutoContinue accept the values as props, drop
    the polling loop, and only fall back to a one-shot HTTP load when
    the props are absent (local /proc-backed runtime path that doesn't
    project DB fields)
  - ProjectCard threads project.promptQueue + project.autoContinueEnabled
    into the hooks

Mutation paths (PUT /api/beacon/queue/<tab>, POST /api/control/auto-continue)
are unchanged. Optimistic local state + revision-based CAS retry still work
exactly as before; the stream just pushes the post-write revision back
instead of the hook polling for it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 11:31:55 +02:00
Mao NakamotoandCursor a4f52b3fb2 test(control-presenter): align open-idle evidence label with badge wording
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-09 02:41:54 +02:00
Mao NakamotoandCursor 9ddcec86d7 test(autopilot): update daemon.env loader assertions for brand rename
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-09 02:31:55 +02:00
Mao NakamotoandCursor b1c4a3eb74 fix(control): stabilize autopilot injection and fleet observability
Align stop-hook, beacon, and UI dispatch gates so autopilot respects per-project pause, choice wire format, and typing blocks; add control audit trail, Fleet Doctor, and updated cloud-local docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-09 02:28:06 +02:00
Mao NakamotoandClaude Opus 4.7 8a44e2c5b8 fix(control): state-label SSOT, error dedup, selected-row clarity
Five drifted phrasings collapsed into one set. Same conceptual state
("agent shell open, awaiting input") was being labeled "Agent shell
open" / "Ready — pick the next task" / "Agent open · idle" / "Tab open ·
no agent process" / "Open, idle" by four different functions —
staleEvidenceLabel, getTabActivityText, buildLiveTabRows, liveEvidenceLabel.
All now route through display.stateLabel (the canonical STATE_LABEL map)
so the badge, row subtitle, workspace panel, and activity feed agree on
one wording per state.

Identical adjacent failures in AttentionBar collapse into one row with
×N count. Pre-fix three consecutive "inject → fleetcrown failed" rows
piled up; now they read "inject → fleetcrown failed: <reason> ×3"
with the dismiss button clearing the whole group.

Selected project row in ProjectOperationsView now dims its siblings
(opacity-60) so the "this row IS the expanded card below" connection is
obvious. Used to look like 20 identical rows above what appeared to be a
21st duplicate row.

Repair connection → Restart helper (matches what it actually does).
ZellijLivePanel composer placeholder + title clarify it's a quick-send
to any tab, distinct from the project card's intent dispatch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-08 18:49:30 +02:00
Mao NakamotoandClaude Opus 4.7 bdd4fc14f7 feat(fleet): cold-start restoration + reliable injection
After a PC restart, Fleet Runner now brings zellij + every agent back
without the user opening a terminal or typing CLI names. The last
runtime_snapshot.panes (extended with {tab, paneIndex, agentCli, cwd})
acts as SSOT for "what should be running" — Fleet Runner generates a KDL
layout with embedded `bash -c "cd … && claude"` per pane and spawns
`zellij --session fleet --layout`, bypassing zellij's press-ENTER
resurrection prompt entirely.

Injection is now self-healing end-to-end. Pre-flight ensureZellijReady
re-spawns the session if it died mid-day. /tmp/fc-cmd-<id>.done sentinels
make commands actually idempotent so a PATCH-ack retry can't fire the
same prompt twice. Post-flight watches ~/.claude/sessions/<tab>.md mtime
for 5s after inject and reports verified=false if the agent didn't pick
up — surfaced in AttentionBar via getRecentFailedCommands. The legacy
"No Zellij session found — start Zellij first" throw is replaced with a
synchronous spawn-default-session path so /api/agent/launch on
self-hosted servers self-heals too.

Settings → Agent gets a new Fleet Lifecycle section (auto-restore on/off,
fresh-spawn vs leave-alone for exited zellij sessions, session name,
auto-start at login). Stored as users.fleet_settings jsonb so future
knobs don't need a migration each time.

Bundled binary version-aware (Fleet Runner ≥0.4.0 ships zellij in
resources/bin and prepends to PATH). Inline tests for the KDL generator
run as a 9th suite under `npm run test:home` — 8/8 cases pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-08 18:47:58 +02:00
Mao NakamotoandClaude Opus 4.7 eaeaa44356 feat(control): agent switching v0.8.0
Users switch agents from the Control UI without typing quit commands in
Zellij — click the agent chip on a project card, pick from Cmd+K palette,
or accept the rate-limit banner's fallback suggestion. Detection lives in
agent-resolution.ts (client-safe) + agent-process-scan.ts (server /proc
walk); switch enqueues pending_commands type switch_agent which the Fleet
Runner poller executes locally, quitting every running agent in the dir
before launching the next.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-08 18:46:30 +02:00
Mao NakamotoandClaude Opus 4.7 729237cd69 feat(control): structured loop-control fields end-to-end
Phase 1 of the sustainable autopilot-control refactor. Adds explicit
block-reason + no-op-count fields to the session.md handoff, plumbs
them through parser → desktop pusher → API → DB → React, and updates
the bash guard to read them directly. Eliminates the three-vocabulary
problem that caused the OC no-op spiral on 2026-06-08, where agent's
"health: critical — awaiting user" string collided with the bash
guard's first-word match.

Schema:
- ORCHESTRATION_TASK_SUMMARY_FIELDS gains "block-reason" + "no-op-count"
- SessionState gains blockReason?: string + noOpCount?: number
- project_states adds session_block_reason + session_no_op_count columns

Pipeline:
- control-fast-state.parseSession projects kebab-case → camelCase
- desktop pusher payload + runtime-state route + persistSessionIfNewer
  all carry the new fields
- /api/control/route + /api/control/stream re-emit them to React

Consumers:
- session-state.ts derivations prefer structured fields, fall back to
  content-sniffing for pre-2026-06-08 sessions
- autopilot-needs-fire bash guard reads block-reason + no-op-count
  directly; same fallbacks active
- agent-hook-bridge + fleetcrown-daemon handoff templates and the
  blocker_create SPACE prompt now instruct agents to emit the fields

Memory of why this exists: OC ran 21 no-op turns (~60k tokens) in an
hour because three layers parsed the agent's intent from free text
with different rules. Phase 2 (daemon owns the should-fire decision)
follows; bash guard's content-sniff fallbacks live until every agent
has rotated through the new template.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-08 15:50:30 +02:00
Mao Nakamoto deda43539b fix(desktop): make remote zellij control reliable fleet-runner-v0.7.9 2026-06-08 13:12:22 +02:00
Mao Nakamoto 964b1d67f4 fix(desktop): detect user-installed agent CLIs fleet-runner-v0.7.8 2026-06-08 12:23:45 +02:00
Mao Nakamoto 40cbf877d4 fix(desktop): push rich runtime snapshots fleet-runner-v0.7.7 2026-06-08 11:52:28 +02:00
Mao Nakamoto 948934158a feat(desktop): v0.7.6 remote command control fleet-runner-v0.7.6 2026-06-08 09:16:13 +02:00
Mao Nakamoto 797fa998e7 fix(control): repair local project sync and desktop command draining 2026-06-08 09:09:21 +02:00
Mao Nakamoto f586e93486 feat(site): /releases page + footer-version pill (user ask)
User asked: 'I really want you to put the version number and changelog
when you do releases somewhere on the site for transparency and context.'

NEW src/config/changelog.ts:
  SSOT for release history. One ReleaseEntry per fleet-runner-vX.Y.Z tag.
  Fields: version, tag, date (ISO 8601 UTC), highlights[] (user-facing
  bullets in plain English, not commit-message slang), breaking[] (compat
  breaks the user must read before upgrading), notes (optional paragraph
  on WHY this release matters).
  Currently populated with v0.4.4 → v0.7.4 (9 releases).
  Add a new entry per release going forward.

NEW src/app/releases/page.tsx (public marketing page):
  /releases — vertical timeline of every release. Newest first, current
  version pill on top entry. Each card: version + date + notes paragraph +
  'What changed' bullets + 'Breaking' bullets (status-warning color) +
  link to the GitHub release tag for binaries + raw asset list.
  Footer paragraph explains the auto-update-on-.deb-Linux caveat
  (electron-updater can't escalate sudo from userspace; manual dpkg -i
  required until task #48 — apt repo — ships).

UPDATED src/components/public/PublicFooter.tsx:
  • Added 'Releases' link to the Product group → /releases
  • Version pill at bottom-right is now Link to /releases, sourcing the
    string from CURRENT_RELEASE.version. The pre-this-commit value was
    a stale hardcoded 'v0.4.0' from months ago — exactly the
    'transparency' gap the user called out.

UPDATED src/app/globals.css @layer components:
  • .ui-public-badge-current (accent-colored 'Current' pill)
  • .ui-public-release-entry (rounded card per release)
  • .ui-public-release-version, .ui-public-release-date,
    .ui-public-release-notes, .ui-public-release-section-heading,
    .ui-public-release-section-heading-breaking, .ui-public-release-list

Adding a new release going forward:
  1. Append entry to FLEET_RUNNER_RELEASES (newest first) in
     src/config/changelog.ts
  2. The footer + /releases page auto-update on next Vercel deploy
  3. (Optional) commit message can stay focused on code; the user-facing
     'why' lives in the notes field of the changelog entry instead

tsc clean, 19/19 control-presenter tests pass.

Next: permanent fix for the .deb auto-update problem. Two real options:
  (a) Self-hosted apt repo at https://fleetcrown.vercel.app/apt/ with
      GPG-signed Packages — user does `apt update && apt upgrade`
      with their normal package manager, no Fleet-Runner-specific UX.
  (b) Switch Fleet Runner desktop to ship an in-app 'update available'
      banner showing the exact dpkg -i command + Copy button when
      electron-updater detects newer version but can't apply it.

(b) ships in one desktop release; (a) is the durable answer for Linux
users + sets up the path for self-host customers. Going to do (b) now,
plan (a) as a real follow-up.
fleet-runner-v0.7.5
2026-06-07 21:18:39 +02:00
Mao Nakamoto 152c8e9493 feat(db): bootstrap drizzle.__drizzle_migrations ledger (task #57)
Pre-this-commit, the Hetzner DB had ALL 26 historical migrations applied
(via drizzle-kit push during the v0.6 cutover, task #15) but ZERO rows in
drizzle.__drizzle_migrations because push doesn't write the ledger. As a
result drizzle-kit migrate would have tried to re-apply every migration
from scratch on its first run — failing on the first CREATE TABLE for an
already-existing table, OR worse, silently producing drift if any IF NOT
EXISTS / IF EXISTS guards saved the run.

This commit closes that gap permanently.

NEW scripts/db/bootstrap-migration-ledger.ts (175 lines):
  Reads all drizzle/NNNN_*.sql files. Computes sha256 of each (drizzle's
  canonical hash format). Modes:
    --dry-run (default)  Print the SQL it would apply
    --emit-sql           Print to stdout (pipe to psql)
    --write-journal      Update drizzle/meta/_journal.json locally
    --apply              Run against DATABASE_URL via psql -f
  Idempotent (uses ON CONFLICT DO NOTHING). Safe to re-run.

APPLIED to prod (postgresqlbridge.orangecat.ch):
  CREATE SCHEMA IF NOT EXISTS drizzle;
  CREATE TABLE IF NOT EXISTS drizzle.__drizzle_migrations (id, hash, created_at);
  CREATE UNIQUE INDEX __drizzle_migrations_hash_idx ON (hash);
  INSERT one row per migration (26 total) with computed sha256.
  Verified: SELECT count(*) FROM drizzle.__drizzle_migrations → 26.

WROTE drizzle/meta/_journal.json:
  26 entries, monotonic 'when' timestamps starting 2026-01-01.
  Future 'drizzle-kit generate' calls will append entries on top;
  'drizzle-kit migrate' will see existing entries' hashes match the
  ledger and skip them, applying only new migrations.

GOING FORWARD:
  Schema changes:  edit src/db/schema/*.ts → drizzle-kit generate → review
                   the new drizzle/NNNN_*.sql → drizzle-kit migrate to apply.
  No more direct 'drizzle-kit push' to prod (kept available for dev DBs).
  No more manual 'psql -f drizzle/NNNN_*.sql' shenanigans.

Tech debt this resolves:
  - Drift detection: works now. drizzle-kit migrate exits 0 if and only
    if the ledger matches the file hashes.
  - CI: future deploy pipelines can run drizzle-kit migrate as a step
    and have confidence in the result.
  - Team scaling: someone other than me can apply migrations without
    'how does this DB actually get migrated' tribal knowledge.

Verified: tsc clean, 19/19 control-presenter tests pass. Prod DB
unaffected outside the new drizzle schema.
2026-06-07 19:42:19 +02:00
Mao Nakamoto f3ae874ced feat(observability): /api/metrics — operator dashboard, 0 new deps
The architecture discussion called out 'no metrics, no traces, no alerts'
as a real gap. Pre-this-commit, when something broke we had two signals:
console.warn lines that hopefully landed in Vercel logs, and the
debug_logs table that 12 routes write to (others use console). Counting
'how many dispatches in the last hour' or 'what's the error rate' was
not possible without writing the SQL by hand against prod.

This commit ships a JSON metrics endpoint built entirely on existing
tables — NO new infrastructure (no Prometheus, no OpenTelemetry, no
metrics_* table, no new deps). The signals operators actually want are
all already in the operational tables; aggregate them on demand.

NEW src/db/queries/metrics.ts (177 lines):
  getDispatchMetrics(userId) → pending_commands: total24h, failed24h,
                                pending, avgLatencyMs
  getRunMetrics(userId)      → orchestration_runs: total24h + outcome map
  getErrorLogMetrics()       → debug_logs: totalErrors24h + bySource map
                                (system-wide — debug_logs has no user_id)
  getTokenMetrics(userId)    → agent_tokens: total + byLabel map
                                (spot the next leak before it hits 10 rows)
  getDaemonMetrics(userId)   → runtime_snapshots: lastSeenAt, secondsAgo
  getProjectMetrics(userId)  → user_projects: active, inactive, total

NEW src/app/api/metrics/route.ts:
  GET /api/metrics → 6 parallel queries, returns a JSON snapshot.
  Auth-gated via getSessionUserId; 401 when unauthenticated.
  Cache-Control: no-store (real-time by design).
  ~50ms on healthy DB.

Why JSON not Prometheus text format: no scraper to feed. Add ?format=prom
later if we ever wire a scraper.

Why 24h window hardcoded: operators ask 'what happened today,' not
'what's the 99th percentile latency over the last week.' Premature
parameterization.

Cost of this approach: every /api/metrics hit runs 6 queries — fine for
operator on-demand use, would NOT scale to a per-second scraper. That's
the tradeoff we accept for zero new infra.

Verified: tsc clean (both web + desktop), 19/19 control-presenter tests.

Next: bootstrap the drizzle migration ledger so schema drift becomes
visible (task #57), and the deferred audit items (#56).
2026-06-07 19:18:09 +02:00
Mao Nakamoto d437a962e6 feat(palette): add project entries to Cmd-K
The command palette had nav + agent prompts + templates but no PROJECTS.
For a fleet-management product the most common Cmd-K intent is 'jump
to project X' — that wasn't possible. Now it is.

Each active user-project becomes a PaletteEntry with kind="project":
  - label = project name
  - sub = 'Project · <dirPath>'
  - icon = FolderKanban (lucide)
  - href = /control?focus=<name> (existing deep-link handler)

Projects render at the TOP of the default list (before nav), because
this is the highest-frequency use of the palette. The existing fuzzy
match works as-is — typing 'fl' surfaces FleetCrown.

Fetched lazily: useFetch('/api/user-projects') only fires while the
palette is open. Closed palette = zero network cost.

tsc clean, 19/19 control-presenter tests pass.

Linear-style Cmd-K parity: navigation ✓, agent prompts ✓, templates ✓,
PROJECTS ✓. Still missing: per-project quick-dispatch actions ('send
next-best to FleetCrown'), agent quick-switch ('switch to Codex'). Those
are deeper UX moves that touch the dispatch path — separate pass when
the underlying flow is hardened.
2026-06-07 18:47:14 +02:00
Mao Nakamoto 9ada0fbadf refactor(terminals): Port 2 — TerminalAdapter, Zellij as first impl
Mirror of Port 1 (AgentAdapter) — same architectural move applied to
the terminal-multiplexer layer. Pre-this-commit, src/lib/zellij.ts was
263 lines of hardcoded `zellij action ...` shellouts. Supporting tmux
or screen would have meant a sprawling code-search-and-replace across
15 call sites.

NEW STRUCTURE — src/lib/terminals/:
  types.ts      TerminalAdapter interface: detectAvailable, listOpenTabs,
                getActiveTab, focusTab, injectText, sendRawKey, dumpScreen,
                isUserTyping
  zellij.ts     The full Zellij implementation behind the adapter —
                multi-session-aware, focus-dance HOF, ZSH typing-hook
                detection, ANSI-stripped dump-screen
  index.ts      ALL_TERMINALS = [zellijAdapter], findTerminal(id),
                activeTerminal() — picks first detectAvailable=true

ADDING A NEW MULTIPLEXER:
  1. Write src/lib/terminals/tmux.ts exporting tmuxAdapter: TerminalAdapter
  2. Add it to ALL_TERMINALS in index.ts
  Done. The 15 call sites importing from @/lib/zellij keep working
  unchanged (they go through the compat shim that delegates to whichever
  adapter is active).

zellij.ts (263 → 57 lines): kept as a thin compat shim re-exporting the
historical function names (getZellijTabs, injectIntoTab, peekTab, etc.).
Existing consumers in:
  - src/app/api/orchestration/run/route.ts
  - src/app/api/control/{focus-tab,switch-agent,agent,stream}/route.ts
  - src/app/api/control/route.ts
  - src/app/api/project/{commit,clear-context}/route.ts
  - src/lib/agents/{claude,grok,gemini,cursor}.ts (launch-command builders)
  - src/lib/git-state.ts
  - src/lib/orchestration/runners/openclaw.ts
  - desktop/src/main/poller.ts
…all keep working without edits. Migration to direct @/lib/terminals
imports happens incrementally as those files are touched for other
reasons.

VERIFIED: tsc --noEmit clean on both web + desktop; 19/19 control-
presenter tests pass; no behavior change.

The two ports together (#58 + #59) deliver the strategic goal: 'we don't
own the model OR the terminal, but both are first-class plug-ins to our
coordination layer.' Adding a new agent OR a new multiplexer is now ONE
new file plus one line in the corresponding index.

Next: Port 3 — command palette (Cmd-K).
2026-06-07 17:07:23 +02:00
Mao Nakamoto 56065e7e1b refactor(agents): Port 1 — AgentAdapter, one file per agent
The strategic move from the architecture discussion: FleetCrown's value
isn't owning the model, it's being the COORDINATION LAYER where any
model plugs in. Pre-this-commit, agent-registry.ts mixed data + behavior
across 427 lines, with per-agent switch statements in buildAgentOption-
LaunchCommand and per-agent functions for availability detection.
Adding a new agent (Cline, Aider, opencode, etc.) meant hunting through
5+ files.

NEW STRUCTURE — src/lib/agents/:
  types.ts       AgentAdapter interface + AgentCapabilities + runtime config
  helpers.ts     commandExistsInPath, parseTomlStringField, dedupeStrings
                 (shared across adapters)
  claude.ts      Anthropic CLI — full capabilities, hooks-based activity
  codex.ts       OpenAI CLI — manual prompts, model from ~/.codex/config.toml
  grok.ts        x.ai CLI — native session log under ~/.grok/sessions
  gemini.ts      Google CLI — model via -m flag, no persistent config
  cursor.ts      Cursor 'agent' CLI — strict detection (version regex + path heuristic)
  openclaw.ts    FleetCrown bundled gateway agent (not user-switchable)
  index.ts       ALL_ADAPTERS = [claude, grok, cursor, codex, openclaw, gemini]
                 findAdapter(id), effectiveDefaultModel, effectiveModelSuggestions

ADDING A NEW AGENT:
  1. Write src/lib/agents/newagent.ts exporting newagentAdapter: AgentAdapter
  2. Import + add it to ALL_ADAPTERS in index.ts
  Done. No edits to agent-registry.ts. No edits to api/control. No edits
  to UI switch statements. The catalog, the launcher, the availability
  badge, the install button all read from the adapter automatically.

agent-registry.ts (427 → 160 lines): kept as a thin compat shim that
maps the historical AgentRegistryEntry shape to the new adapters via
entryFromAdapter. All existing consumers (api/control, agent-catalog,
control-presenter, etc.) keep working unchanged. Long-term they should
migrate to importing from @/lib/agents directly; this shim stays until
that's complete.

Verified: tsc --noEmit clean, 19/19 control-presenter tests pass,
zero eslint issues. No behavior change for users.

Next: Port 2 (TerminalAdapter — same treatment for src/lib/zellij.ts
to enable tmux/screen/browser-shell plug-ins).
2026-06-07 17:02:42 +02:00
Mao Nakamoto 8604d97a69 feat(desktop): v0.7.4 — Phase 1, delete bundled renderer + dead IPC
ARCHITECTURAL CLEANUP, first-principles pass per the design discussion.

PROBLEM:
Pre-0.7.4 Fleet Runner shipped TWO parallel UIs:
  1. The Next.js app at fleetcrown.vercel.app (the real UI, full feature
     set, accessible from any browser, phone, or workstation)
  2. A 407-line bundled renderer at desktop/src/renderer/ that read
     agent-projects.conf, talked to IPC for project state, and never
     reached parity with /control

This violated:
  - Ground truth #2 (one source of truth — two UIs is two truths)
  - Ground truth #3 (design for change — every feature shipped twice)
  - Ground truth #5 (complexity compounds — 2,135 LoC of dead/dual code)

The split also produced the v0.7.0 disaster, where the bundled renderer
became the default boot target and users saw 'YOUR MACHINES. YOUR AGENTS.'
+ '0 projects' + 'Sync error: Failed to fetch' — a half-working stub
instead of their actual /control page.

SOLUTION:
Fleet Runner is now what it really should be: a native Electron wrapper
around the cloud /control UI, with real local-execution services
(poller/pusher/watcher/peek) running in the main process. Same category
as Slack, Linear, Notion, Discord desktop apps.

DELETED:
  - desktop/src/renderer/ (407 lines App.tsx, main.tsx, globals.css,
    index.html — the bundled renderer that never reached parity)
  - desktop/src/main/runtime.ts (224 lines — only the deleted renderer
    called these IPC handlers; getLocalRuntimeStatus, getProjects,
    dispatchIntent, getCurrentState are gone)
  - electron.vite.config.ts renderer block (no more renderer build)
  - The USE_WEB_SHELL conditional throughout main/index.ts — there's
    only one mode now: web shell.
  - loadBundledRenderer() function
  - did-fail-load → loadBundledRenderer fallback (replaced with proper
    branded offline page that has 'Try again' button)
  - IPC handlers: ping, get-runtime-status, get-projects, dispatch-intent,
    get-current-state, probe-cloud, switch-to-cloud
  - Preload bridge methods for the above
  - FleetRunnerBridge type entries for the above
  - Dependencies no longer needed: @vitejs/plugin-react, autoprefixer,
    postcss, react, react-dom, tailwindcss, @types/react, @types/react-dom

ADDED:
  - reload-web-shell IPC handler (offline page → main → loadURL retry)
  - reloadWebShell on preload + FleetRunnerBridge type
  - Improved offline page copy: 'cloud surface is offline, your local
    agents and Zellij tabs are running regardless' — honest about what's
    affected, accurate about what isn't

NET: 2,135 lines removed, 136 added. Build still works: out/main 199 KB,
out/preload 2.5 KB. Both tsc --noEmit clean (web + desktop). No behavior
change for users in the default path; the bundled-renderer escape hatch
that produced the broken v0.7.0 boot is gone for good.

Version bump 0.7.3 → 0.7.4. Auto-update pulls this on next launch.
2026-06-07 16:14:19 +02:00
Mao Nakamoto 3079780b10 fix(db): drop duplicate project_states trigger + cap event-stream-token leak
Live Hetzner DB inspection on 2026-06-07 surfaced two real defects.

BUG 1 — DUPLICATE NOTIFY TRIGGERS ON project_states
The table had two trigger sets firing on every INSERT/UPDATE:
  * fc_notify_project_states (correct, from migration 0022 — emits on
    the canonical 'fc:state' channel via fc_emit_change)
  * project_states_notify (legacy pre-rename — emits on 'fleetcrown_state'
    via fleetcrown_notify_project_state, which nothing listens to)

Every state push fired both, doubling bridge NOTIFY traffic + giving
every SSE subscriber two events to process for one change.

drizzle/0026_drop_legacy_project_states_trigger.sql: drops the legacy
trigger + its function. Applied directly to prod via psql (verified
before: 5 trigger rows; after: 3). Idempotent (IF EXISTS).

BUG 2 — TOKEN TABLE LEAKS ON EVERY BROWSER LOAD
/api/event-stream-token mints a fresh ck_* token on every call. The
file's own comment (lines 33-39) literally said 'we always mint a fresh
one regardless'. Result: my account had 10 stale event-stream rows over
36 hours, all live, no cleanup. At any user scale agent_tokens grows
unboundedly.

Fix (three parts):

  a. NEW src/db/queries/agent-tokens.ts: getReusableEventStreamToken
     returns the most-recent event-stream token if last_used_at < 7 days,
     reused as-is.
  b. /api/event-stream-token: try reuse first, mint only as fallback.
     Response now includes {reused: true|false} for telemetry.
  c. NEW src/db/queries/agent-tokens.ts: deleteStaleEventStreamTokens
     deletes event-stream tokens with last_used_at older than 30 days
     (never touches other labels — daemon tokens are persistent).
  d. NEW src/app/api/crons/prune-agent-tokens/route.ts: Vercel Cron at
     05:00 UTC daily runs the cleanup, logs result to debug_logs as a
     heartbeat.
  e. vercel.json: register the new cron path.

ONE-TIME CLEANUP (already applied to prod during inspection):
  DELETE FROM agent_tokens WHERE label='event-stream' AND id NOT IN (
    SELECT id FROM (most-recently-used event-stream row per user)
  )
  Result: 10 stale rows → 1 active token per user.

Both fixes are deploy-on-Vercel-push safe; the SQL is already on prod.
Vercel deploy picks up the new cron route + endpoint change.

DEFERRED (separate batch): bootstrap drizzle.__drizzle_migrations
ledger so future migrations are traceable. The schema arrived via
'drizzle-kit push' so the migrations table doesn't exist; not blocking
this round.
fleet-runner-v0.7.4
2026-06-07 15:53:18 +02:00
Mao Nakamoto c04bb464f1 fix(desktop): v0.7.3 — clear stale tokens on 401 + Cockpit title purge
Dogfooded v0.7.x today and hit two real bugs that kept the user stuck on
the broken bundled-renderer experience even with v0.7.2 binaries live.

ROOT CAUSE 1 — Permanently-stuck dead tokens.
The pusher and poller both stop on 401/403 but DID NOT delete the stale
token file. FleetRunnerAutoMint's bail check is 'if (existing) return',
so a user with a dead token (revoked, expired, server-side row gone) is
permanently locked offline: the daemon never recovers, no fresh token
gets minted, /control reads 'Daemon offline' forever.

Fix in BOTH desktop/src/main/{pusher,poller}.ts: on 401/403, call
clearToken() before stopping. Next time FleetRunnerAutoMint mounts in
/control (next page navigation or relaunch), it sees no existing token,
mints a fresh one from the user's signed-in session cookie, saves it
via IPC. saveToken() already restarts the poller + pusher, so recovery
is automatic from there.

Verified on my own machine: my saved token from 2026-06-06 14:24 is
returning 401 against /api/control/runtime-state (server doesn't
recognize it). Pre-fix: every subsequent launch reads the same dead
token, pusher 401s once, gives up. Post-fix: pusher 401s, deletes
file, gives up; next /control load triggers auto-mint to fresh token.

ROOT CAUSE 2 — Stale 'Cockpit Fleet Runner' window title.
Caught earlier this session: desktop/src/renderer/index.html still had
the pre-rename title hardcoded. Window manager picks that up before
the loaded /control page's title swaps it in, so taskbar showed
'Cockpit Fleet Runner' for a beat on every launch and as a permanent
state on bundled-renderer fallback. Already fixed in source, ships
with this release.

Version bump 0.7.2 → 0.7.3. Both bugs only affect FRESH desktop
binaries; v0.7.0 / v0.7.1 / v0.7.2 are unaffected at the source level
because the bugs were structural-in-shipping-code. After this commit
lands + CI builds + mirror finishes, electron-updater on v0.7.0+
installs will pick up v0.7.3 on next launch.
2026-06-07 14:22:59 +02:00
Mao Nakamoto 6fafd2233d fix(desktop): purge stale 'Cockpit' branding from renderer index.html
desktop/src/renderer/index.html still had <title>Cockpit Fleet Runner</title>
from before the FleetCrown rename. Caught it dogfooding v0.7.x today — the
running v0.7.0 install shows up in the window list as 'Cockpit Fleet Runner'
because the OS WM reads the document title before the web-shell loadURL
swaps it.

Impact:
  - v0.7.0 users: see 'Cockpit Fleet Runner' in their taskbar / alt-tab list
  - v0.7.2+ users in WEB-SHELL mode (default): never see it — the loaded
    page's title 'Control — FleetCrown' takes over within ms of paint
  - v0.7.2+ users in LOCAL mode (FLEETCROWN_WEB_URL=local) or on a cloud
    fallback: would still see it
  - User in dogfood today saw 'Cockpit Fleet Runner' in xdotool output and
    asked what was up

Title is now 'Fleet Runner'. Renderer-bundled fallback gets the same
branding as the cloud-loaded primary surface.

This is source-only — doesn't affect the already-shipped v0.7.1 / v0.7.2
binaries. Ships with the next desktop release (v0.7.3 or whenever).
fleet-runner-v0.7.3
2026-06-07 14:15:05 +02:00
Mao Nakamoto 8cf1de3774 refactor(quality): batch 2c — timing constants + phase-dot-class SSOT
Audit honorable mentions, both small and low-risk:

1. Refresh-after-action durations consolidated in constants/timings.ts.
   Pre-fix: 500/700/1500/3000ms inlined across use-control-data.ts and
   ZellijLivePanel.tsx with no documented intent. Now four named
   constants:
     REFRESH_AFTER_DISPATCH_MS  = 500   (inject → re-fetch)
     REFRESH_AFTER_TAB_ACTION_MS = 700  (close-tab, tab-inject)
     REFRESH_AFTER_LAUNCH_MS    = 1500  (full project launch)
     AGENT_COLD_START_MS        = 3000  (wait between launch + 1st prompt)
   Each has a one-paragraph rationale so future tuning has context.

2. PHASE_DOT_CLASS exported from control-presenter.ts.
   Pre-fix: ProjectOperationsView.tsx had a 9-line ternary chain mapping
   phase → Tailwind dot class. The ControlPhase enum and its visual
   mapping lived in different files and couldn't be type-checked
   against each other. Now: Record<ControlPhase, string> — adding a
   new phase value forces an explicit color choice (the type errors
   without one). ProjectOperationsView.tsx drops to one line:
     const dotClass = PHASE_DOT_CLASS[snapshot.phase];

19/19 control-presenter tests pass; tsc --noEmit clean.
2026-06-07 13:50:01 +02:00
Mao Nakamoto f7c555048b refactor(quality): batch 2b — extract zellij focus-dance HOF
Audit item #3: sendRawKey, injectIntoTab, and peekTab in src/lib/zellij.ts
each ran the same 8-line dance:
  1. findSessionForTab → session
  2. getCurrentTab(session) → originalTab
  3. exec('zellij [--session X] action go-to-tab-name <tab>')
  4. waitForTabFocus or throw
  5. do the per-function thing
  6. if originalTab !== tab: exec('zellij [--session X] action go-to-tab-name <originalTab>')

Plus the 'session ? `zellij --session X action …` : `zellij action …`'
ternary appeared 8 times across the file.

Two helpers collapse this:
  - zellijCmd(session, ...args): builds the command string with or
    without --session. The 8 inline ternaries become one helper.
  - withFocusedTab(tab, fn): focus → run fn(session) → restore. fn
    is called with the resolved session so it can keep using zellijCmd
    for follow-up actions.

The three public functions (sendRawKey, injectIntoTab, peekTab) drop
from ~20 lines each to 3-10 lines each. The dance now lives in ONE
place — if Zellij grows a 'write to non-focused pane' API we change
one HOF, not three call sites.

Behavior preserved:
  - Same focus + restore logic
  - Same 1s wait timeout, same throw on focus failure
  - Same 0.1s sleep after write-chars before pressing Enter
  - Same try/finally for tmp-file unlink in peekTab
  - Same best-effort restore on error
Verification: 19/19 control-presenter tests still pass; both web and
desktop tsc --noEmit clean.

zellij.ts: 280 → 263 lines (6% smaller, much more readable).
2026-06-06 15:42:01 +02:00
Mao Nakamoto ec866abcb3 refactor(quality): batch 2a — extract fetchAllGitStates + profile-match from /api/control god route
Audit item #6: api/control/route.ts was a 537-line god route mixing
transport, slow-cache, git-shell, profile fuzzy-match, lifecycle event
derivation, and DB writeback. First extraction pass: pull the two pure
data-transformation chunks into lib/ where they belong.

NEW src/lib/git-state.ts — fetchAllGitStates(dirs)
  The single-bash-invocation git probe (one fork, N background jobs per
  dir, parallel wait). Returns Map<dir, GitState>. Behavior unchanged.
  Future consumers (/projects page, cron heatmap) can call it without
  importing the /control route.

NEW src/lib/project-profile-match.ts — rowToProfile + matchProfile +
  matchProfileById + resolveAutoInjectOverride
  The three near-identical fuzzy matchers were inline in route.ts with
  subtle differences: matchProfile did bidirectional substring matches,
  resolveAutoInjectOverride only exact-normalized. That meant a user
  with slightly-different tab spelling could see their profile attach
  but the autopilot override silently miss — "why isn't sleep mode
  firing for this project even though it's clearly set?"
  Consolidated normalizeName() helper inside the module; resolve uses
  exact-normalized (intentional, matches the legacy precedent) but
  shares the same string-prep logic with matchProfile so the two can't
  drift. matchProfile still does the broader bidirectional substring
  search it always did. No behavior change at the entry points.

Cleanup:
  - Drop now-unused imports from route.ts: path, AUTO_INJECT_MODE_VALUES,
    type AutoInjectMode, exec + promisify + execAsync local.
  - Drop the 'Profile matching' section divider comment (the file's
    section headers are stale anyway; will rewrite when batch 2b lands).

Size: route.ts 537 → 407 lines (24% smaller). Remaining batch 2 work:
  - persistProjectSessionIfNewer + appendProjectDevLog writeback block
    (lines 282-308 in current file) → lib/control-session-writeback.ts
  - Inline tab/dir/project assembly inside the projects.map → split into
    a buildProjectState helper

19/19 control-presenter tests still pass; tsc --noEmit clean both ways.
2026-06-06 15:37:43 +02:00
Mao Nakamoto d7dfe0bb5c refactor(quality): batch 1 — daemon constants, token-store, ansi-strip, agent-list SSOT
Code-quality-reviewer audit identified 10 SSOT/DRY/SoC violations across
/control + dispatch + auth. This commit handles the four lowest-risk ones
(plus the design-token violations I introduced yesterday in PeekTabDrawer).
No behavior change intended; all 19 control-presenter tests + 89 home/
tests pass; both desktop and web tsc --noEmit clean.

1. NEW src/lib/constants/daemon.ts
   Three daemon timing numbers (heartbeat cadence, offline threshold,
   long-poll wait) had to agree across desktop pusher, web ControlPanel,
   and /api/control/commands but were edited independently. The pusher
   source comment even said "the 90s threshold is too aggressive for
   this 5min cadence" — UI briefly flickered "offline" between
   heartbeats. Now: heartbeat is the input, threshold is heartbeat × 1.5
   + 30s grace (auto-scales), long-poll is shared.
   Sites updated: ControlPanel.tsx, desktop pusher.ts + poller.ts,
   api/control/commands/route.ts.

2. NEW desktop/src/main/token-store.ts
   ~/.config/fleetcrown/fleet-runner-token + loadToken read-and-trim was
   copy-pasted across poller.ts, pusher.ts, and three IPC handlers + the
   deep-link handler in index.ts (5 sites). A token-path rename would
   silently leave callers on the stale path. Now one module owns the
   path + load/save/clear with discriminated-result error handling.
   Eliminates 5 duplicate paths + 3 duplicate loadToken functions.

3. NEW src/lib/ansi.ts
   stripAnsi() — CSI + OSC regex was duplicated in zellij.ts's
   cleanZellijLines (CSI only — missed OSC title-set / hyperlink) AND
   peekTab (broader regex with both). cleanZellijLines now uses the
   broader function too, so future zellij output that includes OSC
   sequences won't quietly bleed escape codes into the parsed tab list.

4. api/control/route.ts: drop hardcoded ["claude","codex","gemini",
   "cursor","grok","openclaw"] in daemonAvailability — derive from
   listAgentRegistry() so adding a new agent in lib/agent-registry no
   longer requires also remembering to update this list. Was a real
   drift trap: 'openclaw' had been added to the registry but the
   availability map still listed it manually anyway.

5. Cross-OS tmp-file path: peekTab now uses os.tmpdir() instead of /tmp.
   Linux/mac behavior unchanged; this unblocks Windows builds (which the
   desktop pipeline ships .exe for) from writing to a path that doesn't
   exist on that platform.

6. Design-token cleanup (project CLAUDE.md four-layer rule):
   - PeekTabDrawer.tsx: replaced bg-[#0a0a0a] + text-[#FAF8F5] with new
     ui-control-terminal-frame / ui-control-terminal-surface classes
     in globals.css @layer components. My violation, my fix.
   - 4 sites of text-[9px] in control-* components → text-micro (10px
     token, slight 1px upsize is fine, brings them under SSOT).
   - money/page.tsx text-[10px] → text-micro (same).
   Final design-token audit: 0 violations across src/.

Audit issues remaining for future batches (higher-risk, multi-file):
  #1 ProjectState type derivation from Drizzle schema
  #3 zellij focus-dance HOF
  #5 collapse two dispatch entry points to one
  #6 split 537-line /api/control/route.ts god route
  #9 split useControlData into snapshot + form + mutations
2026-06-06 15:27:36 +02:00
Mao Nakamoto b73bb9a8d4 feat(desktop+web): v0.7.2 — peek tab contents from /control
The hardest UX gap in /control was: you saw your tab NAMES + state chips
('Working', 'Awaiting input') but never the actual screen content. To know
what the agent was saying you had to alt-tab into Zellij and find the
right tab. Web-shell users saw even less.

v0.7.2 closes that. Per-tab eye-icon button on /control workspaces table
opens a drawer that captures the live screen of that Zellij tab and renders
it as a static terminal frame (monospace, dark background, scrollable).
Auto-refresh toggle re-peeks every 3s for watching long-running agents
without permanently leaving the user on the peeked tab.

Mechanism (sub-200ms round-trip):
  1. ZellijLiveRows eye-button → setPeekTab(name)
  2. PeekTabDrawer mounts → window.fleetRunner.peekTab(name)
  3. preload → IPC peek-tab → main process
  4. src/lib/zellij.peekTab: save focus, go-to-tab-name, dump-screen to
     /tmp file, restore focus, read+strip ANSI, unlink temp
  5. Returns content → drawer renders in <pre>

Same focus-dance pattern as injectIntoTab (already in zellij.ts) — users
have accepted that disruption budget for remote dispatch, this reuses it.

Outside Fleet Runner the button is hidden (one-tick mount probe of
window.fleetRunner.peekTab). No degraded "button that always errors"
experience for browser users.

Also in this drop:
  - desktop bump 0.7.1 → 0.7.2 (auto-update will pull this on next launch)
  - control-presenter test: "cockpit" string was a leftover from the rename,
    failed CI on the v0.7.1 push; now compares to 'FleetCrown' as intended
  - ZellijLivePanel daemon-offline CTA now points to /releases/latest
    instead of the hardcoded fleet-runner-v0.7.0 tag (was pointing users
    at the broken bundled-renderer build)

Next: v0.7.3 cloud-fallback (browser-only users get peek via the command
queue → daemon → result table → SSE), v0.8 inline terminal column.
2026-06-06 14:54:46 +02:00
Mao Nakamoto d68ffbff24 fix(desktop): v0.7.1 — REVERT Phase C primary flip, web-shell default again
v0.7.0 shipped USE_WEB_SHELL=false; the bundled local renderer became
the boot target. User QA on 2026-06-06 launched the installed app and
saw:
  - '0 active projects' (renderer reads agent-projects.conf, NOT the
    cloud DB; user's actual FC projects invisible)
  - Dev-surface copy ('YOUR MACHINES. YOUR AGENTS. / BUILT FOR BUILDERS
    WHO RUN REAL FLEETS') that has no place in a customer build
  - 'Sync error: Failed to fetch' on the connect-to-cloud action

That's not the experience anyone should ship. The Phase C VISION
(local-first renderer with parity to /control) stands — it's
task #44, v0.7.1+ work, multi-day real build. Until that ships,
the default reverts to v0.6 behavior: Fleet Runner opens the
fleetcrown.vercel.app UI inside Electron. Same UI users know from
the browser, same projects, same dispatch, no surprise.

Cursor / Anthropic / Grok ship the same pattern at this stage.
Local-first renderer is the destination, not v0.7.0's reality.

Bundled renderer stays OPT-IN via FLEETCROWN_WEB_URL=local for
power-user dogfooding while parity work happens in the background.
desktop/package.json: 0.7.0 → 0.7.1. Existing v0.7.0 installs
auto-update on next launch (electron-updater wired since v0.3.0).
fleet-runner-v0.7.2
2026-06-06 14:28:44 +02:00
Mao Nakamoto 5902b612a4 ux(download): Linux defaults to .deb, AppImage as secondary
User report: clicking the Linux download CTA gives an AppImage that
KDE/KIO refuses to execute ('Aus Sicherheitsgründen ist es in diesem
Kontext nicht erlaubt'). The user has no idea what to do — dead end.

Flip: .deb becomes the primary Linux CTA. AppImage moves to secondary
for users on Arch/Fedora/immutable distros where .deb isn't right.
After-download instruction shows the one-line install + launch via
sudo dpkg, not chmod-and-pray.

KDE/KIO's policy refuses to execute any standalone binary that isn't
installed system-wide; .deb installed via dpkg goes through the
package manager and is never gated. .deb is also smaller (no
Chromium per-app sandbox payload) and gets a Start Menu entry +
desktop icon for free. For 90% of FleetCrown's likely user base
(Ubuntu/Debian/Mint/Pop) this Just Works.

The marketing footer 'AppImage / .deb' phrasing in the platform-
parity bullet stays — it documents what we ship, not what we
recommend.
fleet-runner-v0.7.1
2026-06-06 14:02:26 +02:00
Mao Nakamoto eb0cd0af43 ux(control): replace generic 'no workspace data' copy with actionable install links
User QA: cloud /control shows 'No live workspace data · The cloud
control plane needs your local daemon running and pushing state.
Start an agent workspace, then check the local connection in
Settings.' which is generic and dead-ends — the user has no idea
what to actually do.

Replaced with two concrete CTAs:
  - 'Download Fleet Runner (desktop app)' → v0.7.0 release page
  - 'Or run the bash daemon' → quickstart docs anchor
+ a one-liner explaining auto-mint flow so the install is one
click and 30s of waiting, not a doc treasure hunt.

The architecture is the v0.7 vision: Electron desktop owns local
execution, cloud is sync layer. This banner now reflects that
honestly — cloud literally can't see localhost Zellij without
something local pushing state, so the right UI is 'install the
local app' not 'why is this broken'.
2026-06-06 13:50:41 +02:00
Mao NakamotoandClaude Opus 4.7 e4753728dd feat(prompts): v2.1 — user-owned prompt library (schema + API + UI)
Pre-v2.1 the prompt library was 41 templates baked into
src/config/prompt-library.ts. Users couldn't add their own, pin to a
project, or capture successful ad-hoc dispatches. v2.1 is the
structural fix — each user can now create their own prompts that
merge with the FC defaults on /prompts.

Multi-disciplinary design (product · UX · engineer · prompt engineer):
- Product: prompts are repeatable work units; users need their own +
  per-project recipes. Library grows with use.
- UX: user-owned section above FC defaults; +New button opens an
  inline form (modal in v2.2 if needed); edit/delete on each card;
  scope toggle global vs project.
- Engineer: new prompts table (user_id, scope, project_id nullable,
  body, variables JSONB, tags, source, run_count, success_count).
  Migration applied to Hetzner.
- Prompt engineer: body supports {{name}} and {{name|default}}
  placeholders; parsed once at insert time into a variables[] array
  so v2.2's variables-at-run modal doesn't re-parse.

Shipped:
  + drizzle/0025_prompts.sql (applied to Hetzner)
  + src/db/schema/prompts.ts
  + src/db/queries/prompts.ts — parsePromptVariables, renderPromptBody,
    CRUD helpers, listPromptsForUser, listPromptsForProject
  + src/app/api/prompts/route.ts (GET list, POST create)
  + src/app/api/prompts/[id]/route.ts (GET, PATCH, DELETE soft)
  + src/components/prompts/UserPromptsSection.tsx — list + inline
    create / edit form with scope picker, tags, body textarea,
    variable-syntax hint
  ~ src/components/prompts/PromptLibraryClient.tsx — accepts
    optional userPrompts prop; renders UserPromptsSection above the
    FC-defaults grid
  ~ src/app/(app)/prompts/page.tsx — fetches user prompts via
    listPromptsForUser and passes to the client component

Roadmap noted in comments:
- v2.2: variables-at-run modal (quick-fill {{name}} placeholders
  before sending)
- v2.3: "Save as prompt" capture from /history rows
- v2.3: success-rate analytics from orchestration_runs.outcome
- v2.4: scheduled prompts (cron, integrates with the autonomous
  scheduler shipped in Change 5)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-06 13:47:31 +02:00
Mao Nakamoto c5b7c267de fix(today): coerce Date params to ISO before raw sql FILTER (fixes server crash)
Root cause of the /today crash captured by the diagnostic shipped one
commit ago. Drizzle's raw sql template interpolation calls .toString()
on Date params — Postgres rejects the JS default ('Sat Jun 06 2026
00:00:00 GMT+0000') as an unparseable timestamp. The non-template
builder helpers (gte/lte/eq) serialize Date correctly; only the raw
sql interpolation in count(*) FILTER (WHERE ...) clauses tripped.

Fix: convert dayStart/weekStart to ISO strings and cast in-SQL as
::timestamptz. /today renders again.

The per-step try/catch + onRequestError instrumentation that found
this can come out in a later cleanup; leaving them in for now in
case other server-component pages hit the same pattern.
2026-06-06 13:34:58 +02:00
Mao Nakamoto 709372ea47 diag(today): per-step try/catch + logDebug to localize the crash
/today has been crashing in prod with an opaque Server Components
render error. Client telemetry and onRequestError aren't surfacing a
useful stack. Wrap each upstream call (getCurrentUserName, requirePage
UserId, getUserProjects, getOrgProjects) in a 'step' helper that logs
to debug_logs with the failure site + truncated stack, then re-throws
so the error boundary still renders.

Next /today crash lands a row keyed by source='today/page' with the
step label that threw. Once we have the root cause and a fix, this
diagnostic scaffold can come back out.
2026-06-06 13:18:16 +02:00
Mao Nakamoto 99597e3eab ux(control): slim DaemonStatusBanner for users with existing projects
Pre-fix: even with N projects, the daemon-never-seen banner showed the
full two-card pitch (Start a new project + Install Fleet Runner). User
QA called it noise — they have a project; the 'start new' card is
redundant.

Now: when hasProjects=true AND daemonNeverSeen, banner shows ONLY the
'Install Fleet Runner' card with a single-line intro. The 'Start new'
pitch stays for empty-state users where the welcome cards aren't yet
visible.
2026-06-06 12:58:59 +02:00
Mao Nakamoto 3d397f4ece feat(observability): onRequestError logs full server stack + digest to debug_logs
Next.js prod strips error.message client-side, leaving only the digest
visible. vercel logs CLI doesn't reliably surface them from our local
env. onRequestError fires server-side on every uncaught render error;
logging digest + full message + stack to debug_logs gives a durable
correlation key the client-side telemetry can pair with.

Next /today crash will have a debug_logs row with the actual error.
2026-06-06 12:54:36 +02:00