This is the UI the user is asking to see live + the reflection fixes for direct terminal use (Cockpit tab showing correct agent).
Part of the approved zellij-control + terminal-reflection plan.
Extracted the branch logic from healReturningUserOnboarding into a
pure decideHealPatch() function in src/lib/onboarding-heal-decision.ts,
so it can be unit-tested without spinning up Postgres (the previous
location imported @/db/queries/* transitively, which fails at import
time without DATABASE_URL).
The I/O wrapper in onboarding-heal.ts now resolves projectCount and
suggested-username availability up front, then delegates the patch
decision to the pure function. Re-exports decideHealPatch + HealPatch
type so existing callers don't need to update import paths.
Test suite (npm run test:onboarding-heal) covers the six observable
branches:
- brand-new user → no heal
- returning user + free suggestion → both fields patched
- returning user + taken suggestion → onboardedAt only
- already-onboarded + valid username → no heal
- legacy migrated row (onboardedAt set, no username) → username only
- zero projects + onboardedAt set → still treated as returning
The never-throws contract on the I/O wrapper is verified by inspection
(try/catch wraps every await — there is no test-framework-friendly way
to inject a throw through the @/db import boundary without a real DB).
Finishes the Oracle migration plumbing started in ec6f423. Three pieces:
1. scripts/db/oracle-await-cutover.sh — polls
~/.config/cockpit/oracle-migration.env every 15s for ORACLE_HOST
(timeout 7200s by default), then runs oracle-cutover.sh with
SKIP_DUMP=1 once the IP is set. Lets the operator launch this
before creating the VM in the Oracle console; cutover fires
automatically the moment the public IP lands in the config.
2. scripts/db/oracle-cutover.sh — SKIP_DUMP=1 reuses an existing
pre-oracle-cutover.sql.gz instead of re-dumping prod, so the await
loop doesn't double-dump on every retry; env -u NODE_ENV wraps
`npm run build` and `vercel deploy`/`vercel redeploy` so the
ambient NODE_ENV=production from systemd or .env files can't
poison the build's mode resolution.
3. package.json — adds db:oracle-await alias.
Vendor-neutral DATABASE_URL helpers, dump/restore/sync tooling, and one-command
Oracle migration after a single console VM step. Publishes the studio-stack
thoughts article and hardens build (dynamic layout, resilient sitemap).
Co-authored-by: Cursor <cursoragent@cursor.com>
Control buried fleet state behind config metrics and only showed an open-tab count on cloud. Push the full Zellij tab list from the daemon, store it in runtime_snapshots, and lead the page with a workspace table showing agent, state, and current activity per tab.
Co-authored-by: Cursor <cursoragent@cursor.com>
Add @cockpit/agent init, server-side PIN enforcement for private APIs,
Postgres-backed cron jobs, daemon auto-continue sync, and cloud/local docs
so SaaS users get a clear path from browser signup to local dispatch.
Co-authored-by: Cursor <cursoragent@cursor.com>
After commit a12d2d9 closed the lifecycle pair across every adapter, the
detail field — the human-readable summary attached to each
orchestration_events row — had drifted across five emit sites into four
different formats:
• route.ts:354 ${intent.name} — ${message} (em-dash)
• route.ts:436 openclaw worker start failed: ${msg} (verbose prefix)
• inject.ts:225 ${promptLabel} — ${result.error} (em-dash)
• worker.ts:72-3 ${intent} done | ${intent}: ${error} (split formats)
• worker.ts:88 ${error.message} (no intent context)
Downstream chart/list queries would need to grep multiple separator
formats and strip multiple prefix variants. Unified to one canonical
shape across all five sites:
success → "<intent_or_label>" (no trailing " done")
failure → "<intent_or_label>: <error>" (single-colon separator)
Operators can now split on the first colon to extract the intent label,
or pattern-match `:.*` to extract the error. The verbose "openclaw
worker start failed:" prefix is gone — the `source: 'api-orchestration'`
column already carries that context.
No schema changes. detail column is still truncated to 400 chars. The
existing task_started emits (which only carry the intent name with no
error) were already consistent and untouched.
tsc + eslint + build clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The codex/gemini branch in /api/orchestration/run emits task_started at
line ~296 before injectIntoTab. The openclaw branch did not. So every
successful openclaw run was invisible in orchestration_events — only
its orchestration_runs row existed. Commit 9a0ac77 closed the worker-
start-failure pair (failed-to-spawn now emits task_failed), but the
happy path and the in-worker error path were both still silent.
Three coordinated changes:
1. Route emits task_started before scheduleOpenClawWorker — mirrors
the codex/gemini emit shape so dispatches across all adapters look
uniform in queries.
2. scheduleOpenClawWorker signature gains userId, encodes it into
the base64 payload. The worker needs user_id to write to
orchestration_events (NOT NULL constraint).
3. Worker emits task_completed (state:'done') or task_failed
(state:'error' or thrown) after its terminal updateOrchestrationRun.
Source field 'openclaw-worker' (vs 'api-orchestration' on the start
event) so timeline queries can tell which process emitted what.
After this, orchestration_events carries a full started/completed-or-
failed pair for every openclaw dispatch — same shape as codex/gemini —
and the single dispatch-success-rate query introduced in 9a0ac77 covers
every adapter without per-adapter casing.
tsc + eslint + build clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Vercel deploy failures previously sat in Error state silently until
someone ran `vercel ls`. The just-fixed CRON_SECRET-whitespace incident
(02c3c0d) is exactly this class: the build error existed for several
minutes before I noticed.
scripts/wait-for-vercel.sh polls vercel ls --prod for the most-recent
deployment, echoes each status transition, and exits:
0 on Ready
1 on Error / Failed / Canceled (prints `vercel inspect <url> --logs` hint)
2 on timeout (default 420s; tunable via env)
3 when the vercel CLI isn't installed
Gotcha I hit while writing this: `vercel ls` emits the deploy table to
STDERR, not stdout — `2>/dev/null` silently swallows every row. Use
`2>&1` to merge. Comment in the script flags it so the next person
debugging doesn't waste the same hour.
npm scripts:
wait:vercel direct invocation
ship git push origin main && wait:vercel
Use:
npm run ship # push and wait
bash scripts/wait-for-vercel.sh --quiet # exit code only
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Follow-up to the stale-Working defense (48fa2b6). Two related bugs:
1. ROOT CAUSE — agent-hook-lib.sh:write_inject_state used a naive printf
to interpolate $label and $key directly between JSON double quotes,
with zero escaping. Any user-supplied custom prompt containing
newlines, quotes, or backslashes broke the JSON so jq rejected it
in the daemon's parser. cpsat then fell back to "null", the
cleanup's outer guard skipped, and the file lingered indefinitely
leaking /tmp space (e.g. the AOZ sentinel from May 19 with a 1132-
byte multi-line prompt).
Fix: switch to `jq -Rs .` for both key and label — the same idiom
the daemon's execute_inject (cockpit-daemon.sh:258-262) already
uses. Newlines and quotes are now correctly escaped on every write.
2. LEGACY CLEANUP — even after fixing the writer, existing corrupted
files keep lingering since the parser still can't extract
startedAt. Added a belt-and-suspenders elif branch in the daemon
sweep: when the file exists but cpsat couldn't be parsed, fall
back to filesystem mtime; if older than 30 min, delete it. Files
that fail to parse never become live again, so a time-based sweep
is safe.
Both edits stay in scripts/agent-hook-lib.sh and scripts/cockpit-
daemon.sh — agent-hook-bridge.sh is untouched.
Companion to the UI staleness gate. Closes the leak at the source so
the sentinel doesn't keep getting re-pushed every 2s — fires the same
two checks the UI uses (session-mtime newer than prompt-start, OR
prompt older than 30min) inside _push_loop, deletes the file, and
clears cpk/cpl/cpsat so the JSON pushed to /api/control/runtime-state
carries nulls.
Verified against live state:
- OrangeCat: 3-day-old "echo ui-dispatch-test" prompt → cleared
after daemon restart (DB row's current_prompt_started_at went
null within one push interval).
- revamp-it: 30-min-old "Auto: next_best" → cleared on next push.
Companion to:
fix(control): stale "Working" defense — gate currentPrompt by
session signals + time
Cursor's audit caught this — the script committed in e33cd22 hardcoded
the live Neon `neondb_owner` password and a specific NEON_USER_ID.
Repo is private so blast radius is limited to anyone with read access,
but the value sits in git history forever and would leak immediately
if the repo were ever open-sourced or accidentally made public.
Refactor: all connection strings + user IDs now read from env vars.
LOCAL_DATABASE_URL / NEON_DATABASE_URL / NEON_USER_ID are required
(with a sensible local default for the source URL); script bails with
a clear hint if NEON_DATABASE_URL_DIRECT-style resolution finds
nothing. Matches drizzle.config.ts's existing env-var pattern.
ACTION REQUIRED (separate from this commit, your action on Neon):
• Rotate the `neondb_owner` password on the cockpit project via
neon.tech dashboard or `neonctl roles reset-password`. The OLD
password lives in commit e33cd22 forever; only a rotation kills it.
• Update Vercel env vars (DATABASE_URL + NEON_DATABASE_URL_DIRECT)
+ your local .env.local with the new password.
Bash syntax clean.
User reported cockpitapp.vercel.app/control still showing 'Local daemon
offline last seen Xm ago' even though the daemon is alive and the
FORCE_REMOTE fix landed yesterday.
Root cause: _push_loop only POSTs to /api/control/runtime-state when
the state hash changes. Between agent actions, state is stable for
minutes, so no push fires. The cloud UI's daemonOffline threshold is
90 s (src/components/control/ControlPanel.tsx:110). Idle daemon →
push gap > 90 s → UI permanently flagged offline.
Added a heartbeat: even when the hash is unchanged, force a push
every DAEMON_HEARTBEAT_S (default 60 s, env-overridable). That stays
comfortably under the 90 s threshold with one missed-push slack.
Pushes on actual state change still fire immediately (the OR
condition runs first). Net cost: 1 push/min from a healthy daemon
instead of 0 — negligible vs the inject claim-loop frequency.
Bash syntax clean. Will take effect after daemon restart on this
machine.
Yesterday's session diagnosed a silent trap: cockpit-daemon.sh's
_base_url() prefers local-when-reachable, so a user running both
cockpit-app systemd on localhost:3000 AND $COCKPIT_BASE_URL pointed
at https://cockpitapp.vercel.app silently polls local, ignoring every
dispatch from the production /control page. The fix on the user's
machine was a one-line daemon.env edit (DAEMON_FORCE_REMOTE=1) — but
nothing in the script tells them they're in this state.
Added a startup-time warning in _init_base_url: when the daemon picks
LOCAL but $COCKPIT_BASE_URL is a non-localhost URL, three log lines
fire explaining the trap and the fix. Stays silent for genuine dev
setups ($COCKPIT_BASE_URL pointing at localhost or 127.0.0.1) so it
doesn't cry wolf.
Bash syntax clean. No behavior change — same routing logic, just a
diagnostic log when the trap configuration is detected.
Each home/ module ships an inline test suite (state/decide/projects/
render/emit/log/watcher/worker — 76 tests total as of 00058f9), but
running them required eight separate npx tsx invocations. Added
scripts/test-home.sh that chains them in a stable order, captures
each suite's output, parses the N/M passed footer, and aggregates a
total at the end. Wired as 'npm run test:home' alongside the existing
smoke and check:design scripts.
The footer regex matches '^N/M' rather than 'N/M passed' specifically
because render.ts prints '12/12 intents render' — most suites use
'passed' but the loose anchor catches both shapes. Exits non-zero on
the first suite that fails (set -euo pipefail + a tracked total_fail
counter for the summary line).
Output of npm run test:home ends with:
✓ 76 total tests passed across 8 home/ self-test suites
No code change in home/. tsc unaffected.
The cancelledRunIds → user_abort relabel I shipped in e81d9ee matches
on event.runId. But the chain that produces worker.finished didn't
preserve the runId:
1. home/worker.ts:executeDispatch injected the prompt but never
wrote the /tmp/<slug>-run-<tab> sentinel that the stop hook reads
to learn the runId. Cloud's cockpit-daemon.sh writes it; the
local worker had been silently skipping it.
2. scripts/agent-hook-bridge.sh:emit_worker_finished didn't include
runId on the event at all — the JSON template only had
{v,id,ts,kind,project,outcome,durationMs,handoff}. It DID read
the sentinel for duration_ms, then threw the runId on the floor.
Net effect: every user-cancelled run was missing runId in
worker.finished, the relabel never matched, and the cancel
was recorded as whatever infer_outcome_v1 inferred (typically
"partial"). e81d9ee was working in tests but dead in production.
Fix:
• home/worker.ts: write event.runId to the sentinel before
injectIntoTab. Wrapped in try/catch since failure to write a /tmp
file shouldn't block dispatch — degrades gracefully to runId-less
worker.finished.
• scripts/agent-hook-bridge.sh: read the sentinel into run_id
alongside the existing duration_ms read, build a separate
{runId:...} object via jq, and merge it into the worker.finished
via jq's `+` operator. Empty sentinel → empty object → merge is a
no-op (matches the legacy shape, parseEvent accepts both).
Validated the jq merge output through parseEvent: both shapes parse
clean as worker.finished events. tsc + all home/ self-test suites
still green.
The foot-gun: \`npx tsx home/worker.ts | tail -3\` looks like a one-shot
test invocation but actually starts a fs.watch + log tailer that runs
forever after \`tail\` closes the pipe. Last session I tripped this twice:
once with a bad self-test loop that ran the worker without --self-test
(leaving a hot worker hours later), and once with a server smoke that
left an orphan on port 3088. The hot worker then picked up a real
bridge.dispatch from a separate smoke test and injected the next_best
prompt straight into the Cockpit zellij tab — i.e. into the active
agent session running the smoke test.
Structural fix: all three long-running home/ processes now require an
explicit --start flag. Naked invocations print a usage banner and exit
0, so accidental \`| tail -N\` or \`| head\` piping no longer leaves
orphans. worker keeps its existing --self-test branch.
• home/server.ts: --start guard at top, before any tailLog/listen
• home/watcher.ts: --start guard before fs.watch on SESSIONS_DIR
• home/worker.ts: --start | --self-test | (default: help+exit)
• scripts/home-start.sh: passes --start to all three launches
home/worker.ts self-tests still 12/12; tsc clean. State/decide/render/
projects suites untouched and still green.
Symmetric to the watcher.ts fix in 58e195b. emit_worker_finished was
appending worker.finished events to ~/.${APP_SLUG}/events.jsonl for any
tab the stop hook fired in — including scratch shells, ad-hoc one-off
tabs (Tab #1, Logo, …). The brain's state map would still accumulate
junk via this path, even though the watcher half was now filtering.
Closes the loop: both event-producing paths in the home/ system now
respect ~/.config/agent-projects.conf as the SSOT for which projects
the brain tracks.
awk-based filter (no jq dependency for the lookup itself):
- reads ${APP_PROJECTS_CONF:-${AGENT_PROJECTS_CONF:-${CLAUDE_PROJECTS_CONF:-$HOME/.config/agent-projects.conf}}}
- case-insensitive match on the first |-delimited field
- skips comment lines
- missing conf file means no filter — preserves the existing behaviour
for users who never registered projects
Verified against the live ~/.config/agent-projects.conf with 8 sample
tab names: Cockpit/cockpit/COCKPIT → REGISTERED; Tab #1, Logo,
NonexistentTab → skip; OpenClaw/openclaw → REGISTERED.
After this commit, the brain's view is curated symmetrically on both
input paths. Adding/removing a project name happens in exactly one
file: ~/.config/agent-projects.conf.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
scripts/home-start.sh starts server + watcher + worker together, merges
their output (with [server] / [watcher] / [worker] prefixes per line)
into /tmp/${APP_SLUG}-home.log, and traps SIGINT to take the whole stack
down cleanly. Removes the previous three-terminal ceremony — one command,
one log, one Ctrl-C.
Pre-flight: refuses to start if anything is already serving
localhost:3001, so two stacks can't race on the same events.jsonl file.
Wait -n: if any child process exits unexpectedly, the launcher tears the
remaining two down. The user gets one obvious signal instead of a quiet
half-broken loop where (say) the worker crashed but the server kept
serving stale state.
home/README.md updated to point at the launcher first, with the
three-terminal recipe kept for iterative development.
Unblocks the M9 live exercise: previously each test required three
terminals + remembering each command + cleaning up three pids manually.
Now it's `bash scripts/home-start.sh` → curl /api/dispatch → Ctrl-C.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Fourth milestone of the greenfield rewrite. handle_stop in agent-hook-bridge.sh
now appends a properly-stamped worker.finished JSONL event to
~/.${APP_SLUG}/events.jsonl in parallel with the existing
finish_orchestration_run cloud call. The new home/ Brain gets a complete
view of each run (idle from M3 watcher + finished from this commit) without
the cloud-round-trip dependency.
Two new functions:
infer_outcome_v1 Bash port of src/lib/orchestration/infer-outcome.ts.
Same precedence: health=critical → error; long-running
with empty done → hang; tests has 'fail' or health
'needs attention' → partial; health=good + done set
→ success; else partial.
emit_worker_finished Reads done/next/tests/todos/health out of the session
file the agent just wrote, derives durationMs from
/tmp/${APP_SLUG}-run-<tab> mtime (the dispatch
sentinel), assembles a v=1 worker.finished envelope
via jq, appends to the log. Skips silently if jq
isn't installed — the cloud finish path keeps working
unchanged.
Wired into handle_stop right after finish_orchestration_run. Both consume
the same session.md, so they always agree on the handoff. The new path adds
zero latency to the stop hook (jq append is sub-ms) and zero blocking — if
the log file is full or unwritable, the error path is squashed via
|| true so the popup still fires.
What this commit deliberately does NOT do:
- retire the legacy /tmp/agent-* sentinels (still written for daemon parity)
- stop calling finish_orchestration_run (cloud path stays during cutover)
- emit worker.started yet (M5 — once dispatch flows through the new
bridge.dispatch event path)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Last hidden 3-way contract between brand and runtime:
scripts/install-cockpit-hooks.sh writes hooks that emit
/tmp/cockpit-typing-<PANE_ID>
src/lib/zellij.ts reads files starting with cockpit-typing-
scripts/cockpit-daemon.sh (already routed)
If a rename only touches the install script, existing user shells keep
writing the old prefix while zellij.ts reads the new one — dispatch fires
while the user is typing, garbling input. No static gate would catch it.
Both sides now derive from APP_SLUG. The install script sources _brand.sh
and uses unquoted heredoc with backslash-escaped $-references so the
generated .zshrc block has APP_SLUG baked in literally at install time
(no dependency on the user having APP_SLUG exported at shell startup).
The MARKER + function names + tab variable name + tmp path are all
slug-derived.
After a rename, users need to re-run install-cockpit-hooks.sh to refresh
their .zshrc with the new prefix. The new MARKER means the install is
detected as fresh, not idempotent — by design, since the old hooks need
to be manually removed or they'll keep writing the old prefix.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
scripts/cockpit-beacon-window.sh launches chromium with --class=cockpit-beacon
and both /api/beacon/window/{show,hide} search by that exact class to find and
move the pre-warmed window. The string was hardcoded in three places — a
rename would silently break beacon visibility (window/show/hide would find
zero matches and no-op).
Now derived from APP_SLUG in all three places (BEACON_WM_CLASS const). The
shell script sources scripts/_brand.sh; both route files compute the same
string from src/config/brand.ts. A rename flips all three together.
Also routed in this commit:
- COCKPIT_BEACON_URL / COCKPIT_BEACON_PROFILE → _brand_env BEACON_URL / BEACON_PROFILE
(so APP_BEACON_URL is the new spelling, legacy still works)
- /tmp/cockpit-beacon dir → _brand_tmp 'beacon'
- "cockpit-app unreachable" log → "${APP_SLUG}-app unreachable"
- profile dir default ~/.config/cockpit-beacon-profile → uses APP_SLUG
The beacon launch + show/hide endpoints have to be restarted together after
a rename — the running browser still carries the old WM_CLASS until the
window-launcher script is restarted.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Audit before this commit: 642 case-insensitive 'cockpit' refs across 119
files; only 2 callers actually used src/config/brand.ts. A rename was an
hour of careful sed touching things like email templates, auth UI copy,
/tmp paths, env var names, log prefixes — easy to miss one.
After this commit: every UI string, every /tmp sentinel, every env var,
and every shell log prefix derives from one of two files:
src/config/brand.ts APP_NAME · APP_SLUG · APP_DOMAIN · APP_EMAIL_FROM
APP_KICKER · APP_DESCRIPTION · APP_TAGLINE
APP_URL · APP_PROFILE_URL(username)
scripts/_brand.sh $APP_NAME · $APP_SLUG · $APP_DOMAIN
_brand_env <KEY> <default> → $APP_<KEY> || $COCKPIT_<KEY>
_brand_tmp <name> → /tmp/$APP_SLUG-<name>
UI broker (TS): SignInForm, project-intent-panel, bootstrap-modal-steps,
AgentTokenSettings, setup/page, whitepaper/page, /u/[username]/page,
invite/layout, beacon/live/BeaconLiveClient, api/project/bootstrap, and
src/lib/email all import APP_NAME from brand.ts. /tmp paths in
agent-config:stateFile.run, control/sleep-mode/route, control/auto-continue/route,
beacon/route, beacon/sse/route derive from APP_SLUG.
Shell broker: cockpit-daemon.sh and agent-hook-bridge.sh source _brand.sh,
read env via _brand_env (so APP_DAEMON_TOKEN and APP_BASE_URL work alongside
the existing COCKPIT_* names), write /tmp paths via _brand_tmp, log under
[$APP_SLUG-daemon] / [$APP_SLUG-bridge].
Env aliases (TS): src/lib/brand-env.ts mirrors _brand_env. src/lib/constants,
src/lib/daemon-auth, src/lib/session, src/auth.config (Edge), and
api/beacon/transcribe all resolve env via the alias scheme. Existing
COCKPIT_*-prefixed env vars on machines in the wild keep working — APP_*
takes precedence when both are set.
To rebrand the entire product after this commit: edit APP_NAME / APP_SLUG /
APP_DOMAIN in src/config/brand.ts AND in scripts/_brand.sh, swap the
vercel.json alias, point DNS at the new registrar. That's it — no other
code touches the name.
Out of scope (deliberately): content/* essays and whitepaper.md (editorial
voice, not mechanical), README.md (would distract from this commit's
purpose), .env example DATABASE_URL (config value, not code), file names
themselves (CockpitMark.tsx, cockpit-daemon.sh — those become git mv after
a chosen new name).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
_base_url() prefers $_LOCAL_URL when /api/health responds, which is the
right default when the user runs everything locally. But when a local
Next.js dev server is up alongside a *different* cloud Cockpit (the
common case for cockpitapp.vercel.app users), the daemon ends up pushing
runtime state and claiming commands from the local DB while the user
watches the cloud — daemonLastPushedAt on cockpitapp.vercel.app stays
frozen for days even though the daemon is healthy.
Add a single env var that skips the local probe entirely. _init_base_url
logs the choice so it shows in the daemon log line at startup.
Verified locally: /api/health responds on localhost:3000 with
{"ok":true,"runtime":true}, but POST /api/control/runtime-state on
cockpitapp.vercel.app already returns {"ok":true,"count":0} with the
daemon bearer — so the moment the user restarts the daemon with the
flag set, state will land on the cloud control panel for the first
time since the schema-drift fixes landed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Verifying the sleep-mode loop surfaced this gap: cloud-mode dispatches go
through pending_commands and never created an orchestration_runs row, so
agent-hook-bridge.sh:finish_orchestration_run silently no-opped on Vercel
(no /tmp/cockpit-run-<tab> sentinel was ever written).
- InjectPayload gains an optional runId so the run id can be threaded from
server-side dispatch to the local daemon over the pending-commands queue.
- /api/orchestration/run cloud-mode block now creates a tracked run row
before enqueueing (mirroring the local-mode path), excluding lifecycle
intents. runId is returned to the caller so the client can correlate.
- cockpit-daemon.sh:inject case reads payload.runId and writes the
/tmp/cockpit-run-<tab> sentinel before execute_inject, so the existing
stop hook closes the loop unchanged.
With this, the next live agent run dispatched from cockpitapp.vercel.app
will produce its first end-to-end outcome row.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Close the loop on Sleep Mode v1. The web-app side (Moon toggle in /control)
already writes /tmp/cockpit-sleep-mode via POST /api/control/sleep-mode and
short-circuits the ReadyBanner countdown to 0 in the browser. The local
stop hook was still launching the popup regardless — so a user who flipped
sleep mode and closed the lid would come back to a stale popup.
Adds a single check between the popup-mode and min-idle gates: if the
sentinel exists, log + exit 0 (matching the existing 'disabled' semantic).
The browser-side ReadyBanner continues to auto-inject as long as Cockpit
is open in any tab — no other change needed for the loop to close.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Foundation for the autonomous-dispatch loop — every prompt dispatched into a
zellij tab now produces an outcome row that downstream logic can learn from.
- orchestration_runs gains an `outcome` column (success/partial/error/hang/
user_abort/timeout) plus a partial index on (user_id, project_key, finished_at)
scoped to finished rows, sized for the "last 5 outcomes" lookup.
- inferOutcome() classifies a session handoff (done/next/tests/todos/health)
+ durationMs + error into one of the six outcomes. Pure, no I/O.
- Every dispatch for claude/codex/gemini adapters now creates a run row at
inject time and writes the run id to /tmp/cockpit-run-<tab>. Lifecycle
intents (hard_stop / close_session) are deliberately not tracked.
- New endpoint POST /api/orchestration/runs/[id]/finish closes a run with
inferred (or explicit) outcome + summary.
- agent-hook-bridge.sh:handle_stop reads the run sentinel and posts the
session handoff back. Fire-and-forget, never blocks the stop hook.
The visible side of this loop (dispatch reasoner ingestion + ProjectCard
streak chip) ships in the next commit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replace the 10s polling loop (20 × 0.5s sleeps) with `xdotool search --sync
--onlyvisible` which blocks until the window actually appears — no fixed
timeout, no race on slow machines. Guard the xdotool block so the script
stays functional without it installed.
beacon.py no longer cold-spawns its own browser window (that path created
rogue, untargetable windows when the service wasn't running). Instead it
ensures the cockpit-beacon-window.service unit is active (idempotent systemctl
start) and pings /api/beacon/window/show — SSE drives the same path from React,
this is belt-and-suspenders to minimise perceived latency.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Three issues with the off-screen pre-warm approach:
1. cockpit-beacon-window.sh was using exec (replaced process), so the
background unmap watcher couldn't run. Changed to background & with
an explicit wait so the watcher subshell can poll for the window
and unmap it the moment it appears, preventing any initial flash.
2. hide/route.ts was using windowmove -32000,-32000 to "hide" the
window. KDE Plasma/KWin clamps offscreen positions back to the
nearest visible screen edge, so the window was never truly hidden.
Switched to windowunmap (X11 visibility off) — works reliably.
3. show/route.ts was calling windowmap after windowmove. Moving an
unmapped window is silently ignored by the WM. Reordered to
windowmap --sync first, then windowmove/activate/raise.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Two bugs in the beacon popup:
1. Race condition in BeaconLiveClient: handleClose scheduled
setSession(null) after 1500ms unconditionally. If a new SSE session
arrived during that window, the setTimeout would overwrite it with
null, silently killing the next popup. Fixed with a functional
updater that only clears if the closing session's ID still matches.
2. Wayland/xdotool invisibility: cockpit-beacon-window.sh was launching
chromium as a native Wayland window (on KDE Plasma, chromium defaults
to Wayland for --app windows). xdotool is X11-only and cannot find
or move Wayland-native windows, making /api/beacon/window/show and
/hide silently no-op. Fixed by unsetting WAYLAND_DISPLAY and passing
--ozone-platform=x11 so the window runs through XWayland instead.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
/api/beacon/window/show moves the pre-warmed chromium window on-screen
and raises it; /api/beacon/window/hide moves it off-screen (-32000,-32000).
BeaconLiveClient calls these whenever session state changes, so the popup
appears fully populated with no Standby flash visible to the user.
The service script already launches chromium with --class=cockpit-beacon
and --window-position=-32000,-32000 so xdotool targets the right window.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When cockpit-beacon-window.service manages the pre-warmed Chromium window,
it never writes _LIVE_PID_FILE. The old code would fail the PID check and
spawn a duplicate window alongside the running one. Now: try xdotool/wmctrl
focus first, only cold-start if no window is found.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Split ProfileSettings into Profile (public identity) and Account (auth/security) tabs
- Add LocationSettings with two-tier model: homeCity/timezone/locale + currentCity/timezone/until for travelers
- Add AccountSettings with email display, password change, connected OAuth providers, danger zone
- New SettingsTabs with 7-tab horizontal nav (Profile · Account · Location · Agent · Projects · Team · Billing)
- New user_preferences DB table with getUserPreferences/upsertUserPreferences query functions
- New API routes: GET/PATCH /api/me/preferences, GET/DELETE /api/me/connected-accounts/[provider]
- Wire user's active city into weather API; active timezone into cron default
- beacon: replace "Waiting for Claude…" spinner with clean Standby screen (logo + text)
- beacon: fix grep pipeline crash in agent-hook-bridge.sh (|| true guards), fix token lookup
- beacon: fix _PROJECT_ROOT via agent-projects.conf, fix auto-start without zenity dialog
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Web popup at /beacon/live is the sole popup surface. Deletes the dead
PyQt vendored modules, the foreign-UI zenity/kdialog/notify-send dialog
that asked the user whether to start Cockpit, and the PyQt-import gates
in the install/smoke/runtime check scripts. The session JSON is now
written unconditionally; if Cockpit is unreachable, beacon.py
fire-and-forgets `systemctl --user start cockpit-app` and exits — the
session surfaces via SSE once the service is up.
Also fixes a pre-existing react-hooks/purity error in StuckGoalsCard
(impure Date.now() inside server component body) that was blocking the
pre-commit lint hook for the whole repo.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Moves beacon settings from a shared machine file to a per-user `beacon_settings`
Postgres table so every account has independent control. Adds `popup_mode` (web /
pyqt / both / disabled) with pros/cons shown in the settings UI.
- New `beacon_settings` table (userId unique FK, all existing fields + popup_mode)
- `db/queries/beacon-settings.ts` — getBeaconSettings / upsertBeaconSettings
- GET /api/beacon-settings now requires auth; both verbs read/write DB
- beacon.py reads popup_mode via get_popup_mode() and gates PyQt / web accordingly
- _beacon_config.load_settings() fetches from API with 5-min /tmp cache, falls back
to legacy file when Cockpit is offline
- agent-hook-bridge.sh fetches settings via Bearer token; exports BEACON_POPUP_MODE;
both stop and notification handlers gate immediately on popup_mode=disabled
- Settings page: 4-card popup mode selector with per-option pros/cons descriptions
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace hardcoded 60s idle threshold with min_idle_seconds setting.
Default is 0 which fires the popup every session end regardless of
keyboard activity. Setting lives in beacon.json, surfaced in Settings UI.
Both the stop-hook beacon and the notification auto-inject respect it.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Command pickup latency: 5s → ~100ms. The API now holds requests for up to
25s (local) / 8s (remote Vercel) until a command arrives, eliminating the
sleep-then-poll cycle. The push loop skips the POST when state is unchanged
(md5 hash comparison), cutting idle DB writes from ~30/min to near zero.
After each command execution, a background push fires immediately so the UI
reflects results without waiting for the next push cycle.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Non-lifecycle cloud-queued injects had the same gap as the run route (fixed
in 0bc9cd8): stale closing sentinel persisted, keeping UI in "Closing…" state.
Also cancels any open web-beacon popup for the tab (mirrors cancelActiveBeaconSessions)
so the React beacon client self-closes when a new task is injected remotely.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Route used getSessionUserId() (cookie-only); hook bridge sent no auth header.
Switch route to getApiUserId() (cookie + Bearer) and read COCKPIT_DAEMON_TOKEN
from env or .env.local fallback in patch_project_state curl call.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The notification auto-inject path dequeued queue items before reading session
health, so a critical/degraded health state was ignored and queue items fired
when they shouldn't. Moved the health read before the queue dequeue check and
gates the dequeue on auto_key=next_best — mirroring sessionHealthBlocksQueue()
on the client and the server-side gate in /api/orchestration/run.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
In cloud mode (Vercel), session content was never populated in DB —
the runtime-state route only accepted agent/lifecycle fields, and the
daemon only pushed those. The UI showed empty done/next/health/tests
in the ReadyBanner and ClosedBanner for all cloud-mode users.
Daemon reads ~/.claude/sessions/<tab>.md per project each push cycle and
merges sessionDone/Next/Tests/Todos/Health/UpdatedAt into the payload when
the file exists. Route extended to accept and pass these fields through to
upsertProjectState (absent = skip, present = update).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>