Without this, a Vercel deployment with CRON_SECRET unset would leave the
janitor publicly callable — anyone hitting GET /api/crons/prune-debug-logs
could delete forensics data. The previous version silently allowed the
call when the env var was missing (intended for local dev convenience).
Tighten the gate:
- if (VERCEL=1 && !CRON_SECRET) → 503 "CRON_SECRET not configured"
- if (CRON_SECRET set) → require matching Bearer header (existing behavior)
- if (VERCEL unset && !CRON_SECRET) → allow (local dev curl path)
Also set CRON_SECRET in Vercel production envs via `vercel env add`
(64-char hex, encrypted in the dashboard) so the Vercel-issued cron
request matches and runs, and any unauthenticated probe gets 401.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
debug_logs accumulates without bound — every /api/inject failure, every
Groq fallback, every auth event adds a row. Add a daily Vercel Cron Job
that prunes:
- level=info | warn rows older than 30 days
- level=error rows older than 90 days (postmortem value, longer kept)
Implementation:
- pruneDebugLogs({nonErrorOlderThanDays, errorOlderThanDays}) helper
composes the two retention windows in one DELETE via OR + returning(),
returns the deleted row count.
- GET /api/crons/prune-debug-logs invokes it. Auth: Bearer ${CRON_SECRET}
if the env var is set (Vercel Cron sends this), otherwise allow
(local dev — devs can hit it directly with curl).
- Janitor logs its own outcome to debug_logs (level=info) so we can see
in production whether the cron actually fires every day. Errors land
as level=error rows with the same source string.
- vercel.json crons[] entry: 0 3 * * * (daily at 03:00 UTC) — within the
Vercel free-tier daily-cron allowance.
Verified locally: curl /api/crons/prune-debug-logs → {"ok":true,"deleted":0}
(no rows are 30+ days old yet — only 8 auth entries exist).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Extend the debug_logs capture from /api/inject (99fca82) to the other two
primary server entry points where failures previously vanished into
journalctl with no DB forensics trail:
/api/orchestration/run
- claude path: inject failed → level=error, meta(adapter, intent, projectKey)
- codex/gemini path: inject failed → same
- openclaw path: scheduleOpenClawWorker failed → meta includes runId
/api/control/dispatch
- Groq fallback (key invalid / rate-limited / 5xx / timeout) → level=warn
because dispatch gracefully degrades to queue order, but the cause
still belongs in forensics.
Same fire-and-forget logDebug pattern — telemetry can never break the
observed operation. Auth 401 + the 503/501 "config issue" paths are
intentionally not logged (noisy + not actionable).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per pattern_vercel_log_fallback (memory): journalctl on Vercel is unreliable
for post-incident forensics. The debug_logs table already existed in Neon
(raw-SQL writes from src/auth.ts) but had no Drizzle model and no typed
helper, so other call sites couldn't ergonomically write to it.
Add the missing layer:
- src/db/schema/debug-logs.ts: Drizzle model that matches the live shape
exactly — column meta (not context), no user_id (the existing auth
writes don't use it; adding it would require a destructive schema change).
- src/db/queries/debug-logs.ts: logDebug() fire-and-forget helper that
swallows insert failures (telemetry can never break the operation it
observes) and a getRecentDebugLogs reader for a future admin view.
- src/app/api/inject/route.ts: logDebug calls on both failure paths
(unknown-tab → warn, executeInject !ok → error). Meta includes userId,
tab, mode, adapter, promptKey, promptLabel, customPromptLen, and
runtimeAvailable so the next incident has full context without needing
Vercel logs.
Schema push was blocked by drizzle-kit interactive-only column-conflict
prompts on unrelated existing tables — used CREATE TABLE IF NOT EXISTS via
postgres-js to verify the table shape on Neon, then aligned the Drizzle
model to the existing columns. No destructive migration needed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Incident 2026-05-20: user sent a custom prompt from the mobile site, the
request silently failed (or the global page-top error went unseen because
the user was scrolled to a project card), and the typed text was lost.
Queried pending_commands — zero unclaimed, zero stuck, zero failed in the
last hour, so the request never reached the server. The user thought it
worked.
Root causes (all of them):
1. sendCustom had no per-card error surface — only ControlPanel set a
global error at the top of the page, invisible on mobile when
scrolled.
2. ControlPanel's onInject catch SWALLOWED the throw so children had no
way to react.
3. The custom input wasn't persisted anywhere — a failed send + page
close meant typed text was gone.
4. PromptInput rendered no failure state at all.
Defense in depth (all in one commit):
- src/lib/draft-storage.ts (new): per-tab localStorage SSOT
(getDraft / setDraft / clearDraft). Survives refresh, tab close, failed
send. Best-effort with try/catch around every localStorage call.
- useProjectCardActions: lazy-init custom from getDraft, wrap setCustom
to write to localStorage on every keystroke, sendCustom/sendText
catch+expose sendError and only clearDraft on confirmed success.
Exports sendError + clearSendError.
- ControlPanel: onInject / onRunWithBrain / onRunCustomPrompt now
setError(global) AND re-throw so child cards can also display inline.
- ProjectCard + project-intent-panel: thread sendError + onClearSendError
through to PromptInput.
- PromptInput: red inline error banner above the textarea — "Send failed
/ <reason> / Your text is preserved below — fix the issue and tap Send
again" with a dismiss X. Visible right where the user is looking.
Outcome: a failed send is now impossible to miss AND impossible to lose
the typed text from. Every layer of the failure path has its own guard.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Each essay now generates its own preview image via Next.js file-convention.
Card layout on the same dark canvas as the root + profile OG cards:
[crosshair mark] Cockpit · Essay (top-left brand stamp)
Title (64px, ≤3 lines clamped)
Summary (28px, ≤2 lines clamped)
date · read time · by author [tag] [tag] [tag] (bottom row)
Verified live on /thoughts/the-model-agnostic-layer/opengraph-image-1fqrkj:
1200×630 RGBA PNG, ~59KB, all fields render correctly (title fully visible
on three lines, summary on three lines, "2026-05-18 · 14 min read · by Ivy",
"product / strategy / agents" tag pills on the right).
twitter-image.tsx imports the default and re-declares the route-segment
config inline (Next.js still rejects re-exports of those constants).
Note on URL: Next 16 file-convention appends a build-time content hash to
the OG route on this codebase (-1fqrkj suffix), unlike /u/-/opengraph-image
which gets no hash. The meta tag emits the correct hashed URL automatically.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Essay route's generateMetadata returned only title + description, so the
root layout's generic Cockpit card was inherited everywhere a link was
shared. Add openGraph (type=article + publishedTime + tags) and twitter
(summary_large_image) blocks so Slack / LinkedIn / Facebook render the
preview as a recognized article with the essay metadata.
Verified rendered HTML on /thoughts/the-model-agnostic-layer:
- og:title = essay title
- og:type = article
- article:published_time, article:tag (× N)
- twitter:card = summary_large_image, twitter:title, twitter:description
Image still falls back to the root /opengraph-image (generic Cockpit card)
until a per-essay image generator exists — out of scope here.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
getDefaultUser query already returns the single canonical site-owner.
Append /u/<username> to the sitemap (priority 0.9, weekly changefreq)
so the canonical public profile gets crawled and indexed.
Privacy guardrail: other users' /u/[username] URLs stay OUT. A public
sitemap that enumerates every registered account in a multi-tenant
deployment leaks the user list to anyone fetching /sitemap.xml. Only
the explicitly-flagged isDefault=true user is intentional public.
Function is now async (sitemap default export supports promises) since
getDefaultUser is async.
Verified: /sitemap.xml now contains <loc>…/u/cat</loc> alongside the
static + essay entries.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Both routes were auth-redirected (302 → /sign-in) before this — Googlebot,
Bingbot, etc. saw a redirect instead of policy / URL list.
src/app/robots.ts (file-convention): Allow /, disallow the app shell
(/control, /today, /projects, …) + /api/ + /_next/. Points sitemap at
APP_URL/sitemap.xml and sets host=APP_URL.
src/app/sitemap.ts (file-convention): Static marketing surface +
filesystem-backed essays (listThoughts iterated through changeFrequency
yearly). /u/[username] omitted — per-user, would need a DB scan; can be
added later if profile discoverability becomes a priority.
src/proxy.ts allowlists robots\.txt + sitemap\.xml in the same exclusion
matcher that already covers opengraph-image / twitter-image / icon.svg /
manifest.json — search engines and social crawlers are all the same
class of unauthenticated content fetcher.
Verified: 200 text/plain on /robots.txt, 200 application/xml on /sitemap.xml.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Public-profile nav was a lone BrandMark — anonymous visitors had to type
URLs to reach Features / Pricing / Whitepaper / Sign in. Mount the same
PUBLIC_NAV_LINKS the landing + auth pages use, plus a Sign in link, on
the right side of the existing nav.
Desktop-only (md:flex) per the established PublicSurface pattern — mobile
already has the footer CTA + tap-the-brand-to-go-home. Subtle styling
(text-secondary → text-primary on hover) so the links don't compete with
the profile content.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Empty-state profiles (team member, zero public projects, no writing) rendered
just an avatar + "No public projects yet" with nothing below — barren for
share-target visitors. Even non-empty profiles ended abruptly with the last
essay or project card.
Add a subtle footer below all sections: APP_NAME · APP_TAGLINE on the first
line, "Build your own command center →" link to /sign-up on the second.
Always visible — costs ~40px of trailing space but every shared profile
now ends with a clear next step for the visitor.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Personalized 1200×630 card via Next's file-convention so shared profile
links render the person, not the generic Cockpit card. Card layout:
[avatar/initials 200px circle] Display Name (84px)
@handle (36px, muted)
N public projects · Cockpit · tagline
Implementation notes:
- getInitials moved from Avatar.tsx ("use client") to lib/initials.ts so
the server-side OG generator can import it without crossing the
server/client boundary. Avatar re-exports from the new path so existing
client callers keep working.
- ImageResponse / Satori requires explicit display:flex on any div with
multiple children, AND treats adjacent text-node + variable as multiple
children — switched `@{username}` to `{`@${username}`}` and joined the
meta-row spans similarly. Caught by satori's runtime error in service
logs ("Expected <div> to have explicit display: flex").
- twitter-image.tsx imports the default and re-declares the route-segment
config inline (Next.js rejects re-exports of those constants).
- DB lookup runs on Node runtime (default for app route handlers), not
edge — postgres-js needs Node.
- 404/not-found path renders a "Profile not found" card so even bad
handles emit a sane preview instead of a 500.
Verified: curl -L on /u/cat/opengraph-image returns a 1200×630 PNG, RGBA,
~144KB, with the user's avatar + name + handle + project count rendered.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Root layout now emits openGraph + twitter metadata blocks (siteName,
title, description, url, locale, summary_large_image card) so links shared
to Slack / Twitter / LinkedIn / iMessage render an intentional preview
instead of plain text.
The image is generated at /opengraph-image via Next.js's file-convention
ImageResponse — a 1200×630 dark canvas with the crosshair brand mark,
APP_NAME wordmark, and APP_TAGLINE. /twitter-image re-exports it (Next
rejects re-exported route-segment config, so the consts are duplicated
inline). metadataBase points to APP_URL so Next can build absolute URLs.
Proxy matcher allowlisted /opengraph-image, /twitter-image, /icon.svg,
/manifest.json — social crawlers, PWA manifests, and tab icons must serve
without an auth redirect. Verified: all four return 200 image/PNG (or the
correct content-type) on a fresh curl from an unauthenticated client.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Root layout's "%s — Cockpit" template was wrapping the invite layout's
"Join Cockpit" into "Join Cockpit — Cockpit". Pass title.absolute to bypass
the template entirely — verified curl <title>Join Cockpit</title>.
Same family of fix as 28b0490, different remediation (absolute vs strip)
because "Join" is the verb and "Cockpit" is the brand — neither should be
the suffix.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Root layout's title template ('%s — Cockpit') was double-suffixing pages
that already embedded "— Cockpit" in their own metadata: PublicProfilePage
("George — Cockpit — Cockpit"), its Not Found variant, and the whitepaper.
Fix at the page level — return just the base text and let the template
append the brand. Verified via curl:
- /u/cat → <title>George — Cockpit</title>
- /whitepaper → <title>Whitepaper — Cockpit</title>
Caught during the browser QA pass on /u/cat.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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>
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.
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.
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.