Commit Graph
1304 Commits
Author SHA1 Message Date
g-but bd2c0af290 feat(beacon): default auto_inject_mode to queue_only for new users
Today a fresh customer signing up gets the strategist firing autonomous
prompts at their projects the moment the daemon connects — Groq composing
prompts from context the customer never saw, with no human in the read-loop
between turns. That IS the closed-loop drift failure mode the prompt-design
conversation just spent a day diagnosing, made concrete and shipped to
every new user on day one.

Flip the default from "strategist" to "queue_only". New users must
explicitly opt into autonomous loops via /control settings. Existing
users with a beacon_settings row keep their setting (including the
founder, who explicitly chose strategist long ago — DB DEFAULT only
applies to new INSERTs, existing rows untouched).

Four touchpoints, all aligned:
  • src/db/schema/beacon-settings.ts — column default + explainer comment
  • src/db/queries/beacon-settings.ts — DEFAULTS{} when row absent + coerceAutoInjectMode fallback
  • src/app/api/control/dispatch/route.ts — `?? "queue_only"` fallback for missing-settings race + leading comment
  • src/components/settings/BeaconSettings.tsx — useState initial (cosmetic; replaced by fetch)

The single highest-leverage commit from the prompt-design conversation —
binary protection for every new user against autonomous-strategist drift,
zero behavior change for existing users.

Bootstraps the very first roadmap.md primitive at
~/.claude/sessions/Cockpit.roadmap.md, where this change is the inaugural
DONE entry and the full LOOP v2 / strategist-guardrails / blockers-
primitive / dispatch-wrapper / daemon-signal-computation plan is T1.
2026-05-25 16:04:08 +02:00
g-but cfe7be0322 fix(agent): ship install-daemon.sh in the bundle + wire --install to find it
After f3a08fd a new customer's daemon supports all three agents, but it
still dies on shell exit — the install incantation says "start the
daemon: ~/.local/share/cockpit/cockpit-daemon.sh" which is a foreground
process. The `--install` flag was supposed to register a systemd user
service via install-daemon.sh, but that file wasn't in the bundle and
the agent CLI only looked in process.cwd()/scripts/.

Three-file change:

  • route.ts FILES + next.config.ts outputFileTracingIncludes add
    install-daemon.sh (now 12 files in the bundle).
  • cockpit-agent.js --install handler now prefers ${DAEMON_DIR}/
    install-daemon.sh, falling back to process.cwd()/scripts/install-
    daemon.sh for developers running from inside the repo.

install-daemon.sh's existing structure works in the flat ~/.local/share/
cockpit/ layout without modification: WorkingDirectory + ExecStart use
$SCRIPT_DIR (= the daemon dir, all 12 files siblings), and the token
arrives via env from the CLI's spawn — bypassing the PROJECT_DIR/
.env.local fallback that would have been wrong for non-clone users.

