QA pass on /u/cat surfaced the same broken-avatar bug ProfileSettings used
to have before 1d48165 — the public profile renders next/image with no
onError handler so a 404/CORS/blocked src bleeds through to the broken-
image icon in production.
Extract src/components/shared/Avatar.tsx as the SSOT:
- Three sizes (sm 32 / md 48 / lg 72) → fixed dims for Next/Image + matching Tailwind class
- onError state flips to initials-circle (bg-accent-muted + accent-text)
- getInitials exported so callers can reuse the same name → "GE" / "GB" / "?" logic
- aria-label on fallback so the avatar is announced even without an image
Wired into /u/[username] (size="lg") and ProfileSettings (size="md").
Both old inline implementations and ProfileSettings's local getInitials
copy are gone — one component owns avatar behavior now.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Extend the PullToRefresh wrapper introduced for /today + /control (ea063f3)
to the three other status surfaces. Same component, no code changes — just
wrap each page's PageLayout. Mobile users now get the gesture on every page
that displays live data (server-component fetch + useFetch polls all wake
up via the cockpit:refresh fan-out shipped in 093b33f + 38a358c).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Left over from the previous TileRemoveButton X cancel icon — RemoveConfirmStrip
uses a text "No" button instead so the import is dead. Cleans up the lone
eslint warning from 3dd79fd.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Previously the confirm strip rendered inline alongside Focus + Launch which
squeezed everything below ~360px viewport. Lift the remove stage state into
ProjectTile so when confirming, the entire chips+icons row is replaced by
"Remove <project>? · Yes, remove · No" spanning the full tile width.
- removeStage idle → original action row (chips + icons)
- removeStage confirm/removing → full-width RemoveConfirmStrip
- onCancel/onRemoved → snap back to idle
RemoveTriggerIcon and RemoveConfirmStrip are local helpers; the old
TileRemoveButton (icon + state co-located) is gone since the parent now
owns the state. Project name appears in the prompt so a user reviewing
multiple Stale tiles can't accidentally confirm the wrong one.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Stale bucket is triage — the user opens it to decide what to prune. Add an
inline TileRemoveButton that the tile renders only when an onRemoved prop
is passed (ProjectFleetView sets it only on Stale entries).
Flow:
Trash2 icon → tap → "Remove? · Yes · X"
Yes → DELETE /api/user-projects/[id] → onRemoved() triggers refresh(true)
X → back to icon
stopPropagation everywhere so the buttons don't bubble into the tile's
onExpand click target. Haptic on confirm. Error state stays at the
"confirm" stage with ui-error-xs message so a network blip is recoverable.
Closes the last gap in the original mobile-review item set — Stale is now
an actionable surface, not a passive list.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
idleStaleList previously inherited compareProjects's global rank (today-
commit-count, active-tab presence) which is right for the active/idle
split but wrong inside Stale — the user opens Stale to decide what to
prune, so the most-prunable (oldest mtime, including never-touched) should
surface first.
Sort by session.mtime ascending; no-session falls to -Infinity = first.
Stable sort: same-mtime ties preserve upstream rank, so the existing
compareProjects ordering still applies among equally-old projects.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Third subsection on the idle list: idleStale (session.mtime > 30 days old
or no session at all). Quiet drops from 11 → 6 in the user's fleet; the 5
dormant projects with no recent session move to their own muted-kicker
"Stale · N" group at the bottom.
idleIsStale() lives next to idleNeedsAttention() in control-presenter.ts;
IDLE_STALE_S = 30 * 86_400 matches the rough threshold at which `gog` /
re-orient becomes mandatory before any agent dispatch. No-session falls
through to stale: a never-touched project IS dormant by definition.
The Quiet subheader is now suppressed only when both other buckets are
empty, so the common "everything just quiet" case keeps the clean layout.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
19 idle cards previously scrolled as one undifferentiated mass on mobile.
Split by the simplest signal that means "this project is mid-something":
git.dirty || git.dirtyCount > 0.
Behavior:
- control-presenter exports idleNeedsAttention + idleQuiet alongside the
flat idleProjects list (kept for callers that want the full set).
- ProjectFleetView renders two subsections inside the existing collapsible
with sticky ui-kicker subheaders ("Needs attention · N" amber kicker,
"Quiet · N" muted kicker — only shown when both buckets non-empty).
- ControlPanel threads the buckets through the daemonStateUnknown guard so
daemon-down still hides everything per existing behavior.
The Quiet subheader is suppressed when there's nothing in Needs attention,
preserving the visual mass for the common case of zero pending work.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
useControlData polls /api/control every 30s and on visibilitychange but
ignored the cockpit:refresh broadcast — so PullToRefresh on /control or a
tab-focus return via RefreshOnFocus refreshed everything *except* the fleet
view that the page is actually about.
Add a window listener for COCKPIT_REFRESH_EVENT that calls the same poll()
the interval uses. inFlight guard already prevents duplicate requests when
multiple triggers fire close together (PTR + visibility on the same gesture).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mount RefreshOnFocus once in AppShell. Tracks document.visibilityState; when
the tab returns "visible" after ≥30s hidden, calls router.refresh() and
dispatches cockpit:refresh so server-component data + every client useFetch
poll catch up in lockstep.
Same shape as PullToRefresh's commit path, just triggered by tab focus
instead of finger gesture. 30s threshold suppresses spam from quick app
switches — short enough to beat the longest poll interval (10 min weather),
long enough that "Cmd-Tab → glance → Cmd-Tab" doesn't churn the network.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
router.refresh() only revalidates server-component data. Until now,
GitHubStatus / SystemStats / CalendarCard / WeatherCard kept their useFetch
caches until the next intervalMs tick — so a user pulling to refresh /today
saw the greeting / action queue / commitments update, but weather + calendar
were stale for up to 10 minutes.
Wire a window-level CustomEvent ("cockpit:refresh"):
- src/lib/client-events.ts (new): SSOT for browser-side event names. Kept
separate from src/lib/events.ts which owns the server-side Worker/Bridge/
Brain JSONL schema — different domain, different file.
- PullToRefresh: dispatches the event right after router.refresh() on commit.
- useFetch: adds a window listener that bumps revision when the event fires,
triggering an immediate refetch.
One gesture, everything refreshes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
~60-line client component that wraps a route's children, attaches window-level
touch listeners, and fires router.refresh() when the user swipes down past
80px while at scrollTop=0. Mobile-only via md:hidden indicator + scrollTop
guard so desktop sees nothing.
Behaviors:
- Damped pull (0.5x finger travel) — feels natural, max-clamped at 120px.
- Indicator: small RefreshCw chip that fades in, rotates with pull progress,
then animate-spins once armed (≥80px).
- Commit haptic at 20ms (deeper than the 10ms create/edit tick — confirms
"you triggered the refresh").
- 700ms hold after refresh so the user sees the spin, then snap back.
- Window listeners (not container-scoped) so the gesture works regardless of
which scroll container started receiving touches.
Mounted on the two status surfaces the original Elon-led mobile review
called out (item #13). Other routes can opt in by wrapping their content.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
useInlineEdit's commit() now fires haptic() before the save action, so
inline-edit confirmations across the app feel tactile on Chrome Android:
- goal target-date + progress edits (goal-card-helpers / -sections / hooks)
- person name + notes edits (PersonDetail)
- project inline editors (name, description, status, maturity)
- habit row edits (HabitCard, HabitRow on Today)
Caller-side equality + validation checks run before commit() is called and
short-circuit via ie.cancel(), so the tick only fires on real save attempts.
Same SSOT pattern as useCreateMutation (d0b236f) — one hook owns the
behavior, every call site inherits it for free.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Move haptic() into create() so every "New/Add X" surface gets the tick by
default — NewGoalButton, NewSubscriptionButton, AddCommitmentButton plus
NewHabitButton, NewPersonButton, NewProjectButton (the latter three picked
up the behavior for free).
Removes the three per-caller haptic imports and inline calls added in 25cb863.
By the time create() runs the caller's own validation has already passed
(ModalForm's canSubmit gates the modal path; AddCommitmentButton's
description-required guard runs first), so the tick still only fires on
real submission attempts.
One central SSOT instead of N copies — exactly the consolidation the
session next: called for.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Extend haptic() to the three primary create surfaces:
- AddCommitmentButton: fires in submit() after the description-required guard,
so an empty submit doesn't haptic but a valid one does.
- NewGoalButton / NewSubscriptionButton: fire in onSubmit before the create()
call; ModalForm's canSubmit prop already gates invalid submits so the haptic
only triggers on a real create attempt.
Skipped the previous session's "useHaptic() hook extraction" suggestion —
haptic is already a single named export from lib/haptics.ts; wrapping a
side-effect-free, lifecycle-free function in a hook would add ceremony
without value.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Extends the haptics introduced in 8889c9f to /control's most-tapped surface:
agent dispatch. handleSendIntent wraps onSendIntent with a 10ms haptic() so
the primary CTA, action chips, and More chips all fire a confirmation tick
on Chrome Android. handleSendCustom + handleEnqueue add the same tick to
custom-prompt send / enqueue paths.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
lib/haptics.ts wraps the Vibration API with feature detection + try/catch so
the call is a safe no-op on iOS Safari (Apple removed the API in 2017) and
desktops, and fires a 10ms tick on Chrome Android — short enough to read as
confirmation, not a buzz.
Wired into:
- ApproveGroupButton (bulk "Approve all" on Action Queue)
- ActionButtons (per-row Approve / Reject)
- FeaturedCard "Run Now" (Prompt Library hero CTA)
Purely additive — no UI surface, no fallback, no error path. The original
Elon-led mobile review queue called these out as the dopamine-hit slots
that make a tap feel like "the thing happened" instead of "did it work?".
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
FetchErrorState grew a `detail` prop rendered as a smaller subline below the
friendly headline. Callers thread useFetch's typed `error` (and the
API-payload `data?.error` where present) so the user can distinguish:
- "Couldn't load GitHub status" / "Timed out after 15s" ← AbortError
- "Couldn't load weather" / "HTTP 500" ← server error
- "Couldn't load calendar" / "Failed to load" ← network drop
Wired into GitHubStatus, SystemStats, CalendarCard, WeatherCard. Verified
live on /projects — CI panel now shows the "Timed out after 15s" subline
correctly when /api/github exceeds the 15s ceiling.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Every useFetch caller now gets an AbortController-backed abort ceiling unless
they explicitly opt out via timeoutMs:0. Default is 20_000 — generous enough
for cold serverless paths but tight enough to catch a genuinely hung call.
This closes the gap for the three remaining unguarded callers — AccountSettings
("/api/me/connected-accounts"), ProjectProfile ("/api/prompts/agent" and
"/api/user-projects/[id]") — without per-site opt-in.
Existing tighter overrides remain: 8s weather, 10s system, 12s calendar,
15s GitHub. Pass timeoutMs:0 to disable entirely (no current callers do).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Both polls call shell tools that can hang on flaky external APIs (gcal,
weather.sh). Without a client timeout the cards stay in skeleton state for
the full poll interval (5 / 10 minutes) when an upstream is slow.
- CalendarCard: timeoutMs 12_000 — gcal Python often takes 4-8s warm.
- WeatherCard: timeoutMs 8_000 — open-meteo HTTP is typically sub-second.
Both fall through to FetchErrorState + Retry on abort, matching the pattern
established for GitHubStatus (eed1228) and SystemStats (7ab0017).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
/api/system runs four shell tools each capped at 5s; a 10s client-side abort
gives 2× margin for network/render jitter while ensuring a hung call resolves
to FetchErrorState instead of pinning the panel on stale data for the full
30s poll interval. Uses the timeoutMs option introduced in eed1228 for
GitHubStatus.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ProfileSettings's username field displayed "{location.host}/u/" which is
localhost:3000 in dev and the vercel preview URL on PR deploys — confusing
when the published canonical brand is APP_DOMAIN. Drop the window check and
render APP_DOMAIN directly so the prefix is consistent everywhere and the
SSOT in config/brand.ts is the single point of change for rebranding.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
/api/system now returns disk as { totalMiB, usedMiB, availMiB, pct } pure
numbers instead of shell-suffixed strings ("233G", "175G", "80%"). df -BM +
awk gsub strip the M / % so the client receives MiB integers it can defer to
formatBytes for display rounding.
SystemStats:
- Drop the inline mibToGib helper — formatBytes(value, "MiB") owns it now.
- RAM/Swap render via formatBytes (auto-promotes MiB → GiB).
- Disk row drops the inline "(X free)" suffix and moves it to its own line
below the progress bar — fixes mobile truncation under the Ask Ivy FAB
and makes the X / Y column right-align cleanly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
useFetch grew an optional timeoutMs that wires an AbortController to the
underlying fetch and surfaces an "AbortError" as a normal error string so the
caller's existing error branch handles it. GitHubStatus passes 15_000ms — well
under the server's 30s github-status.sh ceiling and short enough that a slow
upstream resolves to FetchErrorState + Retry instead of an indefinite spinner.
Verified live on /projects: at ~13s the skeleton transitions to "Couldn't load
GitHub status / Retry" with no other panels affected.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Multi-touch mobile polish from a thorough panel review at iPhone-class viewport:
- app-main pb-20 → pb-40 so the Ask Ivy FAB never overlaps the last content
row at scroll-end on /control, /system, /memory.
- PrivatePinGate: inputMode=numeric + pattern=[0-9]* + autoComplete=one-time-code
+ maxLength=20 → iOS opens the numeric keypad instead of full QWERTY.
- Move /goals out of (private)/ — goals are motivational, no reason to gate them
behind the same PIN as people/money/habits/events.
- ProfileSettings: initials-circle fallback when user.image is empty or fails to
load (was rendering broken-image icon).
- SettingsTabs + SummaryBar + ProjectGrid filter chips: ui-scroll-fade-right mask
hint so users can see the row is horizontally scrollable.
- AskIvyModal: hide desktop keyboard hints on touch, show "Tap 🎤 for voice"
instead — Shift+Enter is meaningless on mobile.
- project-card-sections: aria-label on Focus + Collapse icon buttons.
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
Every screenshot from /control showed the same visible bug: cards
saying "Codex working" with timers like 8m, 12m, 61h on tabs the user
knows are sitting idle. Cursor's parallel audit confirmed the root
cause: /tmp/agent-current-prompt-<tab> is only deleted by Claude's
Stop hook, and Codex (interactive TUI) has no Stop hook — so any
Codex dispatch leaves the sentinel file behind indefinitely. Two UI
consumers were then reading this stale signal without defense, and
they were reading it via two different code paths:
- getProjectDisplayState() drove the badge (Working/Ready/Idle)
- ProjectStatusChips read project.currentPrompt directly for the
chip ("Codex working" / "Codex ready")
Anti-SSOT: two rules of "is the agent working?" that can drift apart.
This commit fixes both with one source of truth:
1. New isCurrentPromptStale(project, nowS) helper in
control-presenter.ts. Layered signals (positive → time-based
fallback):
a. session.status === "ready" (Claude path)
b. session.mtime > currentPromptStartedAt + 5 (any agent
that writes a handoff file — proves the cycle closed)
c. nowS - currentPromptStartedAt > 30 min (hard cap for
agents that never write a session file at all)
2. getProjectDisplayState() now nulls out currentPrompt when stale,
so isRunning / tone / stateLabel / showRunningBanner all flip
to idle/ready naturally — no downstream edits needed.
3. New isAgentWorking field on ProjectDisplayState. ProjectStatusChips
accepts it as a prop and uses it for chip tone + label.
project-card-sections passes display.isRunning; ProjectTile
passes display.isAgentWorking. Backward-compat fallback to raw
project.currentPrompt when prop is omitted.
Risk: 30-min cap could falsely flip a legitimate long-running task
to idle. Mitigated because long real work writes intermediate session
files (signal b fires first) and erring toward false-Idle is the
explicit user-preferred tradeoff while we lack a better signal — the
previous "forever working" false-positive was the complaint.
The Path 1 (openclaw worker) error branch updated state:'error' but left
outcome NULL, so the dispatch reasoner's learning loop never saw worker-
start failures in the recent-outcomes streak. One-liner: add
outcome:'error' to the failure-mode updateOrchestrationRun call. Caught
in the Phase 0 audit against the prior 'outcome tracking loop' plan —
all other plumbing was already shipped; this was the one gap.
The composite primary key (user_id, project_key) is case-sensitive,
so two writer paths could each insert a row for the same logical
project — the API canonical-name path used user_projects.name
("Cockpit") and the daemon path used the zellij tab name
("cockpit"). The conflict target missed and a duplicate row was
inserted. Reads then returned both rows, and downstream sync code
could let the empty row stomp the row holding the real prompt
queue (the exact incident that 852c51b's runtime-state defensive
grouping was working around).
Migration 0012 fixes this at the database layer:
1. Dedupe existing collisions deterministically. The survivor is
the row with the longest prompt_queue (so no queued user data
is lost), with updated_at DESC as tiebreaker. Other fields like
tab_open and session_status repopulate from the next daemon
heartbeat, so dropping them on the loser row is acceptable.
2. Add a functional unique index on (user_id, lower(project_key)).
From this point on, any writer that bypasses normalization gets
a DB-level constraint violation instead of silently creating a
stale duplicate.
Applied to Neon prod: confirmed 0 remaining collisions, the right
row was kept ('cockpit' lowercase with the 2-item queue, not the
empty 'Cockpit' row), and a follow-up probe with
INSERT 'CoCkPiT' rolled back inside BEGIN…ROLLBACK was rejected
with the expected unique_violation error.
Schema declaration uses uniqueIndex + sql\`lower(\${col})\` so
drizzle-kit push treats the live state as authoritative — verified
no drift on project_states. (Unrelated orgs_slug_unique drift was
flagged by drizzle but is out of scope for this commit.)
The defensive .toLowerCase() grouping in runtime-state/route.ts and
stream/route.ts remains useful for in-memory dedup of legacy state
but is no longer load-bearing — the DB now guarantees uniqueness.
The DB column landed with the strategist v1 commit (852c51b) but the
settings page had no control for it — users were locked to the default
'strategist' mode unless they hit the PATCH endpoint by hand.
Adds a 2×2 button grid with labels + descriptions (matching the existing
popup-mode pattern), wires the field through state/dirty/save, and
extends the PATCH zod schema to accept the four valid values. Replaces
the previous carryover hack in setData that read the field back from
the previous DB load.
Config SSOT is config/beacon.ts (AUTO_INJECT_MODE_VALUES +
AUTO_INJECT_MODES with label/description). The zod enum on the route
references the same const tuple, so adding a fifth mode is a one-file
change. Verified end-to-end against the live local cockpit-app: GET
returns the field, PATCH round-trips, invalid values are rejected
with a structured error.
Closes the gap Cursor's audit named and Claude's response confirmed:
auto-inject had become 'generic next_best ladder' instead of
'context-aware prompt that drives the product forward.' Thirty commits
of plumbing (status field, queue in DB, daemon heartbeat, /tmp mirror)
didn't change what the model reads when it wakes up. This commit does.
Full reasoning + design in content/thoughts/strategist-and-prompt-quality.md.
Changes (in order of blast radius):
1. /api/control/dispatch — strategist v1 (the meat)
• DispatchAction expands from 'queue | nextbest' to add 'composed'
and 'off'.
• DispatchResult.prompt holds the Groq-composed body when
action='composed'.
• Groq prompt asks for one of three actions + an optional PROMPT:
body. The composer drafts a fresh prompt from handoff.next,
queue tail, recent commits, and outcome streak — concrete verbs,
named files where possible, ≤2000 chars.
• maxTokens 100 → 1500 so the composed body has room.
• Reads auto_inject_mode from beacon_settings and gates:
off → action='off' (suppress), queue_only → queue or off,
next_best → skip Groq + return nextbest, strategist → full chain.
• Strategist now runs even with empty queue — that's when it's
most valuable (smart nudge from session.next + commits alone).
Previously short-circuited to nextbest on empty queue.
2. src/lib/orchestration/renderers.ts — SSOT next_best body
• Adopts the bash hook's shape (the concrete one user has been
pasting every loop turn). Old abstract scan ladder is gone.
• Model-agnostic: avoids assumed tech stack (no hardcoded `git
status` / `npx tsc`). Verifies via 'are there type/lint/compile
errors' phrasing that translates across runtimes.
3. src/hooks/use-project-card-actions.ts — consume composed bodies
• handleAutoInject branches on action='composed' and injects the
returned prompt body as a custom prompt instead of firing
sendIntent('next_best').
• Respects action='off' from mode_gate by returning early.
• Pre-fetch fires whenever ready (not gated on queue.length > 0)
so the strategist can compose even when queue is empty.
4. beacon_settings.auto_inject_mode (drizzle/0011)
• New text column, default 'strategist'. Values: strategist |
queue_only | next_best | off.
• Schema TS + queries plumbed; UI carryover patched in
BeaconSettings.tsx (full UI for the toggle is a follow-up).
5. /api/control/runtime-state — defensive against duplicate keys
• Found two rows for same lowercase project_key ('cockpit' and
'Cockpit', empty queue won iteration order). Sync now groups
by lowercase and prefers the row with the longest queue. The
duplicate row was deleted from Neon as a one-time fix; long-
term a uniqueness-on-lowercase migration is queued.
Migrations applied to Neon prod: 0011 via psql + neonctl. Local PG
is no longer authoritative (.env.local now points cockpit-app at
Neon; verified daemon-token auth resolves to default user b94a359d
and runtime-state sync writes /tmp/agent-queue-cockpit with the real
queue content).
Tests: tsc clean, eslint clean (src/ + home/), npm run test:home
89/89. UI for autoInjectMode toggle is queued.
Co-developed with: prompt-quality audit pass from Cursor Composer
2.5 + Claude synthesis; provenance + design rationale in
content/thoughts/strategist-and-prompt-quality.md.
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.
58e4366 synced DB prompt_queue → /tmp/agent-queue-<tab> on every
/api/control GET (the UI poll), but only while the UI is open.
When the browser tab is closed, /tmp goes stale; the next session
of the bash hook or home/ /control then reads outdated data.
cockpit-daemon already POSTs to /api/control/runtime-state every
PUSH_INTERVAL with a HEARTBEAT_S=60s floor (commit 247e9e0), so the
endpoint runs at least once a minute on every live cockpit-app
machine regardless of whether anyone's looking at /control. Adding
the same queue mirror at the end of the POST handler closes the
gap: /tmp stays warm independent of UI activity.
Gated on isRuntimeAvailable() — Vercel serverless skips it entirely
since its /tmp is ephemeral and there's no bash hook there. Atomic
.tmp+rename matches the existing pattern. Per-file errors are
non-fatal — DB is the source of truth, the mirror is a convenience.
Sync cost: one getProjectStatesByUserId per daemon push (~1/minute
per active user), plus N file writes (N = projects per user, ~10).
Cheap.
tsc clean, eslint clean, npm run test:home 89/89.
Adjacent gap caught by direct probe: Neon project_states.prompt_queue
for 'cockpit' had 1 item, /tmp/agent-queue-cockpit on the same
machine showed empty array. The drift exists because /api/beacon/
queue/[tab] PUT writes to BOTH DB and /tmp, but on Vercel that /tmp
is ephemeral; the user's local machine never receives that write.
Net: home/'s /control queue badge (3c78208) reads /tmp → reports 0
queued, even though DB has the truth.
Fix is small and stays in cockpit-app: every /api/control GET (which
the UI polls every few seconds while open) now also mirrors each
project's DB prompt_queue out to /tmp/agent-queue-<tab>, gated on
isRuntimeAvailable() so it ONLY runs on the user's local box (Vercel
serverless never touches /tmp pointlessly). Atomic write via
.tmp+rename matches the existing pattern in /api/beacon/queue.
Net effect:
• home/'s queue badge reflects DB reality while the UI is open
• bash hook's two /tmp readers (agent-hook-bridge.sh:413,607) get
fresh data without my touching the file the user has denied
edits to 3x
• cockpit-app's own queue UI keeps working as before (DB is still
the source of truth)
Doesn't address the gap when the UI is CLOSED — /tmp goes stale
then. Tolerable for now since both readers fire when someone is
using cockpit, and the UI is open then. Long-term: periodic
background sync job in cockpit-daemon, or home/ reads DB directly.
tsc clean, npm run test:home 89/89.
Adjacent gap from the queue-storage work — the home/ stack now writes
queue items but doesn't display them. Users on home/ /control had no
visibility into what was queued for each project, even though the
data is sitting in /tmp/agent-queue-<tab>.
Changes:
• /api/state response now annotates each project with queueLen by
reading /tmp/agent-queue-<project>.toLowerCase() and counting the
JSON array. File missing or unreadable → queueLen=0 (no badge).
• New .queue-pill CSS rule (blue, matches the broader pill palette).
• Project header renders '<N> queued' when queueLen > 0, sitting
next to the existing running/status pill.
Stays local-first: no DB dependency from home/. The /tmp mirror is
the right source because it's written by both the cloud route's PUT
(via /api/beacon/queue/[tab]) and home/ itself if invoked from a
direct API call. Cross-stack visibility without coupling.
tsc clean, npm run test:home 89/89.
Two ships shipped the queue-into-prompt path: e6bd03b added the queue
field to OrchestrationTaskRequest + renderQueueBlock in
src/lib/orchestration/renderers.ts; 1cacfd2 plumbed it through home/'s
render.ts + /api/dispatch. Neither was covered by the existing
home/render self-tests (which only verified that all 12 intents
produce non-empty strings).
A future change to renderQueueBlock — different header wording, item
ordering, overflow threshold — would silently break both stacks
without any regression signal. Four new cases pin the contract:
• queue items render under 'User's prompt queue for this project'
and are 1-indexed
• empty queue → no block (suppression for the trivial case)
• undefined queue → no block (back-compat for callers that don't
plumb queue yet)
• queue > 10 items → first 10 + '…and N more' overflow indicator
home/render: 16 tests (was 12); full home/ suite total: 89/89.
tsc clean.
home/render.ts gained an optional queue field (mirroring
OrchestrationTaskRequest.queue from e6bd03b); home/server.ts's
/api/dispatch now sources the queue from caller-supplied body OR
falls back to /tmp/agent-queue-<tab> (the file mirror cloud's
/api/beacon/queue/[tab] writes for cross-stack visibility). Either
source threads through buildPromptForDispatch → renderPromptForDispatch
→ renderQueueBlock, so a home/-dispatched prompt now carries the
same 'User's prompt queue for this project' block the cloud path
already had. Closes the asymmetry: home/ and cloud both surface
queue context to the agent now.
Queue items added after the drained head still render — the agent
sees both what they're currently working on (the dispatch prompt
itself) and what's queued behind it.
tsc clean, npm run test:home 85/85.
Closes the queue-storage gap raised in last turn's evaluation. Before:
the per-project prompt queue lived in /tmp/agent-queue-<tab>, which is
ephemeral on Vercel (lost on cold start) and not user-scoped. After:
project_states.prompt_queue (text[] not null default '{}') is the
source of truth — persists across browsers, Vercel cold starts, and
backed by the same per-(user, project) PK as the rest of session
state.
Files touched:
• drizzle/0010_project_states_prompt_queue.sql — ADD COLUMN IF
NOT EXISTS text[] not null default '{}'. Applied to both Neon
prod and local Postgres via psql.
• src/db/schema/project-states.ts — promptQueue field added next
to sessionStatus (also new this week, similar shape).
• src/app/api/beacon/queue/[tab]/route.ts — rewritten to read/
write the DB row. Adds proper auth (was unauthenticated; closed
a real auth gap on the way through). Keeps a best-effort file
mirror so scripts/agent-hook-bridge.sh's two /tmp/agent-queue-*
readers don't break (user has denied prior edits to that file
3x — file mirror stays until that path is touched).
Auth note: the old route had NO auth check. Any unauthenticated
caller could read or overwrite any tab's queue. usePromptQueue is the
only consumer in the codebase and runs in an authed session, so the
new 401 doesn't break any production flow.
What's NOT in this commit (deliberate scope cut):
• The bash hook's two /tmp readers. Long-term they should query
the DB via authed API — that's a separate ticket since user has
repeatedly denied agent-hook-bridge.sh edits.
tsc clean, eslint clean, npm run test:home 85/85.
You called out that the working area on control cards truncates the
prompt with no way to see the full text. The browser title="" tooltip
was the only escape and it surfaced long prompts poorly (small text,
hover-only, often itself truncated by the OS).
Added click-to-expand:
• The prompt label is now a clickable element; clicking toggles full
text (whitespace-pre-wrap, break-words) vs the existing truncation
(1 line for canned prompts, 3 lines for custom prompts).
• A small 'more / less' link button sits next to the 'Working' label
for a clear discovery affordance — clicking either the label or
the button toggles.
• aria-label on the button keeps screen-reader semantics correct.
• Truncation classes are computed up front; the only conditional is
which class string applies (truncated vs expanded).
Default state stays truncated so cards remain scannable. Expansion is
per-card local state — collapses on remount/re-render.
tsc clean, eslint clean.
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.
After 27f31cb + b51fa18 wired the status field into the auto-inject
gates, the home/ Brain's /control UI had no visible indicator of
which projects were marked 'ready' vs 'working'. User couldn't tell
at a glance why an autonomous dispatch was or wasn't firing — the
status was hidden in the handoff text.
Added a status pill rendered next to the project name when no
currentRun is in flight:
• status: ready → green pill, same palette as the running pill
• status: working → yellow pill, same palette as outcome=partial
• missing / empty → no pill (silent, matches the suppress-default)
The render is browser-side JS inside the INDEX_HTML template literal
(the IIFE shape was the cleanest way to keep the conditional inline
without rewriting the surrounding JSX-style map). When currentRun IS
active, the running pill takes the slot as before — status is
implicitly 'working' during a run, so no overlap needed.
No new event kinds, no schema change, no DB touch. The home/ Brain
already parsed status into lastHandoff via the watcher's FIELDS
update from 27f31cb — this commit just surfaces it.
tsc clean, eslint clean, npm run test:home 85/85, smoke-verified the
new HTML lands.
27f31cb introduced the agent-driven status field as the gate for the
cloud /control auto-inject. The home/ Brain's decide() function read
lastHandoff.health but not lastHandoff.status — meaning the home/
stack's autonomous dispatches (autonomy=auto, autonomy=sleep) would
fire on a project whose agent said status=working, contradicting the
cloud's behavior.
shouldAutoExecute now takes a status parameter (defaults to '' for
back-compat with any external callers). When autonomy is non-manual
AND status is anything other than 'ready' (including empty, missing,
or 'working'), it returns false — same strict semantics as the cloud
gate in src/hooks/use-project-card-actions.ts and BeaconClient.tsx.
Manual mode bypasses (user click is the gate).
decide() pulls status from project.lastHandoff?.status and threads it
to all four shouldAutoExecute call sites (the recovery branch, the
queue-head branch, and the next_best branch — caught one I missed on
the first pass by re-running tests).
home/decide tests: 14/14 (was 11) — three new cases:
• sleep mode does NOT fire when status='working'
• auto mode does NOT fire when status is missing
• manual mode ignores status (user click IS the gate)
Plus an update to the existing 'sleep auto-fires on high confidence'
fixture to include status: 'ready' (otherwise it'd fail the new
gate). All eight home/ suites: 85/85 total (was 82).
tsc clean, 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.
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.
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.