You called out that my session.md 'next:' didn't reflect queue items
because I literally never received them — the next_best prompt body
was just the generic scan instruction. Investigation in the previous
turn confirmed: queue lives in browser localStorage (and a busted
/tmp/agent-queue-<tab> mirror that doesn't persist in Vercel cloud),
the agent only ever got 'scan: 1.interrupted 2.tests 3.SSOT 4.mission'.
Plumbed the queue through end-to-end, model-agnostically:
• src/lib/orchestration/contract.ts — OrchestrationTaskRequest
gains an optional queue: string[] field.
• src/lib/orchestration/renderers.ts — new renderQueueBlock() emits
'User's prompt queue for this project (in priority order): ...'
when the request carries queue items. Block appended for every
adapter (claude / openclaw / codex / gemini fallthrough) so
visibility is uniform regardless of model. Capped at 10 items
displayed with overflow indicator.
• src/app/api/orchestration/run/route.ts — RunOrchestrationBody
accepts queue (≤200 items × 4kB, matching /api/beacon/queue
persistence limits).
• src/hooks/use-control-data.ts:runWithBrain — reads the queue
from window.localStorage[queueKey(project.tab)] at dispatch time
and passes it through. Best-effort: SSR / private browsing /
storage-disabled → empty queue → no harm, prompt renders without
the block. Uses the same key the usePromptQueue hook owns.
Net effect: every dispatch (manual or auto-fired) carries the queue
in its prompt body. The agent can weigh queue items against other
scanning candidates and pick what's truly highest-impact — which is
the human-in-the-loop semantics the system was already trying to do
client-side, now extended to my own reasoning.
What this does NOT do (deliberate scope cut):
• Doesn't fix the broken /tmp/agent-queue-<tab> server mirror.
Real fix is DB-backed queue storage — separate work.
• Doesn't change handleAutoInject's queue-head-drain behavior.
queue[0] still fires as the prompt directly when next_best would
have fired; the new block surfaces queue[1..N] context to the
agent so they know what's coming next.
tsc clean, eslint clean (src/ + home/), npm run test:home 85/85.
Applied 0009 via neon CLI (user pointed out I had neonctl access I
hadn't used). project_states.session_status column now exists on
prod; reverting e332f37's temporary code revert.
• src/db/schema/project-states.ts — sessionStatus column declared
again, between userId/projectId/... and sessionDone for top-down
SELECT shape.
• src/app/api/control/route.ts — both upsertProjectState callsites
persist session.status.
• src/app/api/control/stream/route.ts — session object includes
status: r.sessionStatus ?? "" from the DB row.
• src/app/api/project-states/[key]/route.ts — PATCH body schema +
upsert accept sessionStatus.
Now the cloud /control auto-inject gate has accurate status from
project_states server-side (instead of having to parse session.md
content via the beacon). End-to-end chain:
agent writes session.md status: ready/working
→ home/watcher emits worker.idle with handoff.status
→ cockpit-app reads session.md, persists to project_states.session_status
→ /api/control/stream returns session.status
→ handleAutoInject gates on status === 'ready'
Migration applied via: psql \$(neonctl connection-string --project-id
quiet-resonance-56972950 --pooled false) -f drizzle/0009_*.sql
(verified column exists post-apply).
tsc clean, 85/85 home tests, eslint clean.
15af9d9 added the sessionStatus column to the Drizzle schema AND the
writer + reader code that references it. The Vercel build that
deployed from those changes started SELECTing session_status from
project_states — but the migration in drizzle/0009 hadn't been
applied to the Neon DB, so the column didn't exist → /api/control
500s on every request → /control page broken.
I aliased cockpitapp.vercel.app back to the prior Ready deploy
(cockpit-rxqxhzbs2 = commit 27f31cb) immediately when I caught this,
so production is currently safe. This commit makes main safe to
build from again WITHOUT needing the migration applied first.
What's reverted:
• src/db/schema/project-states.ts — sessionStatus column commented
out (with a clear note for re-adding after migration). drizzle/
0009_project_states_session_status.sql kept as the apply target.
• src/app/api/control/route.ts — both upsertProjectState callsites
drop sessionStatus.
• src/app/api/control/stream/route.ts — session object uses
status: "" hardcoded (auto-inject gate treats "" as suppress, which
is the correct default behavior).
• src/app/api/project-states/[key]/route.ts — PATCH body schema +
upsert drop sessionStatus.
What stays:
• drizzle/0009_project_states_session_status.sql — ready to apply
with \`DATABASE_URL=<neon> npx drizzle-kit push\` or psql.
• The status field everywhere ELSE in the chain — Handoff schema
in events.ts, the agent's prompt template, parsers, beacon's
handleAutoInject gate (parses status directly from session.md
content). 27f31cb's status-gate functionality continues working
at the beacon layer; only the cloud /control project_states
server-side surfacing is paused.
Once you apply 0009 to prod (drizzle-kit push, or run the SQL by
hand), I'll push a follow-up that re-adds the schema column + the
four writer/reader references. tsc clean, npm run test:home 82/82.
Completes scope cut #1 from yesterday's 27f31cb commit. The auto-inject
gate now reads status from project_states server-side (not just from
raw session.md content in the beacon), so the cloud /control flow
surfaces the agent's lifecycle state end-to-end.
Plumbing:
• src/db/schema/project-states.ts — sessionStatus column declared
(text, nullable). Position: before sessionDone so the SELECT row
shape reads top-down as status → done → next → ... → health.
• drizzle/0009_project_states_session_status.sql — idempotent
ADD COLUMN IF NOT EXISTS. Apply with drizzle-kit push (no
auto-runner; matches the 0001-0008 pattern).
• src/app/api/control/route.ts — both upsertProjectState callsites
(mtime-advanced + bootstrap) now persist session.status.
• src/app/api/control/stream/route.ts — SSE row construction reads
r.sessionStatus into session.status alongside the other fields.
• src/app/api/project-states/[key]/route.ts — PATCH body schema +
upsert object both accept sessionStatus for the daemon's push.
Migration safety:
• Column is nullable + new — existing rows get NULL.
• The auto-inject gate treats NULL/undefined as suppress (matches
the user's stated default: only fire on explicit 'ready').
• Idempotent SQL — re-applying the migration won't error.
Apply on production: \`DATABASE_URL=<neon> npx drizzle-kit push\` (or
the user's preferred migration runner).
tsc clean, npm run test:home 82/82.
Scope cut #2 remains queued: agent-hook-bridge.sh:emit_worker_finished
including session_status in worker.finished events (user denied prior
edits 3x — happy to ship if they want or leave it for them to land).
User asked: stop firing auto-inject prompts while the agent is mid-task;
inject should only fire when the agent has done everything and now
needs a nudge. They also called out the broader goal that this should
work for any model (claude, codex, gemini, openclaw, or future
adapters) — not just claude — since today's behavior is implicitly
claude-coupled through ~/.claude/sessions/*.md and the stop hook.
Added a new \`status\` field to the canonical handoff format. The
agent self-reports lifecycle state per turn:
status: ready — task fully done, auto-inject may proceed
status: working — agent is mid-task, suppress auto-inject
Missing / undefined / any-other-value is treated as NOT ready. This
inverts today's implicit default (auto-fire fires on every turn end)
so the agent must explicitly signal it's done with everything before
the beacon/ReadyBanner countdown fires the next prompt. Matches the
user's stated intent literally.
Why this is model-agnostic: the field lives in the canonical
ORCHESTRATION_TASK_SUMMARY_FIELDS constant that ALL adapters' handoff
templates read from (claude via buildPromptWithSession, openclaw via
renderSharedHandoffBlock, codex/gemini will inherit when their
handoff plumbing is wired). The parsers (parseSessionFile,
parseSessionText, home/watcher.ts:parseHandoff) all pick it up
automatically. Any new adapter that writes the standard handoff
format gets the same gating.
Files touched:
• src/lib/orchestration/contract.ts — added 'status' to
ORCHESTRATION_TASK_SUMMARY_FIELDS; OrchestrationTaskSummary makes
status optional for back-compat.
• src/lib/events.ts — Handoff zod schema gains status (defaults to
"") so home/ events with status round-trip cleanly.
• src/lib/control-types.ts — SessionState.status is optional;
legacy construction sites that don't yet plumb session_status can
omit it and naturally suppress auto-fire.
• src/lib/agent-config.ts:buildPromptWithSession — new status line
in the handoff template prose (the one claude reads each turn).
• src/lib/orchestration/renderers.ts:renderSharedHandoffBlock —
same line for openclaw.
• src/lib/session-content.ts:parseSessionText — beacon DB parser
extracts status.
• home/watcher.ts:FIELDS — home/ watcher's handoff parser includes
status (cascades to worker.idle events).
• src/hooks/use-project-card-actions.ts:handleAutoInject —
explicit gate: only fires when status === 'ready' (or
health-critical for recovery dispatches).
• src/app/beacon/[id]/BeaconClient.tsx:handleAutoInject — same
gate, parsing status out of session.sessionContent via
parseSessionText (BeaconSession carries raw md text).
• src/app/api/orchestration/runs/[id]/finish/route.ts — finish
body summary preserves status.
• home/{decide,emit,state,worker}.ts test fixtures — added
status: "" to all Handoff literals so the new required-after-
default field type-checks.
tsc clean, eslint clean, npm run test:home 82/82.
Transition note: until adapters start emitting status in their
handoffs, auto-inject will suppress for everyone. This is the user's
explicit choice ("only fire when the agent has done everything").
The handoff template prose now tells the agent to write the field,
so going forward agents will include it.
NOT shipped in this commit (deliberate scope cut, queued for next):
• DB column session_status on project_states (mirror of the new
field) — without it, control/stream/route.ts can't surface the
field server-side. Today the BeaconClient parses status directly
from raw session.md content; the broader cloud /control flow
will get accurate status once the column lands.
• Bash side (agent-hook-bridge.sh:emit_worker_finished) reading
status from session.md and including in worker.finished events.
The user has denied prior edits to that file; happy to ship if
they want or leave it for them to land.
Investigated the user's followup: 'speech to text is not working on
https://cockpitapp.vercel.app/control. it should go to my local voice
model version by default, but i should also be able to sign up for
the online (cloud) speech to text model.'
The architecture for cloud-UI → local-Whisper was 80% there but
disconnected at the route level:
• home daemon already handles type=transcribe payloads (cockpit-
daemon.sh:701-704; reads audio_b64 + mime_type, runs ffmpeg +
transcribe.py, posts result back via /api/control/commands/:id)
• /api/beacon/transcribe/[id] already polls pending_commands.result
for the daemon's reply
• use-whisper-mic.ts already branches on data.transcriptionId and
polls /api/beacon/transcribe/{id} for status
What was missing: the POST route never enqueued. On Vercel where
isRuntimeAvailable() is false, the routing computed useGroq=true for
provider='auto' and tried Groq directly (which 401s right now —
see prior commit 92a30e6). No path produced a transcriptionId, so
the polling code never engaged.
Rewrote the route's routing decision:
provider='groq' → call Groq directly (paid opt-in)
provider='local'/'auto':
runtime present → in-process local Whisper (dev path)
runtime missing → enqueue for the user's daemon
The enqueue path inserts a pending_commands row with the daemon's
expected payload shape (audio_b64 + mime_type, matching the jq
selectors in cockpit-daemon.sh), caps the audio at 6 MB raw so a
runaway recording doesn't bloat the jsonb column, and returns
{ transcriptionId } which the client polls.
Net effect: open https://cockpitapp.vercel.app/control, click the
mic, speak, release — the audio rides through pending_commands to
the local daemon, runs through the user's local Whisper, comes back
via the polling endpoint. Groq stays available as a faster cloud
opt-in by switching beacon-settings transcription_provider to 'groq'
(once the GROQ_API_KEY is rotated).
tsc clean, eslint clean.
Investigated the user's 'STT microphone not working properly' report.
Found two real problems on this machine:
1. GROQ_API_KEY in .env.local returns 401 from Groq (direct probe of
https://api.groq.com/openai/v1/audio/transcriptions with the same
bearer returned {'error':{'message':'Invalid API Key'}}). User
needs to rotate the key at https://console.groq.com.
2. Local Whisper 'base' fallback takes 38-45s per 1-second WAV —
within the route's 60s timeout but well past any user's patience.
The route's 401 path previously wrapped the failure as a generic HTTP
500 with the error body inlined as a string — easy to miss in a network
tab, no actionable hint. Now classifies common Groq failure modes:
• 401 (Invalid API Key) → HTTP 502 with 'rotate the key' hint
• 429 (rate limited) → HTTP 429 with 'retry or switch to local'
• timeout / abort → HTTP 504 with 'try a shorter recording'
• other → HTTP 502 (was 500; bad-upstream is more
honest — the route itself didn't fail)
The original error is preserved as for debugging without
poisoning the user-facing string. Local Whisper path
unchanged — the slowness there is a separate question (model size +
GPU vs CPU) and outside the scope of error-message work.
tsc clean, eslint clean. Doesn't fix the user's 401 — they still need
to rotate the Groq key — but ensures future occurrences are diagnosed
in seconds instead of requiring a deep dive into the route source.
Real safety bug surfaced while auditing the home/ dispatch path. When
injectIntoTab was asked to write into a tab that didn't exist (closed,
typo'd, zellij not reachable from the caller's env), the sequence:
zellij action go-to-tab-name <missing> # no-op, exits 0
waitForTabFocus(missing) # times out, returns void
zellij action write-chars <prompt> # → types into whatever IS focused
…would type the prompt into the user's CURRENTLY-FOCUSED pane, which on
a long-running worker process is almost certainly NOT the intended
agent tab. Could garble a private terminal session, paste secrets, or
trigger a wrong agent. Silent failure — every caller's try/catch
considered it a success.
src/lib/zellij.ts
waitForTabFocus now returns boolean (true = focused, false = timeout)
injectIntoTab throws when waitForTabFocus returns false
sendRawKey throws likewise (same wrong-pane risk for raw key codes)
Error message names the tab + hints at the likely cause:
"injectIntoTab: zellij tab "<name>" did not gain focus within 1s —
is the tab open and zellij reachable?"
Caller impact: every existing call site (orchestration/run, inject,
agent/launch, switch-agent, plus home/worker.ts) already wraps
injectIntoTab in try/catch, so the new throw cleanly surfaces as a
500 / worker.crashed event instead of corrupting an unrelated pane.
All five home/ self-test suites still green: state 8/8, worker 6/6,
decide 10/10, render 12/12, projects 7/7.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closing a metadata-correctness gap: home/worker.ts was hardcoding
adapter="claude" on every worker.started event, so analytics + the
decide() function would always see "claude" even when the run was
actually a codex or gemini agent.
Schema: BridgeDispatch gains an optional `adapter` field (Adapter enum).
Server: POST /api/dispatch body accepts an `adapter` string; validated
against ADAPTERS before forwarding into the appended event.
Worker: executeDispatch echoes event.adapter onto worker.started, with
"claude" as the default when the brain didn't set one (matches
DEFAULT_AGENT in src/lib/agent-preferences.ts).
The caller (UI / API client) is the source of truth for adapter choice
in this round. M10 wires per-project agent_pref so the brain's autonomous
dispatches use the right agent without a caller telling it — that needs
either DB access from home/ or a flat-file agent_pref export from the
existing system. Out of scope here.
All four self-test suites still green:
home/projects 7/7 · home/worker 6/6 · home/render 12/12 · home/decide 9/9
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
First milestone of the greenfield rewrite (Brain-on-the-user's-machine,
append-only JSONL event log as the Worker⇄Bridge contract). No runtime
yet, no migration yet — just the wire-format contract that everything
downstream builds against.
src/lib/events.ts is the SSOT for:
- Versioned envelope (v=1, id, ts) so future schema changes are explicit
- WorkerStarted / Progress / Idle / Finished / Crashed (worker → log)
- BridgeDispatch / BridgeCancel (brain → log)
- BrainOutcome (brain projection)
- parseEvent(line) — never throws; returns structured error on bad lines
- serializeEvent(event) — JSON + newline, no surprises
Field reuses for compatibility with existing infra: the Handoff shape
matches session.md fields, the Outcome enum matches orchestration_runs.outcome,
the Adapter enum matches src/lib/orchestration.ADAPTERS. So the new system
can ingest events from the current daemon during migration without
translation.
Why this lands alone: the whole architecture downstream — the local Brain
server, the Bridge tail, the new Worker hooks, the decide() function —
all depend on these types being right. Easier to redline 170 lines of
zod schemas now than 5 files of runtime later. M2 (local Brain skeleton)
builds on this.
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>
The Postgres LISTEN/NOTIFY contract that drives sub-second SSE state
propagation was hardcoded in two files:
src/db/setup-notify-trigger.ts creates fn 'cockpit_notify_project_state'
and notifies channel 'cockpit_state'
src/app/api/control/stream/route.ts listens on channel 'cockpit_state'
If a brand rename only flipped APP_SLUG without touching these, the trigger
would still emit to 'cockpit_state' but the listener wouldn't subscribe to it
— SSE state push silently breaks while every gate (tsc/lint/smoke) stays
green. Hard-to-spot failure mode.
Now both sides import NOTIFY_CHANNEL + NOTIFY_FN_NAME from
src/db/setup-notify-trigger.ts. Both names derive from APP_SLUG (sanitized
to [a-z0-9_] for safe SQL interpolation, since APP_SLUG itself isn't
user-controlled but the sanitizer is defense-in-depth). The startup
instrumentation logs the resolved names so a deploy mismatch surfaces in
Vercel logs.
After a rename:
1. Deploy lands new fn+channel names
2. setupNotifyTrigger runs on next instrumentation boot (idempotent
CREATE OR REPLACE), installing the new function
3. Listener subscribes to the new channel on next /api/control/stream
connection
4. (Optional cleanup): manually DROP the old cockpit_notify_project_state
function from DB — orphaned but harmless if left
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>
Probed /api/ivy on cockpitapp.vercel.app: every request returns HTTP 500
with body "Ivy is unavailable right now — please try again in a moment."
because (1) the local openclaw gateway isn't reachable in cloud mode and
(2) the Groq fallback throws on the same invalid GROQ_API_KEY that
/api/control/dispatch already exposes via classified error reasons.
Mirror the classification from 97b6d09 (dispatch route): catch the Groq
exception, regex-match on status code / timeout, and return 503 with a
specific cause in the error body ("Groq API key is invalid", "Groq
rate-limited", etc.). Status changes from 500 to 503 since "service
unavailable" is a more accurate code for upstream-dependency failure.
User-visible: the "Ask Ivy" buttons across the app now say *why* Ivy is
offline instead of looking like a generic crash. Same root cause as
dispatch — rotate GROQ_API_KEY on Vercel to restore full functionality.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Audit after a46702f surfaced one more wave of user-visible "Cockpit"
literals — including the Ivy system prompt itself, where the agent
introduces itself as "inside Cockpit". After a rename that string would
make every Ivy response sound wrong. Routed through APP_NAME:
- src/app/api/ivy/route.ts Ivy system prompt
- src/app/invite/[token]/page.tsx "Create your Cockpit account"
- src/app/(app)/not-found.tsx "doesn't exist in Cockpit"
- src/app/(app)/today/page.tsx first-run callout copy
- src/app/(app)/(private)/goals/page.tsx Ivy goals-bootstrap prompt
- src/app/verify-email/page.tsx "Go to Cockpit →"
- src/app/api/agent/launch/route.ts 503 error body
- src/config/marketing.ts "Continuation loop" feature body
- src/config/beacon.ts popup-mode description + cons
- src/lib/constants/today.ts PLAN_DAY_PROMPT preamble
- src/config/prompt-library.ts Project Status Report + Weekly Review templates
Result: only 2 "Cockpit" refs remain in src/ — both are JSDoc comments
(crons-shared.ts and alerts.ts schema), zero are user- or agent-visible.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The logo + wordmark component was the last brand-bound name in the
component layer — every importer plus the file itself referenced
'CockpitMark'. Renaming it to 'BrandMark' completes the brand-agnostic
naming pass: after a chosen new name, no component or file in src/
needs touching.
Touches 4 files (rename + 3 import sites): the file itself, PublicSurface,
SidebarBrand, /u/[username]/page. git tracks the move so blame/history
is preserved.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Audit of remaining 'cockpit' refs after 9ee1df4 surfaced UI-visible leakage
the first pass missed:
- ProfileSettings.tsx "cockpit.app" → APP_DOMAIN
- onboarding/page.tsx public-profile preview → APP_DOMAIN
- ThemeProvider.tsx storageKey="cockpit-theme" → `${APP_SLUG}-theme`
- AgentTokenSettings.tsx "@cockpit/agent init" → `@${APP_SLUG}/agent init`
- DaemonStatusBanner.tsx env-var instructions reference APP_DAEMON_TOKEN
+ the daemon script now interpolates APP_SLUG
- orchestration/run/route.ts /tmp/cockpit-<adapter>-prompt-* → APP_SLUG
Out of scope (intentional):
- Stripe metadata key cockpitUserId — stable identifier on Stripe's side,
renaming would orphan existing subscriber records.
- weather route's COCKPIT_LAT/LON/TZ — env-var contract with the weather.sh
tool, not brand-derived in spirit.
- File names like cockpit-daemon.sh, CockpitMark.tsx — `git mv` is a
follow-up after a name is chosen, not a prerequisite to renaming the
visible product.
- README.md, content/*.md — editorial, hand-written, deserves a real pass
not mechanical sed.
The "one-line rename" claim from 9ee1df4 is now closer to honest: every
user-visible string and every runtime-derived path resolves through
src/config/brand.ts. The remaining work after a chosen name is `git mv`
for component/script file names + content edits, both better done by hand.
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>
Probed the /api/control/dispatch endpoint on production: it returns
{action:"queue", reason:"Groq unavailable — using queue order.",
source:"fallback"} regardless of the actual error. Direct curl against
api.groq.com with the GROQ_API_KEY from Vercel env shows 401
"Invalid API Key" — the key on prod is invalid, so the smart-dispatch
streak reasoning hasn't been working at all since outcome tracking
shipped, and the UI gave no hint why.
Catch now inspects the error and classifies (key invalid / rate-limited /
server error / timeout / verbatim) into the reason field, plus a
console.error so debug_logs picks up failures the same way the auth path
already does. Behaviour on success is unchanged.
Action item out of this commit: rotate GROQ_API_KEY on Vercel
production — the current value returns 401 from the Groq API.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
getOrgProjects(userId) called getOrgPeerIds which intentionally excludes
the caller (it answers "who *else* is in my orgs"). That left a solo user
— or anyone in an org alone, like every new signup before they invite
teammates — with peerIds=[] and getOrgProjects returning [].
Symptom: /api/control returned trackedProjectCount=0 and an empty
projects array on cockpitapp.vercel.app, even with 10 active user_projects
rows for the logged-in user. The control panel rendered no cards, so the
whole outcome-tracking + sleep-mode + dispatch loop we shipped over the
last several sessions had no surface to render against.
Fix: union memberIds = [userId, ...peerIds] before the inArray lookup.
The peer-only semantics live in getOrgEntityProjects (entity layer, with a
readonly:true marker) which is correctly distinct.
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>
The third leg of the autonomous loop. The first two (outcome capture →
streak surfacing) shipped last session. This closes the user's "I want to
go to bed and have it just build" ask.
- New useSleepMode() hook backed by SLEEP_MODE_KEY localStorage. Auto-exits
on the next keydown/pointerdown so simply touching the laptop restores
normal-confirm behavior — no need to find the toggle.
- New POST /api/control/sleep-mode writes /tmp/cockpit-sleep-mode for
agent-hook-bridge.sh to read in a follow-up (skip-popup entirely while
sleep is on). Web-app path is already covered.
- ReadyBanner forces seconds=0 when sleep is on, so the existing
onAutoInject path fires immediately instead of after AUTO_INJECT_S
(default 12s). Timer label switches to "Sleep" so the state is visible.
- Control panel header gains a Moon icon next to the view-mode toggle.
Filled when on, accent-text colored, tooltip explains the wake gesture.
Deliberately small: not the full autonomyMode enum refactor, just the
user-visible "walk away" feature on top of the existing autoContinue
machinery. The enum migration can land later without breaking this.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Keep:
- logger.error → debug_logs (low volume; first line of diagnosis next time
Vercel CLI logs are unreachable)
- events.signIn org bootstrap (the actual fix, not diagnostic)
Remove:
- debug: true (noisy in steady state)
- verbose logger.warn / logger.debug stubs
- per-call signIn try/catch DB write (debug_logs already captures via the
logger when Auth.js wraps the error as AccessDenied)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Visible payoff of the outcome-tracking loop:
- ProjectCard header gains a compact 5-glyph streak chip
(✓ success · ~ partial · ✗ error/hang/timeout · ✕ user_abort)
rendered via the new <OutcomeStreak> component using existing
ui-tag-positive / -warning / -negative tone classes — no new tokens.
- /api/control/route.ts batches outcome lookup across all projects in a
single query (getRecentOutcomesByProjectKeys) and threads it into the
per-project ProjectState shape under `recentOutcomes`.
- /api/control/dispatch reads getRecentOutcomes(projectKey, 5), feeds the
glyph streak into the Groq prompt so the strategist sees recent
performance, and appends "[last 5: ✓✓✗✓✓]" to the dispatchReason
surfaced in the ReadyBanner.
- Client now passes projectKey along with the existing handoff/queue/git
context to /api/control/dispatch.
Together with the data-layer commit, this closes the smallest possible
loop: dispatch → outcome capture → next dispatch reads outcomes →
strategist + UI see what worked last time.
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>
Auth.js v5 calls the signIn callback BEFORE handleLoginOrRegister creates the
DB user, so user.id at that point is the OAuth provider's id (e.g. GitHub's
numeric "41178744"), not our DB UUID. Calling getOrgMembershipCount(user.id)
then trips PostgreSQL's UUID parser, which Auth.js wraps as AccessDenied.
Move the org-bootstrap call into the events.signIn hook, which fires AFTER
the DB user is created/linked — at that point user.id is the real UUID.
Profile sync stays in signIn callback but now resolves the DB user via email
before any UUID-typed write.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The first capture surfaced "AccessDenied" but the inner cause object was
JSON.stringified as "[object Object]". Walk Error.cause chains and serialize
nested Error fields so the actionable detail (which adapter/provider call
threw) lands in debug_logs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Vercel runtime logs aren't reachable via CLI/API in this environment.
Persist Auth.js error events to the database so they can be queried directly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two related fixes for the off-screen pre-warm window flow:
1. --name Beacon: Brave creates 2-3 internal splash subwindows that
share WM_CLASS=cockpit-beacon but have no title. Chaining
map/move/activate across all of them was wasted work; only the
actual page window has "Beacon" in its title.
2. Move before map: KWin Wayland animates a slide-in (~150-200ms) when
a window is mapped at a position different from its last-known
geometry. Moving the unmapped window first costs ~0ms (no
compositor work — the window isn't visible), and the subsequent
map then has nothing to animate. Drops show latency from ~380ms
to ~36ms on KDE Plasma 6. --sync no longer needed since each
step is fast and the chain is serialized inside xdotool anyway.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The cockpit-app systemd service runs Next.js from .next/standalone, so
process.cwd() points at the bundle root and scripts/transcribe.py was
missing. Probe the repo-root and standalone-relative locations, with
COCKPIT_SCRIPTS_DIR override for relocated bundles.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
BeaconPageClient used useState(initialSession) which only captures the
prop on first mount. When a second beacon session arrived via SSE,
BeaconLiveClient updated its session state (showing the new content)
but BeaconPageClient stayed mounted with the OLD session ID — so every
PATCH went to the previous session, which beacon.py wasn't polling.
Fix: add key={session.id} so React remounts BeaconPageClient when the
session changes; also drop the redundant useState and use the prop
directly since the component is now always fresh on arrival.
Co-Authored-By: Claude Sonnet 4.6 <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>
The weather route was embedding the user's city string directly in the
bash command passed to runTool (shell: bash), making it vulnerable to
command injection via $() and backtick expansion inside double quotes.
Fix: geocode the active city via Open-Meteo's geocoding API in the
route (24 h in-memory cache), then pass lat/lon/timezone as env vars
to weather.sh — safe numerics never interpreted by the shell.
Update weather.sh to read COCKPIT_LAT / COCKPIT_LON / COCKPIT_TZ with
Zurich as fallback, so the weather data actually matches the user's city
instead of always showing Zurich regardless of the location setting.
Also add extraEnv parameter to runTool so callers can inject env vars
without putting user data in the command string.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
After saving or clearing the current location override, the "Currently
in" badge and dirty-check both used the original server props, so the
badge never disappeared and the Save button re-enabled immediately.
Introduced savedPrefs state that mirrors the server and gets updated on
every successful PATCH, so the UI reflects what was actually persisted.
Also merged the two duplicate @/lib/api/fetch imports in AccountSettings.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
getActiveCity and getActiveTimezone required currentCityUntil to exist
before currentCity/currentTimezone was used. The UI marks 'Until' as
optional, so setting a current location without an expiry silently fell
back to home — making the feature appear broken.
Fix: only skip currentCity when an expiry IS set and has already passed.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add ui-btn-pill / ui-btn-pill-muted / ui-btn-pill-positive to globals.css
(DRY: was copy-pasted as 60-char className in 4 places)
- Use ui-btn-pill-positive for IvyDispatchButton (Plan/Wrap up day)
- Use ui-btn-pill-muted for LogConversationButton and QuickCaptureButton
- Remove single-child grid wrapper around RecentRunsCard
- Remove wrapper divs in RecentRunsCard and StuckGoalsCard; use Card id= directly
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>
- ProjectDetailHeader: always flex-row so X close button is top-right on
all screen sizes, not buried below name/desc on mobile
- ProjectCard: always flex-row items-start justify-between so action icons
are top-right rather than left-aligning below the name on mobile
- ProjectDetailTabBar: flex-1 justify-center on each tab — equal-width
tabs filling the full drawer width instead of content-width tabs
- Drawer: sm:border-l — suppress left border on full-width mobile drawer
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The seen-set was seeded with ALL existing files at connect time, so any
session written by beacon.py before the browser window opened was never
pushed — causing the /beacon/live window to hang on "Waiting for Claude…"
indefinitely.
Fix: seed seen-set with only resolved sessions (choice != null); push the
most recently created pending session immediately on connect so pre-warmed
windows and freshly opened windows both receive the current beacon.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add createdAt to ProjectData and display relative date in header
- CHANNEL_CONFIG replaces PROJECT_CHANNELS string array as SSOT (key+label pairs)
- StatusBadge uses lookup map instead of string-matching conditionals
- buildProjectIvyPrompt extracted to lib/ivy-prompts — removes duplication between ProjectGrid and ProjectDetailHeader
- DescriptionEditor shows pencil icon on hover
- "No context" placeholder replaced with dashed border call-to-action
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- HEALTH_SIGNAL_BASE moved to project-detail-types.ts (no Lucide dep — safe for
any importer); project-badges.tsx merges in icons via KIND_ICON map
- ISSUE_ATTRS now derived from HEALTH_SIGNAL_BASE — never hand-maintained again
- ProjectDetailHeader: IvyDispatchButton wired with project context prompt;
Issues badge upgraded to ui-tag-negative chip
- GoalsTab: drops optimistic state, uses onReload() so parent refetches and real
progress/status/milestones flow back in; empty state gets Target icon
- OverviewTab: CHANNEL_ICON map for recent-activity entries
- Drawer gains "2xl" size; ProjectDetail uses it for more breathing room
- modal.tsx: Drawer size union extended to include "2xl"
Co-Authored-By: Claude Sonnet 4.6 <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>