After this, `curl … | node - init --token ck_… --install` enrolls the
daemon as a systemd user service in one shot — survives shell exit,
reboot, and restarts on failure.
2026-05-25 01:06:05 +02:00
g-but f3a08fde2b fix(agent): bundle the codex/gemini runners + python helpers in /api/agent/daemon
The 4-file bundle that 02c2551 shipped is enough for a new customer
running the Claude agent — but agent-hook-bridge.sh references seven
more sibling files at $SCRIPT_DIR, and absence is silent failure:

  • run-codex-task.sh / run-gemini-task.sh — HARD fail when dispatching
    those agents (the bridge invokes `bash $SCRIPT_DIR/run-<agent>-task.sh
    ...` with no fallback path; tab gets the command but the runner
    doesn't exist)
  • beacon.py (+ _beacon_config.py import) — audio beacon silently no-op
  • get-idle-secs.py — X11 idle detection falls back to "always idle"
  • notify-choice.py — zenity prompt silently fails
  • sync-agent-runtime-config.py — silent no-op

Each Python helper is wrapped in `|| true` / `2>/dev/null` in the
bridge so the daemon doesn't crash, but the feature degrades and the
user has no signal why. The codex/gemini runners DO crash dispatch
for those agents.

Two-file change: add the 7 missing files to FILES in route.ts and to
outputFileTracingIncludes in next.config.ts. All cross-references in
the added files resolve within the bundle (run-*.sh call back into
agent-hook-bridge.sh; beacon.py imports _beacon_config — both shipped).
Bundle grows from 4 files / ~20 KB compressed to 11 files / ~28 KB —
still under one HTTP round trip.

Verified locally with the same pure-Node ustar builder the route uses
(scripts/test-tar-v2.mjs equivalent): all 11 files extract at the
destination root, bytes-identical to repo source, 0755 mode, valid
under system `tar -tz`. Tsc + eslint clean.

After this lands, a new customer's daemon supports Claude, Codex, AND
Gemini agent dispatch end-to-end without a repo clone.
2026-05-25 00:57:09 +02:00
g-but fcc56f18d2 fix(agent): build daemon tarball in pure Node so /api/agent/daemon stops 500ing
Verified the route live and it returns HTTP 500 "Daemon bundle unavailable" —
my catch block from the spawn("tar", ...) path. Vercel's serverless runtime
either doesn't have the tar binary or spawn can't reach it from a Node API
route. Either way, depending on a system binary for an installer endpoint
is fragile.

Replace with a pure-Node ustar implementation: one 512-byte header per file
(name + mode 0755 + size + mtime + ustar magic + checksum), content padded
to a 512-byte boundary, then a 1024-byte end-of-archive marker, all gzipped
via Node's built-in zlib. ~50 lines of format-spec code, zero external
dependencies, zero system-binary dependencies.

Verified locally against the same scripts/ directory the route reads from:
  • Output is a valid tar.gz (system `tar -tz` lists the 4 expected files)
  • Extracts at the destination root with 0755 mode
  • Bytes-identical to the repo source

Error catch now also reports the message + stack in the JSON body so any
future regression is diagnosable from `curl -s | jq` instead of needing
Vercel runtime logs.
2026-05-25 00:29:55 +02:00
g-but 02c2551ee6 feat(onboarding): one-command public installer for the local daemon
Closes the second half of the connect-step gap. Last week's 422873a
made `curl|node - init --token X` reachable for new customers (the
agent CLI was served via /api/agent/install). 15727a7 added an
honesty disclaimer that the daemon scripts still required a Cockpit
repo clone. This commit removes the disclaimer by shipping the
scripts the same way.

  • New /api/agent/daemon route spawns `tar -czf - -C scripts/ …`
    with the 4 daemon files (~1500 lines bash: cockpit-daemon.sh,
    _brand.sh, agent-hook-lib.sh, agent-hook-bridge.sh) and returns
    the gzipped tarball (~20 KB).

  • next.config.ts outputFileTracingIncludes pins those 4 source
    files to the route so Vercel ships them in the bundle (the route
    reads them via spawn at runtime — they'd otherwise be tree-shaken).

  • src/proxy.ts matcher exception adds api/agent/daemon so the
    download works pre-auth.

  • packages/agent/bin/cockpit-agent.js gets a new downloadDaemon()
    step inside `init`: after writeEnvFile, fetch the tarball, pipe
    into `tar -xz -C ~/.local/share/cockpit`, chmod +x the two
    executables. Soft-fail with a warning if it errors — the token
    write still lands and the user can retry by re-running init.

  • ConnectMachineStep step 3 drops the "requires repo clone, public
    installer coming soon" caveat in favor of the actual path
    (~/.local/share/cockpit/cockpit-daemon.sh).

After this, a brand-new customer's path is:
  1. Sign up + onboarding (username + project + connect)
  2. Generate token → copy one curl command → paste into terminal
  3. ONE command installs both the env file AND the daemon scripts
  4. Run ~/.local/share/cockpit/cockpit-daemon.sh and they're live

No repo clone. No npm publish dependency. Customer-#2-ready.
2026-05-25 00:20:36 +02:00
g-but 15727a706e fix(onboarding): tell the truth about the daemon requiring a repo clone
Last commit (422873a) made step 2 of the connect flow work for new
customers, but step 3 — "Start the daemon: ./scripts/cockpit-daemon.sh"
— was still a lie: the agent CLI only writes a token env file, it does
not install the 783-line daemon script. New customers would copy that
path, get "No such file or directory", and assume they did something
wrong.

Update both surfaces (the onboarding UI's step 3 + the CLI's post-init
"Next steps" output) to acknowledge that the daemon currently requires
a Cockpit repo clone and flag a one-line public installer as coming
soon. The "Skip for now" button on the step already lets non-developer
customers complete onboarding and explore the cloud — the copy now
makes that the explicit, honest path.

Does not change behavior. The real fix (serve scripts/cockpit-daemon.sh
+ _brand.sh + agent-hook-lib.sh via /api/agent/daemon, with a bash
installer that drops them into ~/.local/share/cockpit) is queued — out
of scope for one commit (1500+ lines of bash, multi-file tracing).
2026-05-25 00:03:38 +02:00
g-but 422873a21d fix(onboarding): make ConnectMachineStep actually work for new customers
The connect step instructed new users to run
`npx @cockpit/agent init --token ck_...`, but:

  • `@cockpit/agent` is NOT published to npm — `npm view` returns 404
  • The repo is private, so raw GitHub fallback URLs are also gated
  • Result: every new customer hit a dead end at step 3 of onboarding

The CLI itself is fully implemented at packages/agent/bin/cockpit-agent.js
(144 lines, no external deps — only Node builtins + global fetch). It just
isn't reachable from outside this repo.

Three-piece fix that ships value today without needing npm publish:

  1. New route /api/agent/install (Node runtime) reads the script body
     and serves it as application/javascript. Public, cached 5 min.

  2. next.config.ts outputFileTracingIncludes pins packages/agent/bin/**
     to that route so Vercel's tracer ships the file in the bundle
     (otherwise tree-shaken — the route reads it via fs at runtime).

  3. src/proxy.ts matcher exception adds api/agent/install so the
     curl request reaches the route without a session cookie.

  4. ConnectMachineStep init command swaps to:
       curl -fsSL ${APP_URL}/api/agent/install | node - init --token ...
     The npx form is left in a comment for the eventual swap-back when
     @cockpit/agent ships to npm publicly.

What this still does NOT fix (out of scope for one commit): the daemon
script (`./scripts/cockpit-daemon.sh`) still requires a cockpit repo
clone — the agent CLI only writes the token env file. That's the next
layer of the "no public install path" gap.
2026-05-24 23:55:32 +02:00
g-but 047e29ceb6 test(auth): pin heal decision logic with 6 unit tests via pure split
Extracted the branch logic from healReturningUserOnboarding into a
pure decideHealPatch() function in src/lib/onboarding-heal-decision.ts,
so it can be unit-tested without spinning up Postgres (the previous
location imported @/db/queries/* transitively, which fails at import
time without DATABASE_URL).

The I/O wrapper in onboarding-heal.ts now resolves projectCount and
suggested-username availability up front, then delegates the patch
decision to the pure function. Re-exports decideHealPatch + HealPatch
type so existing callers don't need to update import paths.

Test suite (npm run test:onboarding-heal) covers the six observable
branches:
  - brand-new user → no heal
  - returning user + free suggestion → both fields patched
  - returning user + taken suggestion → onboardedAt only
  - already-onboarded + valid username → no heal
  - legacy migrated row (onboardedAt set, no username) → username only
  - zero projects + onboardedAt set → still treated as returning

The never-throws contract on the I/O wrapper is verified by inspection
(try/catch wraps every await — there is no test-framework-friendly way
to inject a throw through the @/db import boundary without a real DB).
2026-05-24 23:43:12 +02:00
g-but e7f95a34ab fix(auth): make heal never throw so a failed write can't lock users out
Three call sites (jwt callback in auth.ts, /api/onboarding GET, POST)
awaited healReturningUserOnboarding without try/catch. Heal does a
DB write (updateUser) which can fail transiently (DB hiccup, unique
constraint race on the suggested username when two users register
the same email near-simultaneously) — a throw out of heal propagates
to NextAuth as AccessDenied for the jwt() case, or a 500 from the
route handler for the API cases. Either way the user is bounced.

Heal is an optimization layer on the sign-in path. The un-healed user
is still valid — they just fall through to the normal onboarding step
instead of skipping it. So wrap the body in try/catch, log to stderr
(not logDebug — the DB might be the very thing that's failing, and a
logDebug insert would compound the error path), and return the user
unchanged. Every call site is now automatically safe; no per-caller
boilerplate.
2026-05-24 23:32:44 +02:00
g-but 97f77db0ba perf(auth): stop hitting DB on every Node-runtime request
The heal flow in 1f9155b dropped the trigger gate on jwt(), so every
request to a Node handler ran getUserById + countActiveProjects (+ a
possible updateUser). resolveSessionUserId() added a second getUserById
on every API call. Two-to-three DB round-trips per authenticated request,
unconditionally — fine for one user, a real bottleneck at multi-tenant
scale (which is the explicit goal: "start getting other customers").

Restore the original gate: jwt() only refreshes on sign-in or an explicit
session.update(). All the moments that need fresh state (post-onboarding
finish, /onboarding mount, username save) already call update() — so
correctness is preserved.

resolveSessionUserId() trusts a valid-UUID token.id without a DB lookup.
Email fallback still fires for the rare stale-cookie case where the JWT
carries an OAuth provider id instead of our UUID.
2026-05-24 23:12:12 +02:00
g-but 4484750692 fix(onboarding): surface 400 from auto-finish instead of bouncing to /today
The returning-user branch awaited POST /api/onboarding and redirected
unconditionally. When heal couldn't pick a free username (suggestion
taken or unsuggestable), POST returned 400 with "Choose a username
before finishing onboarding." — but the page redirected anyway, the
stale cookie still failed the middleware's onboardingComplete check,
and the user bounced right back here. Infinite loop.

Check res.ok: on success, redirect as before; on failure, surface the
error and fall through to the normal username step so the user can pick
one explicitly.
2026-05-24 22:56:45 +02:00
g-but 1f9155b1ec fix(auth): heal onboarding for returning users with stale JWT cookies
Migrated/returning users with existing projects were stuck on /onboarding
because their JWT cookie carried onboardedAt=null even though the DB had
project data. The middleware then bounced them back every navigation.

Heal them transparently in three places that all share the same primitive:

  - events.signIn: backfill username + onboardedAt when DB shows projects
  - jwt callback: re-heal on every refresh and carry onboardingComplete
  - /api/onboarding GET/POST: heal-on-read so a stale cookie self-corrects

Onboarding page now calls session.update() on mount to sync JWT from DB,
and auto-finishes for returning users instead of forcing them through
the username step a second time.

Session helpers gain resolveSessionUserId(): when JWT carries an OAuth
provider id instead of our UUID, fall back to email lookup so getUserById
queries don't poison API routes with invalid-uuid errors.
2026-05-24 22:43:18 +02:00
g-butandCursor ec6f423b0f feat(infra): Postgres portability, Oracle cutover scripts, and DB kill-switch essay
Vendor-neutral DATABASE_URL helpers, dump/restore/sync tooling, and one-command
Oracle migration after a single console VM step. Publishes the studio-stack
thoughts article and hardens build (dynamic layout, resilient sitemap).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 11:24:20 +02:00
g-butandCursor d1db4e292e feat(control): add live Zellij workspace panel with full tab sync
Control buried fleet state behind config metrics and only showed an open-tab count on cloud. Push the full Zellij tab list from the daemon, store it in runtime_snapshots, and lead the page with a workspace table showing agent, state, and current activity per tab.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-21 19:10:09 +02:00
g-butandCursor 87e6104b35 fix(mobile): redesign bottom nav, Control layout, and page chrome
Mobile was cramped by six bottom tabs plus a floating FAB. Consolidate to five slots with Ask Ivy in the bar, put Control's brain panel first, and tighten spacing/safe-area padding across shell pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-21 17:33:41 +02:00
g-butandCursor 6fb9c199b2 feat: harden cloud onboarding with agent CLI, private zone, and cron DB
Add @cockpit/agent init, server-side PIN enforcement for private APIs,
Postgres-backed cron jobs, daemon auto-continue sync, and cloud/local docs
so SaaS users get a clear path from browser signup to local dispatch.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-21 15:20:03 +02:00
g-butandClaude Opus 4.7 ce642d3a06 fix(control): hide Clear-context on cloud + gate endpoint with 503
Last leaf in the cloud-mode silent-failure audit. The "Clear context"
button in IntentButtonPanel's More-intents submenu called /api/project/
clear-context, which directly invoked injectIntoTab() — a zellij helper
that throws on Vercel because the binary isn't on $PATH. The click
handler awaited the response but threw away the result, so cloud users
saw a brief spinner and then nothing — silent no-op with no feedback.

Two fixes:

  1. /api/project/clear-context now guards on isRuntimeAvailable() and
     returns 503 {ok:false, reason:'runtime_offline'} — mirrors the
     existing shape of /api/project/commit's 503. The previous behavior
     was a generic 500 from the zellij module that didn't carry a
     useful error code.

  2. The button only renders when runtimeAvailable is true. Threaded
     the existing runtimeAvailable prop from ProjectCard into
     IntentButtonPanel; gated the button's render alongside the
     existing currentAdapter === "claude" gate. Cloud users no longer
     see an action they can't successfully fire.

Of the three per-project 503 action endpoints (sync, commit,
clear-context), the other two were already indirectly gated by their
UI: "Update from GitHub" only renders when git.behindRemote > 0,
and the commit chip only renders when uncommitted changes exist —
both require git state that the daemon populates, so they're
implicitly absent on cloud. clear-context was the only one with no
UI gate, so it's the targeted fix.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 09:34:27 +02:00
g-butandClaude Opus 4.7 a7c37c358d fix(projects): GitHubStatus shows 'connect daemon' instead of fake 'No repo data'
Same pattern as commit 3ee1567 (CalendarCard on /today). The
GitHubStatus card on /projects always rendered "No repo data" for
cloud users because /api/github returned `{repos: []}` when
isRuntimeAvailable was false — the github-status.sh script runs the
local `gh` CLI which doesn't exist on Vercel. Users saw an empty
"CI / GitHub" card and had no way to know it was a runtime gap rather
than a genuinely-no-repos state.

Fix mirrors the calendar fix:
  • /api/github cloud branch now returns {repos: [], runtimeOnly: true}.
  • GitHubStatus checks data.runtimeOnly before the repos.length === 0
    branch and renders "CI status shows here once the local daemon is
    connected." — ties the empty state to the same daemon-install
    requirement that DaemonStatusBanner on /control already names.

Local dev (runtimeAvailable=true) behavior unchanged — when the gh
CLI returns no repos for real, the old "No repo data" copy still shows.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 09:22:41 +02:00
g-butandClaude Opus 4.7 3ee1567d56 fix(today): cloud users see 'connect daemon' instead of fake 'No events today'
Onboarding-funnel audit continued — /today is the default landing
surface, and a brand-new cockpitapp.vercel.app user always sees the
CalendarCard render "No events today" because:

  • /api/calendar returns `{events: []}` in cloud mode (isRuntimeAvailable
    is false — the calendar source is `gog calendar list`, a local
    Google CLI), and
  • CalendarCard treats events.length === 0 as the "you have nothing
    on today's calendar" branch.

That's misleading. The user might have a packed calendar locally but
is staring at "No events today" with no indication that the empty state
is a runtime gap, not a real reflection of their day. They have no
reason to ever check Settings or install anything based on what they
see.

Fix: the cloud branch now returns `{events: [], runtimeOnly: true}`.
CalendarCard checks `data.runtimeOnly` before the empty branch and
shows "Calendar shows here once the local daemon is connected." —
links the surface to the same daemon-install requirement that
DaemonStatusBanner on /control already names.

WeatherCard already handles cloud mode correctly via 947fc55 (HTTP
fallback to open-meteo); GitHubStatus is on /projects, not /today, so
out of scope for this commit.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 09:08:59 +02:00
g-butandClaude Opus 4.7 954030218c fix(control): "+ New" toolbar opens Register on cloud instead of Bootstrap
Session next caught the remaining leak. Commit 3b2fbad hid Bootstrap-
with-AI from the /control empty state on cloud (where /api/project/
ai-brief always 503s), but the BrainConfigPanel headerRight toolbar
still had a "+ New" button hard-wired to open BootstrapModal — same
dead-end, just from a different entry point.

Routed the toolbar "+ New" through the same runtimeAvailable check:

  • runtimeAvailable=true  (local dev with claude CLI) → BootstrapModal,
    title "Bootstrap new project" (unchanged behavior).
  • runtimeAvailable=false (cockpitapp cloud) → NewProjectModal, title
    "Register existing project" — same intent ("add a project"), but
    routes to the flow that actually works in cloud mode.

Preserves the affordance for cloud users instead of hiding it; they
still get a working "+ New" button, just one that lands them on the
Register path. Verified live on local — title still reads "Bootstrap
new project" and clicks BootstrapModal as before.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:54:50 +02:00
g-butandClaude Opus 4.7 3b2fbadaae fix(control): hide Bootstrap-with-AI on cloud where the API always 503s
Onboarding-funnel dead-end. A brand-new cockpitapp.vercel.app user lands
on /control, sees the existing empty state's "Bootstrap new project →"
primary button, types a project idea, clicks Generate — and gets a 503
from /api/project/ai-brief because that route requires
isRuntimeAvailable() (true only on local dev where the claude CLI is
on $PATH). Cloud users have no path forward on the Bootstrap button
ever; the only working option is "Register existing project."

ProjectFleetView didn't know whether the runtime was available, so it
showed Bootstrap unconditionally. Threaded the existing runtimeAvailable
flag from useControlData → ControlPanel → ProjectFleetView and:

  • Hide the Bootstrap button entirely when runtimeAvailable is false.
  • Promote Register existing project to the primary button (was
    secondary alongside Bootstrap) so cloud users get one clear CTA.
  • Add a one-line helper underneath: "Bootstrap-with-AI is available
    once the local daemon + claude CLI are installed (see the 'Finish
    setup' banner above)." — sets expectations without dumping a wall
    of text into the empty state.

On local dev (RUNTIME_AVAILABLE=true) the empty state looks unchanged:
Bootstrap stays primary, Register stays secondary, no helper text.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:40:54 +02:00
g-butandClaude Opus 4.7 7c41e9b12c fix(settings): /settings#<tab> deep links open the right tab
Onboarding-funnel audit found a broken handoff. The DaemonStatusBanner
shipped in 0f96cb2 directs new users to /settings#tokens to mint a
daemon token, but SettingsTabs initialized to "profile" with no URL-hash
handling — the deep link silently dumped the user on Profile, and they
had to discover the Agent tab themselves. Two-fix combo:

  1. SettingsTabs reads window.location.hash via a useState lazy
     initializer (pure function so no cascading-renders lint hit and SSR-
     safe via `typeof window` guard). Direct tab-id match wins;
     otherwise a HASH_TO_TAB alias table handles drift between the
     banner copy ("tokens") and the tab id ("agent"). Tokens, agent-token,
     agent-tokens all resolve to the Agent tab.

  2. Banner deep link updated from /settings#tokens → /settings#agent
     (the canonical tab id). The HASH_TO_TAB alias keeps any cached/
     bookmarked /settings#tokens URLs working after the change.

Verified live in Playwright at desktop width:
  • /settings#agent → activeTab=Agent, Agent Tokens panel visible ✓
  • /settings#tokens → activeTab=Agent (alias resolves) ✓

Side-benefit: any future /control nudge that wants to deep-link to a
specific settings tab can now do so just by writing the right hash —
no more silent-Profile dumps.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:27:03 +02:00
g-butandClaude Opus 4.7 0f96cb2e70 feat(control): first-time setup checklist replaces single-command nudge
Onboarding gap surfaced in a user conversation: a brand-new web user
who signs up on cockpitapp.vercel.app gets the life-OS surfaces
immediately, but the agent fleet (the headline /control feature) only
works after they install three pieces locally — none of which the UI
ever names. They discovered the requirement by hitting the wall: try
to dispatch, see DaemonStatusBanner pop up with a single "start the
daemon" command and no mention of Zellij or the agent CLIs.

Replaced the daemonNeverSeen branch of DaemonStatusBanner with a
three-step checklist that names every prerequisite up front:

  1. Install Zellij (link to zellij.dev — the terminal multiplexer the
     daemon injects prompts into).
  2. Install at least one agent CLI of choice (Claude Code, Codex,
     Gemini, openclaw) on $PATH.
  3. Mint a daemon token at Settings → Agent tokens (deep-linked) and
     run the daemon command shown.

The daemonOffline branch (returning user whose daemon dropped — they
already have everything installed) keeps its existing minimal restart
copy unchanged. That user doesn't need the install steps re-explained.

Title shifted from "Local daemon not connected" → "Finish setup to
dispatch agents" so the warning reads as a guided onboarding step
rather than a runtime error.

Side benefits:
  • Deep-link to /settings#tokens makes the token flow discoverable.
  • External Zellij link uses noopener+noreferrer (security default).
  • Existing dismiss button still works — power users can hide it.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:08:49 +02:00
g-butandClaude Opus 4.7 23174f37a3 fix(auth): suppress redundant catch-all log row on CredentialsSignin
After commits 91a5989 (logAuthReject) and 5287904 (logAuthAccept) added
structured forensics for every credentials sign-in attempt, the old
catch-all logger.error path kept firing in parallel — Auth.js calls
logger.error after authorize() returns null, so every credentials reject
landed TWO rows in debug_logs:

  • auth.authorize / warn  — provider/reason/identifier structured row
  • auth / error          — useless "Read more at .../credentialssignin"
                            with minified stack and nothing actionable

Verified live by triggering a reject on prod — both rows landed within
the same second, both pointed to the same user attempt.

The structured row is the canonical one. Suppress the catch-all when
err.type === "CredentialsSignin"; keep every other type flowing
(MissingCSRF, AccessDenied, OAuthCallbackError, system errors) since
those don't have dedicated loggers and the catch-all is their only
debug_logs surface.

Three-line guard at the top of logger.error.

Verified live: triggered a credentials reject against the local dev
server (which writes to the shared Neon DB) and confirmed only ONE
new row landed in debug_logs with source='auth.authorize' —
no companion source='auth' row this time. Halves the row count on
brute-force bursts.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:57:15 +02:00
g-butandClaude Opus 4.7 360e8ce1aa fix(control): toolbar icons 18×18 on tablet — extend tap target through lg
User's "this area still looks awful" complaint had two parts. The model-input
duplication was addressed in ec27b5c; this fixes the other half — the four
toolbar buttons in the BrainConfigPanel headerRight strip (sleep mode,
view mode, refresh, "+ New") were 18×18 px at iPad portrait width
(768×1024), well below the WCAG 2.5.5 / iOS HIG 44px tap target.

Root cause: ui-icon-btn carries `sm:min-h-0 sm:min-w-0` which collapses
the 44px tap target at the 640px breakpoint, but iPad portrait is at
768px and is still a touch-only device. The toolbar bar effectively
became unusable from a tablet — four invisible-to-fat-finger dots
crowded together in the top-right corner.

Fix: added a touch-friendly SSOT variant `ui-icon-btn-touch` that
collapses at `lg:` (≥1024px) instead of `sm:` — keeps 44×44 through
tablet widths, only releases at true desktop where a pointer is the
dominant input. Applied to the three control toolbar buttons that
used ui-icon-btn, plus updated the inline-class "+ New" button from
`sm:min-h-0` to `lg:min-h-0` to match the new policy.

Did NOT change the SSOT `ui-icon-btn` class itself — 14 other call
sites (goal-card-helpers, project-overview-helpers, queue-list, etc.)
sit inside dense desktop layouts where 44×44 would push rows taller.
The new class is opt-in for explicitly touch-friendly toolbars.

Verified live in Playwright:
  • 768×1024 (iPad portrait): all 4 toolbar buttons 44×44 (or 47×44 for
    the wider "+ New").
  • 1280×800 (desktop): same buttons collapse back to 18×18 / 20px —
    desktop look unchanged.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:42:42 +02:00
g-butandClaude Opus 4.7 ec27b5c758 fix(control): hide redundant model input when value matches a chip
User complaint, verbatim: "this area still looks awful. wtf … sonnet
sonnet haiku opus." The BrainConfigPanel on /control rendered both:

  • An <input> with value "sonnet"
  • A chip-toggle button labeled "sonnet" (highlighted as active)

…stacked one above the other. Readers parse the duplication as a bug,
not as "same value, two views." Verified live at 768×1024 (iPad
portrait) — the input was a full-width box visually competing with the
chips below it.

The chips already cover the common case (sonnet / haiku / opus for
Claude, similar lists for Codex / Gemini). The input is only useful
when the user wants a model name NOT in the suggestion list. So:

  • Hide the <input> when modelSuggestions.includes(model) — chips
    handle it.
  • Add a "Custom…" chip after the suggestion chips that, when clicked,
    sets the model value to "" (which falls outside modelSuggestions),
    causing the input to render so the user can type.
  • Clicking any suggestion chip while in custom mode collapses the
    input back away (same logic).

Verified live in Playwright:
  • iPad portrait 768×1024: panel collapses from "input + 4 chips"
    to just "4 chips + Custom…" — no more "sonnet" twice.
  • Custom click → input appears with empty value.
  • Click any suggestion chip → input hides again.
  • iPhone 390×844: same behavior, panel ~30% shorter.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:26:33 +02:00
g-butandClaude Opus 4.7 c6f57d1bbb refactor(orchestration): unify detail field on task_completed/task_failed events
After commit a12d2d9 closed the lifecycle pair across every adapter, the
detail field — the human-readable summary attached to each
orchestration_events row — had drifted across five emit sites into four
different formats:

  • route.ts:354    ${intent.name} — ${message}            (em-dash)
  • route.ts:436    openclaw worker start failed: ${msg}   (verbose prefix)
  • inject.ts:225   ${promptLabel} — ${result.error}       (em-dash)
  • worker.ts:72-3  ${intent} done | ${intent}: ${error}   (split formats)
  • worker.ts:88    ${error.message}                       (no intent context)

Downstream chart/list queries would need to grep multiple separator
formats and strip multiple prefix variants. Unified to one canonical
shape across all five sites:

  success → "<intent_or_label>"            (no trailing " done")
  failure → "<intent_or_label>: <error>"   (single-colon separator)

Operators can now split on the first colon to extract the intent label,
or pattern-match `:.*` to extract the error. The verbose "openclaw
worker start failed:" prefix is gone — the `source: 'api-orchestration'`
column already carries that context.

No schema changes. detail column is still truncated to 400 chars. The
existing task_started emits (which only carry the intent name with no
error) were already consistent and untouched.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:06:23 +02:00
g-butandClaude Opus 4.7 a12d2d9841 fix(orchestration): wire openclaw lifecycle events end-to-end
The codex/gemini branch in /api/orchestration/run emits task_started at
line ~296 before injectIntoTab. The openclaw branch did not. So every
successful openclaw run was invisible in orchestration_events — only
its orchestration_runs row existed. Commit 9a0ac77 closed the worker-
start-failure pair (failed-to-spawn now emits task_failed), but the
happy path and the in-worker error path were both still silent.

Three coordinated changes:

  1. Route emits task_started before scheduleOpenClawWorker — mirrors
     the codex/gemini emit shape so dispatches across all adapters look
     uniform in queries.

  2. scheduleOpenClawWorker signature gains userId, encodes it into
     the base64 payload. The worker needs user_id to write to
     orchestration_events (NOT NULL constraint).

  3. Worker emits task_completed (state:'done') or task_failed
     (state:'error' or thrown) after its terminal updateOrchestrationRun.
     Source field 'openclaw-worker' (vs 'api-orchestration' on the start
     event) so timeline queries can tell which process emitted what.

After this, orchestration_events carries a full started/completed-or-
failed pair for every openclaw dispatch — same shape as codex/gemini —
and the single dispatch-success-rate query introduced in 9a0ac77 covers
every adapter without per-adapter casing.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:55:58 +02:00
g-butandClaude Opus 4.7 9a0ac77ac3 fix(orchestration): emit task_failed on dispatch failure paths
Completes the lifecycle pair on the failure side. After commit 81f4dc3
closed task_started → task_completed on the happy path, the failure path
was still silent in orchestration_events:

  task_failed: 0 rows (lifetime)

…despite three real failure code paths each calling logDebug and either
returning 500 or marking orchestration_runs outcome:'error' — none wrote
to orchestration_events, so a single one-query dispatch-outcome timeline
could only see successes.

Three sites instrumented, each mirrors the existing task_started emit
shape (userId, projectId, projectKey, source, adapter, intent, detail)
with eventType:'task_failed' and detail carrying the truncated error
message:

  1. src/app/api/inject/route.ts !result.ok branch
     — covers the /api/inject failure path (the most-trafficked dispatch
       entry); previously every failed inject left an orphan task_started
  2. src/app/api/orchestration/run/route.ts codex/gemini catch
     — task_started was already emitted ~line 296 before injectIntoTab;
       if that throws, the pair closes here
  3. src/app/api/orchestration/run/route.ts openclaw worker catch
     — the orchestration_runs row was already marked outcome:'error'
       by commit 384cacc, but orchestration_events had nothing — now
       has the matching event row

All three writes are fire-and-forget (.catch(console.error)) so
telemetry failures don't break the user-facing error response. detail
field truncated to 400 chars (column is text but no need to dump full
stack into an events stream).

After this lands, the operator query becomes:

  SELECT date_trunc('hour', happened_at) hr,
         event_type, COUNT(*)
    FROM orchestration_events
   WHERE happened_at > NOW() - INTERVAL '24 hours'
     AND event_type IN ('task_started','task_completed','task_failed')
   GROUP BY 1, 2 ORDER BY 1 DESC, 2;

…which reads as a chronological dispatch-success-rate view. Previously
the same query showed only the 'task_started' column populated.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:44:16 +02:00
g-butandClaude Opus 4.7 81f4dc397a fix(orchestration): emit task_completed alongside input_requested on ready sentinel
Lifecycle telemetry was half-wired. Across all time the orchestration_events
table had:

  task_started:       336
  input_requested:    352
  continue_requested: 146
  close_requested:      2
  task_completed:       0  ← the gap

`task_completed` was a defined OrchestrationEventType in contract.ts but
no code ever wrote it. Every dispatch landed a task_started row, then
either an input_requested (when the agent signaled ready) or nothing
(stalled / closed / etc.) — leaving every started task in an indeterminate
end-state. Pair queries like "how many tasks completed in the last hour"
or "which started tasks never finished" weren't answerable.

Root cause in collectRuntimeLifecycleEvents: when runtime.readyAt fires
it only pushed input_requested. Semantically the "ready" sentinel means
TWO things simultaneously — the agent is done with the current task AND
is waiting for the next input. Emit both events from the same timestamp
so the lifecycle pair closes:

  • input_requested  → drives the UI ready-banner via deriveLifecycleState
                       (existing consumer, unchanged)
  • task_completed   → closes the started/completed pair for queries

shouldPersistLifecycleEvent dedupes per-type so we won't double-write
on subsequent control polls — the second emit is no-op once the table
has a row. No code consumes task_completed yet, so this is forward-only
instrumentation: future commits can answer dispatch-success rate, MTTR
on agent runs, etc., without bookkeeping changes elsewhere.

Cost: doubles the row count for the readyAt code path (~336 lifetime
events → ~672). Trivial.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:32:30 +02:00
g-butandClaude Opus 4.7 41aee9e602 fix(telemetry): replace useless "[object Object]" cause fallback with best-effort shape
A 2026-05-19 accessdenied entry surfaced an unrelated telemetry bug: when
Auth.js threw with a circular-ref `cause` (its internal errors carry
context object refs that loop), JSON.stringify in the unwrapCause helper
threw, the catch ran `String(c)`, and we got `"cause": "[object Object]"`
in debug_logs — the worst possible fallback. Forensics value: zero. The
operator can't tell what kind of object the cause was, what URL or
provider triggered it, nothing.

Replaced the catch path with a best-effort shape extractor:

  1. __ctor   — c.constructor?.name (e.g. "URL", "Request", "AuthError")
  2. scalars  — every own-property whose value is string/number/boolean/null
  3. errors   — nested Errors get {name, message} flattened (one level)

This is safe by construction:
  • No recursion → can't loop on circular refs
  • Reads only own enumerable keys → won't trip getters/Proxy traps
  • Wrapped in its own try/catch → falls back to String(c) if even Object.keys throws

The result for the failing accessdenied case would have been roughly:
  { __ctor: "Object", url: "https://.../api/auth/callback/github", ... }
instead of the useless "[object Object]".

The happy path (JSON.stringify succeeds — every well-behaved cause) is
unchanged, so this only kicks in for pathological cases that previously
gave zero signal.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:20:55 +02:00
g-butandClaude Opus 4.7 5287904cc0 feat(auth): record credentials sign-in successes alongside rejects
Follow-up to 91a5989 (structured reject forensics). The reject helper made
"why did sign-in fail" answerable, but without a matching success record
the pair correlation is lost — debug_logs can't tell:

  • 5 rejects + 1 success  →  forgotten password recovered
  • 5 rejects + 0 success  →  locked-out user gave up OR attacker bailed
  • 0 rejects + 1 success  →  normal sign-in
  • 5 rejects + 5 success  →  busy household sharing a laptop (benign)

Added a `logAuthAccept(provider, identifier, userId)` companion that mirrors
the existing logAuthReject helper but with level:'info' and message
'credentials accepted'. Wired into the success return path of all three
Credentials providers (local / email-password / user-password). Identifier
preserved (email or userId) plus the resolved DB userId so an operator can
join across the user table for richer queries.

Operator workflow becomes:

  SELECT to_char(created_at, 'HH24:MI:SS') t, level, message, meta->>'identifier'
    FROM debug_logs
   WHERE source='auth.authorize'
     AND created_at > NOW() - INTERVAL '1h'
   ORDER BY created_at;

…which reads chronologically as "X tried 5 times, succeeded on the 6th"
or "X tried 5 times, never succeeded" — exactly the signal needed to
distinguish a real lockout from a recovery.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:10:01 +02:00
g-butandClaude Opus 4.7 91a5989182 feat(auth): structured forensics on credentials sign-in failures
debug_logs forensics on auth was useless: six "Read more at
https://errors.authjs.dev#credentialssignin" entries clustered in a
2-minute window on 2026-05-20 with no way to tell brute-force from
forgotten-password from missing-account. Auth.js wraps every
authorize()→null in a generic CredentialsSignin error whose .message
is just the help URL — and the meta only carries the minified stack
(name:"w", type:"CredentialsSignin"), nothing about which provider
was tried or why it rejected.

Three Credentials providers in src/auth.ts (local, email-password,
user-password), each with 4 null-return paths. Replaced all 12
`return null` reject sites with `return logAuthReject(provider,
reason, identifier)` — a small helper that fire-and-forgets a warn-
level debug_logs row capturing:
  • provider:    "local" | "email-password" | "user-password"
  • reason:      "missing-input" | "user-not-found"
              | "no-password-hash" | "wrong-password"
  • identifier:  email or userId, NEVER the password

This makes "why can't I sign in" a one-query answer:

  SELECT meta FROM debug_logs
   WHERE source='auth.authorize' AND created_at > NOW() - INTERVAL '1h'

Operator can now distinguish:
  - 6 wrong-password for one email → forgotten password
  - 6 user-not-found for varying emails → enumeration/brute-force
  - 6 no-password-hash for one email → OAuth-only account hitting
    the password form (a real UX bug worth chasing)

Did NOT modify the catch-all logger at src/auth.ts:67 — it still
captures system errors (DB unreachable, etc.) where the generic
message is appropriate. This change targets the reject path only.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:59:11 +02:00
g-butandClaude Opus 4.7 1762d86ff2 fix(mobile): inline-edit icon buttons — 26px → 44px tap target (height only)
Last unfixed mobile tap-target SSOT. ui-btn-confirm-icon (the green Check
button in inline-edit rows on HabitRow, GoalCard, AddHabitForm,
goal-milestone-helpers, project-overview-helpers, goal-card-sections,
HabitCard) and its paired sibling ui-btn-inline-cancel (the X button next
to it) were both 26-32px tall.

Decision: height-only lift (min-h-11 sm:min-h-0). The instinct to also
add min-w-11 would have made the buttons 44×44 on mobile, but they sit
in flex rows next to a `flex-1` text input — pushing them to 44 wide
would steal ~30px from the input on a 390px viewport and squeeze it
below readability. A 26×44 vertical-strip target is the same pattern
as iOS keyboard arrow keys: narrow but tall enough to thumb-tap reliably,
and the whole inline-edit row now reads as a single 44px-tall control
strip with the input vertically-centered in it.

Verified live on /today AddHabitForm at 390×844:
  • ui-btn-confirm-icon (Check): 26×26 → 26×44
  • ui-btn-inline-cancel (X):     24×24 → 24×44
  • input:                        170×44 (vertically centered, unchanged width)
Desktop at 1280×800: both buttons return to 32px (sm:min-h-0 collapses,
natural p-1.5 height takes over).

This closes the mobile tap-target audit on the canonical button/chip/link
SSOT classes. Every primitive in @layer components now carries the
min-h-11 sm:min-h-0 trick.

tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:47:07 +02:00
g-butandClaude Opus 4.7 94b31ec7d9 fix(mobile): ui-btn-confirm/-sm/-danger — 34px → 44px tap target on touch
Cross-route sweep after the button-primitive fix (commit e811c50) caught
the last big SSOT gap: the confirm/destructive family. /goals showed the
page-level "New Goal" CTA at 112×34 — the primary call-to-action of the
view, sub-spec on every iPhone. Same primitive powers ~20 sites:

  • ui-btn-confirm    — page CTAs ("New Goal"), modal-form submits,
                        ProjectInlineEditors save, JobDetail confirm
  • ui-btn-confirm-sm — every Add row across today (commitments,
                        habits, events), ProjectGoalsTab, AddEventForm,
                        ProjectPromptsTab, ProjectsSettings
  • ui-btn-danger     — destructive confirms (mirrors ui-btn-confirm
                        for consistency)

All three were 34px tall on mobile, under the WCAG 2.5.5 / iOS HIG 44px
floor. Added `min-h-11 sm:min-h-0` to each — same trick already proven
across ui-btn-primary/-secondary/-ghost, ui-btn-add, ui-chip-toggle,
ui-link-subtle, ui-btn-ready-primary.

Intentionally NOT lifted: ui-btn-confirm-icon (icon-only sibling).
Adding min-w-11 there would push adjacent inputs in inline-edit rows
(HabitRow, GoalCard, AddHabitForm, ProjectInlineEditors). Needs separate
layout analysis to decide between width-extend vs row-min-height; tracked
in session next.

Verified live at 390×844:
  • /goals: "New Goal" 34 → 44; stillSmall: []
  • /events: stillSmall: []
  • /money: stillSmall: []
Verified desktop preservation at 1280×800: "New Goal" still 34px
(sm:min-h-0 collapses correctly).

tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:35:48 +02:00
g-butandClaude Opus 4.7 e811c50f3d fix(mobile): ui-btn-primary/secondary/ghost — 36px → 44px tap target on touch
After the chip-picker fix landed (commit 3e7b889), the remaining sub-44px
elements on /control were the two main page CTAs — "Bootstrap new project →"
at 225×36 and "Register existing project" at 221×38 — both using the
universal `ui-btn-secondary` SSOT class. Same story everywhere else: every
modal footer, settings form save/cancel pair, billing tier card, and
control-panel action that uses `ui-btn-primary` or `ui-btn-secondary` was
36px tall on mobile, under the WCAG 2.5.5 / iOS HIG 44px floor.

These three classes are used in 30+ places across the app — modals,
settings (account/profile/billing/team/projects/location/beacon/agent-token),
bootstrap-modal-steps, control-panel-helpers, project-profile-helpers,
PrivatePinGate. One change to globals.css, every secondary/primary/ghost
button gets a real mobile tap target.

Added `min-h-11 sm:min-h-0` to all three sibling button primitives. Same
trick already proven on ui-btn-add, ui-chip-toggle, ui-link-subtle,
ui-btn-ready-primary.

Verified live:
  • /control at 390×844: "Bootstrap new project →" 36 → 44; "Register
    existing project" 38 → 44; sub-44px count 3 → 1 (remaining is the
    icon-only "New" header button, intentional 14×44 on mobile).
  • /people at 390×844: zero sub-44px (Unlock was 36 → 44).
  • /control at 1280×800: secondary buttons stay at 38px, chips stay at
    26/34 — desktop look unchanged thanks to sm:min-h-0.

tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:24:46 +02:00
g-butandClaude Opus 4.7 3e7b889e10 fix(mobile): /control chip pickers were 26–34px tap targets — extend ui-chip-toggle SSOT
Cross-route iPhone-width sweep landed on /control as the worst offender:
9 sub-44px interactive elements, including the per-project LLM model
picker (sonnet/haiku/opus) at 26px tall and the adapter picker
(Claude/Codex/Gemini) at 34px. These are the two most critical controls
on the page — switching agent or model — and they were both physically
hard to hit on a phone.

Two SSOT problems to fix:

1. The adapter chips use the existing `ui-chip-toggle` /
   `ui-chip-toggle-active` SSOT, but those classes didn't enforce a
   mobile tap target. Added `inline-flex items-center min-h-11
   sm:min-h-0` to both — fixes adapter chips on /control plus the
   PeopleGrid filter chips on /people in one stroke.

2. The model chips were a separate bare pattern (`rounded-full border
   px-2.5 py-1 text-xs ...`) duplicated across control-panel-helpers
   and control-panel-modals — a smaller compact variant that never
   made it into the SSOT. Created `ui-chip-toggle-compact` /
   `ui-chip-toggle-compact-active` with the same mobile-tap-target
   trick, migrated both call sites, dropped the now-unused `cn` imports.

Verified live at 390×844: sonnet/haiku/opus and Claude/Codex/Gemini all
26/34 → 44px tap height; /control sub-44px count fell from 9 to 3
(remaining 3 are layout artifacts / 36px primary buttons not in scope).
tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:13:59 +02:00
g-butandClaude Opus 4.7 050526eeb1 fix(mobile): card-header → links and first-run callout had 16-20px tap targets
Continuation of the iPhone-width audit on /today. After the empty-state add
CTAs went 16 → 44px (commit 05315e3), two text-nav links were still under
spec:

  • "Control →" on Recent Agent Work card header — 59×16
  • "Go to Control Panel →" in the first-run callout — 149×20

The first is the ui-link-subtle SSOT, used in six card headers across the
app (RecentRunsCard, EventsDueCard, GoalsDueCard, StuckGoalsCard,
HabitsCard, PersonCard cancel). Extending it with
`inline-flex items-center min-h-11 sm:min-h-0` lifts every card-header →
shortcut to a real tap target on mobile in one stroke while keeping the
desktop one-liner tight — same trick already used by ui-btn-add and
ui-btn-ready-primary. The CardHeader right-slot wrapper is `sm:ml-auto`
so the taller mobile button just lines up below the title; desktop is
unaffected.

The second is a one-off accent CTA in the first-run empty state — added
`min-h-11 sm:min-h-0` inline since it's a unique shape (text-sm,
font-medium, accent-text) that doesn't yet warrant its own class.

Verified live at 390×844 (iPhone 14): zero sub-44px interactive elements
remain on /today. "Control →" 59×16 → 59×44; "Go to Control Panel →"
149×20 → 149×44. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:01:44 +02:00
g-butandClaude Opus 4.7 05315e3a88 fix(mobile): empty-state add CTAs were 16px tall — extend ui-btn-add with min-h-11
Live audit at iPhone width caught the next broken-but-tolerated UX trap:
the primary CTA in the habits empty state ("Add first habit"), the
commitments empty state ("Add commitment"), and four sibling spots
(milestones, log activity, new autopilot job, etc.) were 16px tall —
far below the WCAG 2.5.5 / iOS HIG 44px minimum. A new mobile user
landing on /today with zero habits literally had a 16-pixel tap target
to add their first one.

Root cause: six places copy-pasted the same `flex items-center gap-1.5
text-xs text-text-tertiary hover:text-status-positive transition-colors`
string when the codebase already had `ui-btn-add` for this shape. They
diverged on hover color (status-positive green vs accent-text yellow),
which was a real semantic intent: achievement-flavored "create something
good" vs generic "add a thing."

Fix:
  • ui-btn-add now has `min-h-11 sm:min-h-0` — mobile gets a real 44px
    tap target, desktop keeps the tight one-line look since hover is
    reliable there. Same trick as ui-btn-ready-primary.
  • New ui-btn-add-success sibling carries the green hover for habits,
    commitments, milestones, goal activity, and project prompts.
  • Migrated all six bare-pattern sites to the new class.

Verified live at 390×844 (iPhone 14): "Add first habit" and "Add
commitment" went from 16 → 44px tap height. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:50:21 +02:00
g-butandClaude Opus 4.7 4cfed1973c fix(mobile): hover-only buttons invisible on touch — collapse to ui-hover-reveal
Live audit-driven sweep: grepped for the bare `opacity-0 group-hover:opacity-100`
pattern and found five buttons that vanish completely on touch devices
because there's no hover state on mobile. These are real broken-but-tolerated
UX traps — the icon literally cannot be tapped because it's not rendered:

  • QuickCaptureButton recent-captures trash → can't delete a capture from phone
  • HabitRow edit pencil → can't edit a habit row from phone
  • HabitRow remove X → can't remove a habit from phone
  • HabitGoalLinks unlink × → can't unlink a goal-habit pair from phone
  • ProjectInlineEditors description pencil → can't see edit affordance from phone

The codebase already has the right SSOT for this (ui-hover-reveal in
globals.css = `sm:opacity-0 sm:group-hover:opacity-100`), so mobile always
shows the icon and desktop keeps the hover-reveal polish. Swap each broken
spot to either the SSOT class or the sm: prefix where named groups (group/desc)
preclude the class.

Caught by `grep -rn "opacity-0 group-hover" src/components/` — now returns
zero hits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:35:43 +02:00
g-butandClaude Opus 4.7 4f13245d62 fix(today): Recent Agent Work clusters adjacent same-project runs
Live mobile audit (the same one that found the weather bug) surfaced
"Cockpit · 5h ago" rendering five times in a row, then "6h ago", then
"10h ago" — back-to-back orchestration_runs entries on the same project
flooding the card with near-duplicates.

Cluster pass after the query: walk the already finishedAt-desc list,
each run either extends the previous cluster (same projectKey + within
60 min of the latest run's finishedAt) or starts a new one. Render one
row per cluster with a "↻ ×N" badge when N > 1.

Cluster window matches the rough duration of a back-to-back session
burst; anything longer feels like distinct work and deserves its own
row. Latest run's done/next/health drive the visible summary so the
freshest signal stays prominent.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:15:08 +02:00
g-butandClaude Opus 4.7 947fc557f7 fix(weather): WeatherCard shows real weather on Vercel via open-meteo HTTP
Caught during a live audit at mobile viewport on cockpitapp.vercel.app:
WeatherCard rendered "Unavailable" indefinitely. Root cause: /api/weather's
GET handler bails to {weather: null} when isRuntimeAvailable() is false
(serverless can't shell out to scripts/weather.sh).

But the upstream weather.sh actually calls is open-meteo — a free public
HTTP API. We can hit it directly from Vercel via fetch. Add a
fetchOpenMeteoWeather() path used only when isRuntimeAvailable is false;
local keeps the richer shell path.

Implementation:
  - WMO_DESCRIPTION map: weather codes 0-99 → human strings matching
    weather.sh's vocabulary so WeatherCard's parseWeather +
    WeatherIcon-by-keyword detection still light up the right icon
    (cloud / rain / snow / fog) regardless of source.
  - Output line format matches weather.sh exactly:
      "Now: <desc>, <temp>°C, wind <w> km/h, humidity <h>%"
      "<date>: <lo>-<hi>°C, <desc>"
  - AbortSignal.timeout(7000) so a stalled upstream doesn't pin the route.
  - 503 with explicit error reason when geocoding fails or open-meteo is
    unreachable, so FetchErrorState shows the actual cause rather than a
    silent "Unavailable" wall.

This finally works on the deployed site for the first time. The user has
been seeing "Weather: Unavailable" on their Today page on every mobile
visit; from this deploy onward they'll see real temperature + condition +
tomorrow's forecast.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:01:53 +02:00
g-butandClaude Opus 4.7 9054ce9822 refactor(system): SystemStats useFetch uses REFRESH_CADENCE.system
Single cadence story for the /system surface: the server-card AutoRefresh
and the client-side SystemStats useFetch poll now share REFRESH_CADENCE.system.
One edit retunes both.

Other polling useFetch callers (Calendar 5min, Weather 10min, GitHub 2min)
intentionally stay un-unified — those intervals track the backing API's
data-change rate, not the surface's freshness need. Pulling them into
REFRESH_CADENCE would conflate "page cadence" with "endpoint cadence" —
two different concerns that just happen to be numbers in the same range.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:48:32 +02:00
g-butandClaude Opus 4.7 ab4a79479b refactor(refresh): REFRESH_CADENCE SSOT for AutoRefresh intervals
Four pages hardcoded their own intervalMs after bd8e4fa + cb86bca. Past
the rule-of-three threshold (we have 4 instances) so extract:

  src/config/refresh.ts
    REFRESH_CADENCE = {
      system:   30_000,  // operational signals — fresh failures visible fast
      today:    60_000,  // user-driven; data shifts slowly
      memory:   60_000,
      projects: 60_000,
    }

Every page imports the key for its surface. One edit to retune the whole
app instead of four.

Skipping env-var override: YAGNI. Comment in the file documents how to
convert these to `Number(process.env.REFRESH_CADENCE_X ?? "30000")` if a
deployment ever hits a bandwidth ceiling — but we don't write the env
plumbing speculatively.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:37:33 +02:00
g-butandClaude Opus 4.7 cb86bcaeb6 feat(refresh): AutoRefresh on /today, /memory, /projects (60s)
Mount the existing <AutoRefresh /> on the three other server-rendered
status surfaces. 60s cadence — longer than /system's 30s because these
pages' data changes more slowly (commitments, projects, memory entities)
and an extra Neon round-trip per minute is cheap.

Deviation from the session next: deliberately SKIPPED /control. Its body
is the ControlPanel client component, which already manages its own
polling via useControlData + cockpit:refresh listener — router.refresh()
would only re-render the static PageLayout wrapper, providing no visible
benefit while paying a Neon round-trip. First principles trump the "mount
on every status surface" pattern: AutoRefresh helps server components,
not client-state owners.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:23:03 +02:00
g-butandClaude Opus 4.7 bd8e4fa40d feat(system): 30s AutoRefresh keeps telemetry card live
RecentFailuresCard (510bfc0) only re-renders on PullToRefresh / focus-return
gestures. A failure that lands NOW is invisible to a user staring at /system
without doing one of those.

Tiny client component: <AutoRefresh intervalMs={30_000} /> mounts a
visibility-gated setInterval that fires router.refresh() — re-fetches all
server cards on the page in one call, no per-card plumbing. Visibility
check skips polling on a backgrounded tab so we're not chewing Neon
queries for nobody.

Composable with the existing PullToRefresh + RefreshOnFocus — router.refresh
is idempotent enough that two near-simultaneous triggers batch into one
React work pass. No coordination logic needed.

Mounted on /system right after RecentFailuresCard.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:11:21 +02:00
g-butandClaude Opus 4.7 510bfc052a feat(system): Recent telemetry card surfaces debug_logs on /system
I've been writing every failure/heartbeat into debug_logs across five
sources (api/inject, api/orchestration/run, api/control/dispatch,
api/crons/prune-debug-logs, auth) but the user had no UI to see any of
it — would have to SQL the table by hand.

Mount a Suspense-wrapped server-component card at the bottom of /system:
  - Last 10 rows via getRecentDebugLogs
  - Per-row: relative time · source · level icon · truncated message
  - Header right-side counter: "N errors" in red OR "all clear" in muted
  - EmptyState when no telemetry yet
  - LEVEL_TONE map for icon + color (error red, warn amber, info muted)
  - title attribute on message for hover-to-see-full-text on desktop

No client poll — the card re-renders on PullToRefresh / RefreshOnFocus
gestures which we already wired earlier. Pivoted away from the previous
session next: (Edge-middleware → Node forwarder for cookie-401 telemetry)
because the forensics value is marginal — the user-facing failure is
already visible via 9c2525c — and the forwarder adds a real DoS-amplification
surface (bots probing /api/* would spam debug_logs through it). Better
spend: make the telemetry I already have visible.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:00:12 +02:00
g-butandClaude Opus 4.7 c80c6cf7b3 feat(telemetry): logDebug on /api/inject route-level 401
Captures the route-level unauthenticated branch (line 28) — fires when a
caller passes middleware (Bearer ck_* token) but fails getSessionUserId
(token revoked, mis-configured, expired session that NextAuth couldn't
parse but the middleware let through). Meta includes UA + referer so a
mobile vs desktop attempt is distinguishable.

Scope honest disclosure: this does NOT catch the most-common 401 case —
the cookie-only "session JWT expired" mobile path. Edge-runtime middleware
in src/auth.config.ts intercepts those at line 54-58 before any route
handler runs, and the Edge runtime can't use postgres-js (Node-only).
Capturing that class server-side requires either:
  - moving telemetry to a Node-runtime catch-all route the middleware
    forwards to before returning 401, or
  - using a Vercel-supported Edge telemetry sink (Log Drains / Analytics).

Verified locally: curl with an invalid `Bearer ck_…` token now lands a
row in debug_logs (source=api/inject, level=warn, message="Unauthenticated
inject attempt — likely session expiry"). Cookie-only probes still get a
401 from middleware and bypass this code, by design.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 02:44:51 +02:00
g-butandClaude Opus 4.7 c5a9faa3a7 fix(control): never-lose-a-prompt now covers all four dispatch paths
9c2525c protected sendCustom + sendText (custom-input path). Three other
paths in useProjectCardActions had the same swallow-the-error pattern,
and one of them was destructive:

  handleSendFromQueue: removed the queue item BEFORE the await. A failed
  onInject (network drop / 401 / 5xx) silently destroyed the queue item.
  Same lost-prompt class as the original incident, just on the per-project
  prompt queue instead of the custom input. Swap to remove-on-success:
  await first, then removeFromQueue(index); on throw the item stays in
  the queue and the inline error banner surfaces.

  sendIntent: two await sites (queued-next-best inject + onRunWithBrain)
  with no catch — failures became unhandled promise rejections logged to
  console while the user saw nothing. Wrap each with try/catch → sendError.

  send: same shape, three await sites. Same wrap.

All four now follow the established pattern: clear sendError on entry,
attempt the dispatch, on catch set sendError so the PromptInput red
banner shows. The four error catches are identical because they share
the same fail mode — keep them inline rather than extract a wrapper
since each path has unique state setup before the await.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 02:26:10 +02:00
g-butandClaude Opus 4.7 712aa5f285 refactor(cron): extract requireCronAuth helper as SSOT
Vercel build of 02c3c0d failed because the CRON_SECRET I set via
`echo $value | vercel env add` carried a trailing newline that HTTP
header validation rejects. Fixed env-side via `printf %s` (re-added the
secret with no whitespace).

Code-side: extract the gate into src/lib/cron-auth.ts so the next janitor
doesn't have to re-implement the same auth pattern (and so the "use
printf not echo" warning lives next to the code that depends on it).
requireCronAuth(req) returns NextResponse on failure (caller `return`s
it) or null on success — same three-branch behavior:

  - VERCEL=1 + no CRON_SECRET → 503 fail-closed
  - CRON_SECRET set → require matching Bearer, else 401
  - VERCEL unset + no CRON_SECRET → allow (local dev curl path)

Refactor /api/crons/prune-debug-logs to use it. Two LOC replace nine
lines of inline auth.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 01:47:59 +02:00