mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-02 13:39:41 +02:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8f3981b0c | ||
|
|
1c94995290 | ||
|
|
f485085174 | ||
|
|
98fa8c00d1 |
@@ -208,7 +208,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Unified session list**: `GET /api/sessions/unified` merges live sessions, persisted state, lifecycle-log history, and Claude transcript files into one deduped list (pure core in `src/services/unified-session-service.ts`). Transcript rows fold into their owning session via a `claudeSessionId → Codeman id` alias map, so resumed and `/clear`-respawned sessions do not appear twice. No terminal buffers in the response, unlike `/api/sessions`. Backs the Cmd+K Session Manager, plus pinning and cross-device tab order (`PUT /api/session-order`; pure merge helpers in `src/session-order.ts`, pushing device wins and server-only ids are never dropped). → [architecture-invariants#unified-session-list-and-session-manager](docs/architecture-invariants.md#unified-session-list-and-session-manager)
|
||||
|
||||
**Hook events**: Claude Code hooks trigger via `/api/hook-event`. Key events: `permission_prompt`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `idle_prompt`, `stop`, `teammate_idle`, `task_completed`. See `src/hooks-config.ts`; upstream hook semantics mirrored in `docs/claude-code-hooks-reference.md`.
|
||||
**Hook events**: Claude Code hooks trigger via `/api/hook-event`. Key events: `permission_prompt`, `elicitation_dialog`, `elicitation_complete`, `elicitation_response`, `idle_prompt`, `stop`, `teammate_idle`, `task_completed`. See `src/hooks-config.ts`; upstream hook semantics mirrored in `docs/claude-code-hooks-reference.md`. ⚠️ **Every claude session INSTALLS the hooks block into its workspace** (`applyWorkspaceHooks` in session-routes.ts → `ensureCodemanHooks`, an add-only merge that keeps a user's own handlers), from both create paths and from `restoreMuxSessions()` for sessions recovered on server start. Before 2026-08-15 hooks were written ONLY when Codeman created the case DIRECTORY, so a linked case / cloned repo — where most sessions actually run — had no hooks at all and every hook-driven surface was silently dead there: an AskUserQuestion dialog blocked the pane while the tab and the phone overview both read a calm `idle`, with no Approvals Inbox item, no push, no definitive `stop`/`idle_prompt` for respawn and no `stop`/`blocked` for the wait endpoints. The escape hatch is the synced `workspaceHooksEnabled` setting (App Settings → Agents & CLIs → Claude, **default ON**); OFF restores the old behavior, where a Codeman block that is already there is still refreshed when stale (COD-91) but one is never added. ⚠️ Route the decision through `applyWorkspaceHooks` rather than calling `ensureCodemanHooks` at a new site, or the setting silently stops applying to that path. ⚠️ Claude Code RE-READS `settings.local.json`, so an already-running session starts firing hooks without a restart (measured 2026-08-15) — and the notification for a blocking dialog is delayed by Claude Code (~30s), so the alert trails the dialog. ⚠️ An AskUserQuestion / plan-selection dialog arrives as **`permission_prompt`**, not `elicitation_dialog` (that one is MCP elicitation), so it renders as the RED "needs you" alert, not the yellow idle one.
|
||||
|
||||
**Approvals Inbox** (cross-session queue of prompts waiting on a human; `approvalsInboxEnabled`, SYNCED, default OFF: every surface is opt-in; only the store and answer endpoints run regardless, so flipping it ON shows anything already pending): `web/approval-inbox.ts` is a `sessionWaits`-style singleton fed by `/api/hook-event`, holding at most ONE item per session (a new prompt supersedes), claude-mode only, in-memory. Cards are answered via `POST /api/approvals/:id/answer`, which sends a digit / Esc / idle-prompt text through `writeViaMux` (menu answers never carry `\r`). ⚠️ `option` digits are accepted ONLY when they match options parsed from the captured pane frame, and the answer path RE-CAPTURES the pane first (a dialog that no longer parses on screen means the keystroke would land in the composer, so refuse with 409). ⚠️ Resolution on the heuristic `working` signal is restricted to `idle` items; permission/question items clear only on definitive signals (`stop`, `elicitation_complete`/`elicitation_response`, exit/delete, answer, supersede, 12h TTL). The frontend seeds from `GET /api/approvals` in `handleInit` **regardless of the setting**: the seed re-arms the tab-alert state machine (`setPendingHook`) unconditionally, and only populating `this.approvals` (the inbox surfaces) is gated — seeding used to be gated wholesale, which left a reloaded page with NO red tab while a permission dialog sat blocking a session (2026-08-15); `_onApprovalResolved` clears the pending-hook alert unconditionally for the same reason. ⚠️ The red/yellow tab alert itself is a STEADY border/background/dot with a pulse on top: the original keyframes swung to transparent at 0%/100%, so half of every cycle looked like a normal tab. Push Approve/Deny buttons stay gated on the setting (`sendPushNotifications` strips `actions`/`approvalId` when OFF) and are answered from `sw.js` directly so they work with no tab open. Surfaces (all gated on the setting): header bell (marker-hidden until count > 0, phones never show it) + drawer (`approvals-ui.js`), phone overview NEEDS YOU answer strips (`mobile-overview.js`). Design: `docs/approvals-inbox-plan.md`.
|
||||
|
||||
@@ -262,9 +262,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Phone overview home screen** (`mobile-overview.js`, phones only, per-device `mobileOverviewEnabled`, default ON): under 430px the "C" logo shows a session overview (NEEDS YOU / CURRENT SESSIONS / PAST SESSIONS) instead of the welcome overlay; tablet and desktop are unchanged. The branch lives in `showWelcome()`/`hideWelcome()` (terminal-ui.js) behind `shouldUseMobileOverview()`, which is **width-driven** (`getDeviceType() === 'mobile'`) because this is a layout decision, unlike the settings namespace which stays handheld-based. ⚠️ The container ships with the `hidden` attribute and only this module removes it: never give `.mobile-overview` a bare `display` rule, since desktop does not load `mobile.css` (`media="(max-width: 1023px)"`) and would then render it unstyled. Live re-renders ride on the tail of `_renderSessionTabsImmediate()` (every state change it needs already funnels there); PAST rows come from one `_fetchUnifiedSessions(60)` per home-screen visit and resume through the shared `resumeHistorySession()`, so they behave exactly like the welcome screen's Resume list. ⚠️ Two things must stay in lockstep with surfaces outside this module, because divergence reads as a bug rather than a style: the split Run button carries the **toolbar's own classes** (`btn-toolbar btn-run mode-<backend>` / `btn-run-gear`) so the per-backend gradient and the light-skin overrides apply unchanged (mobile.css must therefore set no `background`/`color` on it), and row status uses the **session-tab language** (green dot when fine, `pulse` while working, yellow blinking row when waiting for input, red blinking row when a question is pending, mirroring `tab-alert-idle`/`tab-alert-action`). The picker mirrors the toolbar run-mode menu (`setRunMode()` + `run()`, `openWebviewFromMenu()` for saved dashboards) and deliberately omits its Recent-Sessions block, since PAST SESSIONS is that. Status pills carry `data-i18n-skip` (generic words like "idle" collide with state strings elsewhere).
|
||||
|
||||
**Desktop home tab rail** (`home-sessions.js`, desktop only): the welcome overlay centers ~560px of content in a ~1400px window, so its left gutter is dead space; it carries the open tabs as a rail **docked flush to the left edge, full height** (a vertically centered card floating mid-gutter read as debris). Rows are in **overview order** (see below), and each carries a **created** stamp plus the **state duration** the order is computed from (`created 3d ago · working 12m`, word and anchor from `_mobileOverviewSince()` so both home screens say the same thing). A rail sorted by a number it does not show reads as arbitrarily shuffled, and a working row's plain last-active stamp always says "just now". ⚠️ The number badge is the **Alt+1..9 index**, i.e. the position in the TAB STRIP, so on a sorted rail it deliberately does NOT run 1,2,3 downward: it names a shortcut, not a row position, and renumbering it to look tidy would make every badge lie. State classification is REUSED from mobile-overview.js (`_mobileOverviewState`/`_mobileOverviewCaseFor`), which is why the module loads after it. ⚠️ The rail is `position: absolute` so the centered content never moves, which is exactly why it needs a **width gate in two places** — `HOME_SESSIONS_MIN_WIDTH` (1180) in the JS plus a `max-width: 1179px` media query as the backstop for a resize that outruns the matchMedia listener; drift between them means a rail overlapping the search panel, and `test/home-sessions.test.ts` pins them equal. ⚠️ `.home-sessions` is `display: flex`, so `[hidden]` must be re-asserted as `display: none` or the module's only visibility lever does nothing. ⚠️ Size scales with the viewport off **one knob**: `width: clamp(250px, 19vw, 430px)` plus a fluid `font-size` on `.home-sessions`, with every child sized in `em` — reintroducing `rem`/px type inside the block silently breaks the scaling, and widening the clamp past the gutter reintroduces the overlap the gate exists to prevent. The age stamps are refreshed **in place** by a 20s clock (`_tickHomeSessionsTimes()`, disarmed in `hideHomeSessions()`), never by re-rendering, which would restart every row's blink and working ring. Working state is deliberately byte-identical to the phone's: pulsing green dot + the `tab-load-spin` ring reused from the tab strip + the same green halo (added to `.mobile-overview-dot--working` at the same time), so "working" reads the same on every surface; **idle** is deliberately NOT that green — dot and pill mix toward `--text-muted` so a glance separates running from sitting. Live re-renders ride the tail of `_renderSessionTabsImmediate()` alongside the phone overview.
|
||||
|
||||
**Home-screen session order** (`CodemanSessionOrder` in constants.js, pure + unit-tested in `test/session-overview-order.test.ts`): BOTH home screens (phone overview and desktop rail) order rows through this ONE comparator, because they list the same sessions and must answer "which of these wants me next?" the same way. Rank is `needs` → `error` → `waiting` → `working` → `idle` → `done`, and ⚠️ **the tiebreak flips direction halfway down**: states a session is still IN sort **oldest-first** (blocked longest / running longest = most urgent), states it has STOPPED in sort **newest-first** (the session that just went quiet is the one you came back for). ⚠️ The running group keys off **`lastSubmitAt`** (the pane's last Enter), never `lastActivityAt`: a working Claude pane repaints about once a second, so its last-activity stamp is always "now" and would rank every running turn as freshly started. A working pane with no submit stamp falls back to last activity, which lands it at the SHORT end of the group rather than falsely leading it. ⚠️ A **0 stamp means "unknown", not "the epoch"**, and it sorts last within its state either way, or a brand-new session would head every oldest-first group. Final tiebreak is the user's tab order (`orderIndex`), so the list is deterministic and cannot shuffle between renders. The tab strip itself is NOT sorted by this; it stays user-ordered and drag-reorderable.
|
||||
**Desktop home tab rail** (`home-sessions.js`, desktop only): the welcome overlay centers ~560px of content in a ~1400px window, so its left gutter is dead space; it carries the open tabs as a rail **docked flush to the left edge, full height** (a vertically centered card floating mid-gutter read as debris). Rows are in **tab order**, not sorted by urgency like the phone overview, because the row badges are the Alt+1..9 indices, and each carries **created / last-active** stamps. State classification is REUSED from mobile-overview.js (`_mobileOverviewState`/`_mobileOverviewCaseFor`), which is why the module loads after it. ⚠️ The rail is `position: absolute` so the centered content never moves, which is exactly why it needs a **width gate in two places** — `HOME_SESSIONS_MIN_WIDTH` (1180) in the JS plus a `max-width: 1179px` media query as the backstop for a resize that outruns the matchMedia listener; drift between them means a rail overlapping the search panel, and `test/home-sessions.test.ts` pins them equal. ⚠️ `.home-sessions` is `display: flex`, so `[hidden]` must be re-asserted as `display: none` or the module's only visibility lever does nothing. ⚠️ Size scales with the viewport off **one knob**: `width: clamp(250px, 19vw, 430px)` plus a fluid `font-size` on `.home-sessions`, with every child sized in `em` — reintroducing `rem`/px type inside the block silently breaks the scaling, and widening the clamp past the gutter reintroduces the overlap the gate exists to prevent. The age stamps are refreshed **in place** by a 20s clock (`_tickHomeSessionsTimes()`, disarmed in `hideHomeSessions()`), never by re-rendering, which would restart every row's blink and working ring. Working state is deliberately byte-identical to the phone's: pulsing green dot + the `tab-load-spin` ring reused from the tab strip + the same green halo (added to `.mobile-overview-dot--working` at the same time), so "working" reads the same on every surface; **idle** is deliberately NOT that green — dot and pill mix toward `--text-muted` so a glance separates running from sitting. Live re-renders ride the tail of `_renderSessionTabsImmediate()` alongside the phone overview.
|
||||
|
||||
**Welcome "Resume Conversation" list** (terminal-ui.js): `loadHistorySessions()` fetches once and caches the corpus on `_historyAll`/`_historyCases`; every subsequent view (filter box, sort select, expand, the periodic refresh in panels-ui.js) goes through `_renderHistoryList()`, so never append rows to `#historyList` directly or re-fetch to re-sort. ⚠️ The box height is **class-driven**: expanding the list without `.history-list.expanded` leaves the collapsed `max-height` in place and just deepens a scroll well, which is the bug #260 reported (35 sessions in a ~4-row box). ⚠️ The A–Z sort keys off `_historyRowLabel()`, the SAME string the row renders (`name || firstPrompt || path`), most rows are transcript-backed and have no session name, so sorting on `name` alone silently does nothing. ⚠️ A filter implies expansion, and `_renderSearch()` hides `#historyHeader` (title + controls) as one unit while a search is active. Tests: `test/history-list-controls.test.ts`.
|
||||
|
||||
|
||||
+16
-15
@@ -47,7 +47,7 @@ later call opens with, and your first REAL call performs them anyway:
|
||||
|
||||
```bash
|
||||
. "${XDG_CACHE_HOME:-$HOME/.cache}/codeman-agent-$CODEMAN_SESSION_ID.sh" 2>/dev/null
|
||||
[ "${CODEMAN_PREAMBLE:-}" = 1.18.3 ] || { echo "preamble missing or stale; run the full §0 block"; exit 1; }
|
||||
[ "${CODEMAN_PREAMBLE:-}" = 1.19.0 ] || { echo "preamble missing or stale; run the full §0 block"; exit 1; }
|
||||
```
|
||||
|
||||
⚠️ **Never spend a Bash call on this check alone.** §1's block opens with this same
|
||||
@@ -75,8 +75,8 @@ PRE="${XDG_CACHE_HOME:-$HOME/.cache}/codeman-agent-$CODEMAN_SESSION_ID.sh"
|
||||
mkdir -p "$(dirname "$PRE")"
|
||||
# Rewrite unless the file already ends with THIS version's stamp, so a stale or a
|
||||
# half-written file self-heals here instead of costing you a round trip to rm it.
|
||||
grep -qs '^CODEMAN_PREAMBLE=1.18.3$' "$PRE" || (umask 077; cat > "$PRE" <<'PREAMBLE'
|
||||
# ---- Codeman agent preamble 1.18.3 (seeded by Codeman at session spawn; the SKILL.md §0 bootstrap rewrites it when missing or stale) ----
|
||||
grep -qs '^CODEMAN_PREAMBLE=1.19.0$' "$PRE" || (umask 077; cat > "$PRE" <<'PREAMBLE'
|
||||
# ---- Codeman agent preamble 1.19.0 (seeded by Codeman at session spawn; the SKILL.md §0 bootstrap rewrites it when missing or stale) ----
|
||||
API="${CODEMAN_API_URL:?CODEMAN_API_URL not set; refusing to guess}"
|
||||
SELF="${CODEMAN_SESSION_ID:?CODEMAN_SESSION_ID not set}"
|
||||
# Credentials, cheapest first. Your session has usually INHERITED the server's
|
||||
@@ -138,14 +138,14 @@ spawn_worker() {
|
||||
# NOT retryable in a loop: every quick-start failure code is terminal (§5.1).
|
||||
[ -n "$sid" ] || { jq -c '{error,errorCode}' <<<"$q" >&2; return 1; }
|
||||
[ "$mode" = claude ] || { printf '%s\n' "$sid"; return 0; } # only claude draws a composer
|
||||
# quick-start RESOLVES the name before creating: a linked case or an existing dir
|
||||
# wins over a fresh scratch case, so "created => hooks" is only true after this one
|
||||
# local grep (the same marker the server itself checks for). No marker means sendwait
|
||||
# would false-resolve on flapping idle, possibly inside the user's REAL repo: refuse
|
||||
# rather than run the job there.
|
||||
# The server installs hooks into every claude workspace now, so this grep normally
|
||||
# passes; it stays because the install is gated on a setting the operator can turn
|
||||
# off, remote sessions never get hooks, and a session created by an older server
|
||||
# still has none. No marker means sendwait would false-resolve on flapping idle,
|
||||
# possibly inside the user's REAL repo: refuse rather than run the job there.
|
||||
cp=$(jq -r '.data.casePath // empty' <<<"$q")
|
||||
grep -qs '/api/hook-event' "$cp/.claude/settings.local.json" || {
|
||||
echo "case '$name' resolved to '$cp', which has no Codeman hooks (linked or pre-existing?): pick an unused name, or work §5.1+§5.5 by hand" >&2
|
||||
echo "case '$name' resolved to '$cp', which has no Codeman hooks (workspaceHooksEnabled off, remote, or an older server?): turn the setting on, or work §5.1+§5.5 by hand with markers" >&2
|
||||
delete_session "$sid" >/dev/null; return 1; }
|
||||
# Short composer wait FIRST, then the trust-dialog probe: a case still showing the
|
||||
# dialog can never pass the composer wait, so probing early keeps a cold case from
|
||||
@@ -233,10 +233,10 @@ last_text() {
|
||||
# The stamp is the LAST line on purpose (a truncated write leaves it unset) and is kept
|
||||
# bare on purpose: the write condition above anchors on it with $, so an inline comment
|
||||
# here would fail that match and rewrite this file on every single bootstrap.
|
||||
CODEMAN_PREAMBLE=1.18.3
|
||||
CODEMAN_PREAMBLE=1.19.0
|
||||
PREAMBLE
|
||||
)
|
||||
. "$PRE"; [ "${CODEMAN_PREAMBLE:-}" = 1.18.3 ] || { echo "preamble at $PRE is stale or truncated: rm it and re-run this block"; exit 1; }
|
||||
. "$PRE"; [ "${CODEMAN_PREAMBLE:-}" = 1.19.0 ] || { echo "preamble at $PRE is stale or truncated: rm it and re-run this block"; exit 1; }
|
||||
```
|
||||
|
||||
Every later Bash call that touches the API starts with the same two loader lines from
|
||||
@@ -287,7 +287,7 @@ and no per-call body to hand-build.
|
||||
|
||||
```bash
|
||||
. "${XDG_CACHE_HOME:-$HOME/.cache}/codeman-agent-$CODEMAN_SESSION_ID.sh" 2>/dev/null # §0 loader
|
||||
[ "${CODEMAN_PREAMBLE:-}" = 1.18.3 ] || { echo "preamble missing or stale; run the full §0 block"; exit 1; }
|
||||
[ "${CODEMAN_PREAMBLE:-}" = 1.19.0 ] || { echo "preamble missing or stale; run the full §0 block"; exit 1; }
|
||||
N=(alpha beta) # INVENT one fresh case name per worker; never list cases first
|
||||
T=('reply with one line: the absolute path of your working directory'
|
||||
'reply with one line: your model name') # tasks, same order as N
|
||||
@@ -343,7 +343,8 @@ Four things this block leans on, each one link away, no detour needed to run it:
|
||||
`~/codeman-cases/<name>`, not your repo. A name that already means something (a
|
||||
linked case, a pre-existing directory) is refused by `spawn_worker` rather than
|
||||
silently reused. Spawning where the work actually is (a linked case, a git worktree)
|
||||
is a different call with **no hooks**, and the costliest mistake in this skill: §5.1.
|
||||
is a different call, and picking the wrong one is the costliest mistake in this
|
||||
skill: §5.1. Those workspaces do get hooks now, unless the operator disabled it.
|
||||
- `sendwait` supplies the `\r`, picks a fresh `seq`, and self-heals a stranded Enter.
|
||||
A prompt without the `\r` is never submitted (§3), a reused `seq` is silently
|
||||
swallowed as an already-applied duplicate, and an Enter eaten by an Ink repaint
|
||||
@@ -358,9 +359,9 @@ One row per job. Acting on this table alone is correct; the §5 links are the de
|
||||
|
||||
| I want to | Call | Detail |
|
||||
|-----------|------|--------|
|
||||
| start a worker **where the work is** | `POST /api/v1/quick-start {"caseName":…}`, which **creates** `~/codeman-cases/<name>` unless the name is already a case: full signals there. Any other path (a git worktree): `POST /api/v1/sessions {"workingDir":…}` then `POST /api/v1/sessions/:id/interactive`, and expect **no hooks**. N workers means N worktrees | [§5.1](reference/verbs.md#51-where-to-spawn) |
|
||||
| start a worker **where the work is** | `POST /api/v1/quick-start {"caseName":…}`, which **creates** `~/codeman-cases/<name>` unless the name is already a case. Any other path (a git worktree): `POST /api/v1/sessions {"workingDir":…}` then `POST /api/v1/sessions/:id/interactive`. Both install hooks by default, so expect full signals in either, and **verify** rather than assume. N workers means N worktrees | [§5.1](reference/verbs.md#51-where-to-spawn) |
|
||||
| know a new worker can accept a prompt | `GET .../wait-output?match=shift+tab&from=buffer` (urlencode the `+`) | [§5.2](reference/verbs.md#52-readiness) |
|
||||
| deliver a task **and** know when it finished | `POST .../input` with `"input":"…\r"`, `clientId`, `seq`, `"wait":true`. Resolves on `stop`, so it is only trustworthy in a **case Codeman created** (claude mode + hooks present). Costs the worker one billed turn | [§5.3](reference/verbs.md#53-send-a-task-and-wait) |
|
||||
| deliver a task **and** know when it finished | `POST .../input` with `"input":"…\r"`, `clientId`, `seq`, `"wait":true`. Resolves on `stop`, so it is trustworthy only where the workspace **has hooks** (claude mode; installed by default, but the operator can disable it and remote sessions never get them). Costs the worker one billed turn | [§5.3](reference/verbs.md#53-send-a-task-and-wait) |
|
||||
| know a hook-less worker finished | it has no `stop`, and `wait:true` there resolves on flapping `idle` **without erroring**: make it print a split, unique marker and `wait-output` on that instead | [§5.5](reference/verbs.md#55-markers-for-hook-less-workers) |
|
||||
| read the answer | `GET .../last-response`, **polled** (claude/codex only; empty for the other modes) | [§5.4](reference/verbs.md#54-read-the-answer) |
|
||||
| know if it is alive | `GET .../wait?until=exit&timeout=1000`: an immediate `signal:"exit"` means dead. `status` and `pid` both lie | [§5.6](reference/verbs.md#56-alive-and-stuck) |
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# ---- Codeman agent preamble 1.18.3 (seeded by Codeman at session spawn; the SKILL.md §0 bootstrap rewrites it when missing or stale) ----
|
||||
# ---- Codeman agent preamble 1.19.0 (seeded by Codeman at session spawn; the SKILL.md §0 bootstrap rewrites it when missing or stale) ----
|
||||
API="${CODEMAN_API_URL:?CODEMAN_API_URL not set; refusing to guess}"
|
||||
SELF="${CODEMAN_SESSION_ID:?CODEMAN_SESSION_ID not set}"
|
||||
# Credentials, cheapest first. Your session has usually INHERITED the server's
|
||||
@@ -60,14 +60,14 @@ spawn_worker() {
|
||||
# NOT retryable in a loop: every quick-start failure code is terminal (§5.1).
|
||||
[ -n "$sid" ] || { jq -c '{error,errorCode}' <<<"$q" >&2; return 1; }
|
||||
[ "$mode" = claude ] || { printf '%s\n' "$sid"; return 0; } # only claude draws a composer
|
||||
# quick-start RESOLVES the name before creating: a linked case or an existing dir
|
||||
# wins over a fresh scratch case, so "created => hooks" is only true after this one
|
||||
# local grep (the same marker the server itself checks for). No marker means sendwait
|
||||
# would false-resolve on flapping idle, possibly inside the user's REAL repo: refuse
|
||||
# rather than run the job there.
|
||||
# The server installs hooks into every claude workspace now, so this grep normally
|
||||
# passes; it stays because the install is gated on a setting the operator can turn
|
||||
# off, remote sessions never get hooks, and a session created by an older server
|
||||
# still has none. No marker means sendwait would false-resolve on flapping idle,
|
||||
# possibly inside the user's REAL repo: refuse rather than run the job there.
|
||||
cp=$(jq -r '.data.casePath // empty' <<<"$q")
|
||||
grep -qs '/api/hook-event' "$cp/.claude/settings.local.json" || {
|
||||
echo "case '$name' resolved to '$cp', which has no Codeman hooks (linked or pre-existing?): pick an unused name, or work §5.1+§5.5 by hand" >&2
|
||||
echo "case '$name' resolved to '$cp', which has no Codeman hooks (workspaceHooksEnabled off, remote, or an older server?): turn the setting on, or work §5.1+§5.5 by hand with markers" >&2
|
||||
delete_session "$sid" >/dev/null; return 1; }
|
||||
# Short composer wait FIRST, then the trust-dialog probe: a case still showing the
|
||||
# dialog can never pass the composer wait, so probing early keeps a cold case from
|
||||
@@ -155,4 +155,4 @@ last_text() {
|
||||
# The stamp is the LAST line on purpose (a truncated write leaves it unset) and is kept
|
||||
# bare on purpose: the write condition above anchors on it with $, so an inline comment
|
||||
# here would fail that match and rewrite this file on every single bootstrap.
|
||||
CODEMAN_PREAMBLE=1.18.3
|
||||
CODEMAN_PREAMBLE=1.19.0
|
||||
|
||||
@@ -251,10 +251,12 @@ that is expected, not a failure: read `terminal?tail=` and strip ANSI instead.
|
||||
**It means** that session has no Codeman hooks, so `stop` can never fire and the wait
|
||||
silently degraded to `idle`, which flaps mid-turn. Nothing rejected your request:
|
||||
`wait:true` (and even an explicit `until=stop`) is accepted because the 400 is about
|
||||
session **mode**, and the mode really is `claude`. Hooks are written only when Codeman
|
||||
**creates** the directory; a linked case or a raw `workingDir` gets none (an existing
|
||||
case that Codeman created earlier keeps the block it was given), see the table under
|
||||
[Signals by mode](#signals-by-mode). Measured: on a
|
||||
session **mode**, and the mode really is `claude`. Hooks are installed into every
|
||||
claude workspace at session create (synced `workspaceHooksEnabled`, default ON) and
|
||||
swept across recovered sessions at boot, so a linked case or a raw `workingDir` gets
|
||||
them too; with the setting off, on a remote session, or on a session from an older
|
||||
server, they are absent, see the table under
|
||||
[Signals by mode](#signals-by-mode). Measured before that changed: on a
|
||||
linked case whose `.claude/settings.local.json` carries env/model/permissions/statusLine
|
||||
and no `hooks` block, a `wait?until=stop,exit` parked for twelve consecutive 60 s rounds
|
||||
never resolved although the worker finished its turn.
|
||||
@@ -360,10 +362,10 @@ loop.
|
||||
⚠️ `caseName` resolves through the linked-cases registry first, so a name that happens
|
||||
to match a case the user linked in lands in that **real repo**, not a fresh scratch
|
||||
directory. Pick distinctive scratch names, and use a linked name deliberately when you
|
||||
do want a worker in an existing checkout. ⚠️ It also decides whether you get hooks:
|
||||
Codeman writes them only when it **creates** the directory, so a linked case or a raw
|
||||
path gives you a worker with no `stop` signal, while a scratch case Codeman created
|
||||
earlier keeps working signals ([Signals by mode](#signals-by-mode)).
|
||||
do want a worker in an existing checkout. It no longer decides whether you get hooks:
|
||||
every claude create path installs them, so a linked case and a raw path both get a
|
||||
`stop` signal unless the operator turned `workspaceHooksEnabled` off
|
||||
([Signals by mode](#signals-by-mode)).
|
||||
|
||||
**The two-step alternative, `POST /api/v1/sessions`.** Use it when you need a session in
|
||||
a directory that is not a case (body takes `workingDir`, `mode`, `name`, `effort`,
|
||||
@@ -614,35 +616,27 @@ Three bounded long-polls. Shared semantics:
|
||||
| `exit` | PTY exited or session deleted | every mode |
|
||||
|
||||
⚠️ **`claude` mode is necessary for `stop`/`blocked`, not sufficient. The real
|
||||
precondition is that the session's working directory has a Codeman hooks block**, and
|
||||
whether it does depends on who created the directory:
|
||||
precondition is that the session's working directory has a Codeman hooks block**, which
|
||||
is now installed by default rather than depending on who created the directory:
|
||||
|
||||
| The worker's directory | Hooks | `stop` / `blocked` | Synchronize with |
|
||||
|------------------------|-------|--------------------|------------------|
|
||||
| Codeman created it (`quick-start` with a NEW `caseName`, `POST /api/cases`, clone, docker quickcreate) | written at create | fire | send-and-wait on `stop` |
|
||||
| Codeman never created it (a linked case pointing at your own checkout, a raw `workingDir`) | none written | never fire | `wait-output` markers only |
|
||||
| any claude workspace, with `workspaceHooksEnabled` ON (the default) | installed at session create, add-only merge | fire | send-and-wait on `stop` |
|
||||
| the same, with the setting OFF and no block already on disk | none added | never fire | `wait-output` markers only |
|
||||
| a remote SSH session, a docker case that opted out, a workspace Codeman cannot write | none | never fire | `wait-output` markers only |
|
||||
| a session created by a pre-1.19.0 server and never restarted since | whatever it had | only if present | check, then choose |
|
||||
|
||||
⚠️ **Docker cases are the one exception.** For a docker case, quick-start writes hooks
|
||||
whenever `.claude/settings.local.json` is *missing* (`session-routes.ts:2836-2845`:
|
||||
absent means write, present means refresh), regardless of who created that host
|
||||
directory. There the discriminator really is "does the settings file exist". No
|
||||
downstream advice changes, since docker quickcreate is already on the create side.
|
||||
The install is an add-only merge, so a user's own hook entries survive and a malformed
|
||||
settings file is left untouched. Sessions recovered at server boot get the same sweep,
|
||||
which is what heals sessions created before this behavior existed. When in doubt, test
|
||||
it rather than reason about it: grep for `/api/hook-event` in
|
||||
`<casePath>/.claude/settings.local.json`.
|
||||
|
||||
⚠️ For every non-docker case the discriminator is **who created the directory, not
|
||||
whether it exists now**. A
|
||||
scratch case Codeman created last week still has its hooks block on disk, so
|
||||
`quick-start` against that existing name gets working `stop` signals. Only a directory
|
||||
Codeman never created lacks them. When in doubt, test it rather than reason about it:
|
||||
grep for `/api/hook-event` in `<casePath>/.claude/settings.local.json`.
|
||||
|
||||
`writeHooksConfig()` runs only on the create paths (`case-routes.ts:341`, `:520`,
|
||||
`:869`, `ralph-routes.ts:318`, `session-routes.ts:2799` inside
|
||||
`if (!existsSync(resolvedCasePath))`, `:2841` for docker). Quick-start against a
|
||||
directory that already exists takes the else-if branch and calls
|
||||
`refreshStaleCodemanHooks()`, which returns immediately when there is no
|
||||
`settings.local.json` and again when the hooks it finds are not ours
|
||||
(`hooks-config.ts:706-731`); it never *adds* a hooks block. `POST /api/cases/link` is
|
||||
not on that list at all: it only records a name-to-path entry. See
|
||||
Before 1.19.0, `writeHooksConfig()` ran only on the create paths and `quick-start`
|
||||
against an existing directory called `refreshStaleCodemanHooks()`, which never *adds* a
|
||||
block, so a linked case or a raw `workingDir` had no hooks at all. `POST
|
||||
/api/cases/link` still only records a name-to-path entry; what changed is that the
|
||||
session-create path installs hooks regardless of how the directory got there. See
|
||||
[symptom 8](#8-send-and-wait-resolves-instantly-with-signalidle-and-the-answer-is-last-turns).
|
||||
|
||||
Default `until` set: `stop,idle,exit`. On non-claude modes the server silently drops
|
||||
|
||||
@@ -196,12 +196,14 @@ idle:
|
||||
The contract an orchestrator follows for any fleet of two or more messaging workers.
|
||||
Every topology in the next section is this protocol plus a wiring diagram.
|
||||
|
||||
1. **Spawn with a name, and with hooks.** Use `quick-start` with `sessionName` (the
|
||||
`--name` gate above), and let it **CREATE** the case. ⚠️ Linking does NOT install
|
||||
hooks (`POST /api/cases/link` writes only the name-to-path entry), and neither does a
|
||||
bare `POST /api/sessions`; a worker in a directory Codeman did not create has no
|
||||
`stop`/`blocked` signals at all and every synchronization below degrades to output
|
||||
markers. The discriminator is who created the directory, not whether it exists now.
|
||||
1. **Spawn with a name, and confirm hooks.** Use `quick-start` with `sessionName` (the
|
||||
`--name` gate above). Session create installs the hooks block into the workspace
|
||||
whatever kind it is, so a linked case and a raw `POST /api/sessions` path both get
|
||||
`stop`/`blocked` by default. ⚠️ Not unconditionally: the operator can turn
|
||||
`workspaceHooksEnabled` off, remote SSH sessions never get hooks, and a session from
|
||||
an older server may have none, and without them every synchronization below degrades
|
||||
to output markers. Grep `<casePath>/.claude/settings.local.json` for
|
||||
`/api/hook-event` at spawn rather than inferring it from how the directory got there.
|
||||
2. **Readiness before addressing.** Flow 1's ladder per worker, then the availability
|
||||
probe. A worker that fails the probe is an HTTP worker for the rest of the run; that
|
||||
is a routing decision, not an error.
|
||||
|
||||
@@ -492,9 +492,9 @@ What breaks if you use send-and-wait anyway: `wait:true` is accepted (the 400 is
|
||||
*mode*, not about hooks, and these are claude-mode sessions), so the call falls back to
|
||||
the default set's `idle`, which is a heuristic that flaps mid-turn. You get a "finished"
|
||||
answer for a turn still running, and `last-response` then hands you the *previous*
|
||||
turn's text. The contrast is the lesson: a worker in a case Codeman created (Flow 1) has
|
||||
the hooks, so `stop` there is definitive and free. In a worktree you pay one marker per
|
||||
worker instead.
|
||||
turn's text. The contrast is the lesson: a worker whose workspace carries the hooks
|
||||
block (Flow 1, and by default any other workspace too) has a `stop` that is definitive
|
||||
and free. Where the block is absent you pay one marker per worker instead.
|
||||
|
||||
```bash
|
||||
declare -A TOK
|
||||
|
||||
@@ -30,28 +30,40 @@ wrong directory.** `quick-start` with a new `caseName` does not find your repo:
|
||||
| Where the work is | Call | Hooks, and therefore signals |
|
||||
|-------------------|------|------------------------------|
|
||||
| a fresh scratch dir (throwaway experiments) | `POST /api/v1/quick-start {"caseName":"scratch-1","mode":"claude"}` with a **new** case name | Codeman creates the directory and **writes hooks**: `stop` and `blocked` fire, send-and-wait is trustworthy |
|
||||
| a linked case (a real repo in the linked-cases registry) | same call with the linked name | **no hooks**, unless that repo already carries a Codeman hooks block from some earlier path. Check before relying on `stop` |
|
||||
| any other absolute path, e.g. a git worktree you made | `POST /api/v1/sessions {"workingDir":"/abs/path","mode":"claude"}` then `POST /api/v1/sessions/:id/interactive` | **no hooks**: no `stop`, no `blocked`, synchronize with markers ([§5.5](#55-markers-for-hook-less-workers)) |
|
||||
| a linked case (a real repo in the linked-cases registry) | same call with the linked name | **hooks installed at session create**, so `stop` fires here too. Not guaranteed: the operator can turn it off. Check |
|
||||
| any other absolute path, e.g. a git worktree you made | `POST /api/v1/sessions {"workingDir":"/abs/path","mode":"claude"}` then `POST /api/v1/sessions/:id/interactive` | same: **hooks installed at session create**, subject to the same setting. Check |
|
||||
|
||||
Read `.data.casePath` back from the `quick-start` response and check it is where you
|
||||
meant. `caseName` accepts letters, digits, `-` and `_` only, and it resolves through
|
||||
the linked-cases registry **first**, so a name that collides with something the user
|
||||
linked in lands in that real repo rather than a scratch dir.
|
||||
|
||||
**The rule is who created the directory.** Codeman writes hooks only where it created
|
||||
the workspace itself: `quick-start` on a NEW case name, `POST /api/cases`, the repo
|
||||
clone, the docker quick-create. Those hooks persist, so a scratch case created last
|
||||
week still has them today. A directory that already existed when Codeman first pointed
|
||||
at it never gets them: `POST /api/cases/link` writes only the name-to-path entry in
|
||||
`linked-cases.json`, and quick-start into an existing path runs
|
||||
`refreshStaleCodemanHooks()`, which by design returns immediately when there is no
|
||||
Codeman hooks block to refresh. Source-verified by exhaustive call-site grep, and
|
||||
measured: a worker in a linked case never resolved a parked `wait?until=stop,exit`
|
||||
across twelve consecutive 60 s rounds, although it had finished its turn.
|
||||
**The rule is a setting, not who created the directory.** Every claude create path
|
||||
(`POST /api/sessions`, `POST /api/quick-start`, and quick-start's docker branch) now
|
||||
installs the hooks block into the workspace, and the server sweeps the workspaces of
|
||||
sessions it recovers at boot. So a linked case, a cloned repo and a hand-made git
|
||||
worktree all get `stop`/`blocked`, not just a scratch case Codeman scaffolded. The
|
||||
install is an **add-only merge**: a user's own hook entries and every other settings
|
||||
key survive, and a malformed settings file is left alone.
|
||||
|
||||
**Check, do not assume.** Read `<casePath>/.claude/settings.local.json` with your own
|
||||
file tools and look for `/api/hook-event`. Present means `stop`/`blocked` will fire;
|
||||
absent means they never will.
|
||||
The gate is the synced **`workspaceHooksEnabled`** setting, **default ON** (an absent
|
||||
key counts as ON). Turned OFF, the old behavior returns exactly: an existing Codeman
|
||||
block is still refreshed when stale, but one is never added, and the boot sweep is
|
||||
skipped. Three cases stay hook-less regardless: **remote SSH sessions** (their
|
||||
`workingDir` is a path on another host), **docker cases that opted out**, and any
|
||||
workspace Codeman cannot write to.
|
||||
|
||||
Until this landed, hooks existed only where Codeman created the directory, and the
|
||||
gap was invisible: a worker in a linked case never resolved a parked
|
||||
`wait?until=stop,exit` across twelve consecutive 60 s rounds, although it had finished
|
||||
its turn. If you are driving an older server, assume that older rule.
|
||||
|
||||
**Check, do not assume.** This is now the load-bearing habit, because you cannot tell
|
||||
from the call which way the setting is set, and an old session created before the fix
|
||||
on a server that has not restarted still has nothing. Read
|
||||
`<casePath>/.claude/settings.local.json` with your own file tools and look for
|
||||
`/api/hook-event`. Present means `stop`/`blocked` will fire; absent means they never
|
||||
will, whatever kind of workspace it is.
|
||||
|
||||
⚠️ **The hook-less failure is silent, and it is the worst one in this skill.**
|
||||
`"wait":true` is still **accepted** on a hook-less claude session: the 400 you may be
|
||||
@@ -59,9 +71,10 @@ expecting is about session *mode*, not about hooks. With no `stop` to resolve on
|
||||
default signal set falls back to the heuristic `idle`, which flaps mid-turn, so
|
||||
send-and-wait returns "finished" while the worker is still working, and the
|
||||
`last-response` you read next hands you the **previous** turn's text. No error is
|
||||
raised anywhere. In any workspace Codeman did not create, use markers
|
||||
([§5.5](#55-markers-for-hook-less-workers)) and treat send-and-wait's answer as
|
||||
unreliable.
|
||||
raised anywhere. Hooks are installed by default now, so this is rarer than it was, but
|
||||
the failure is unchanged when it happens: in any workspace whose settings file has no
|
||||
`/api/hook-event`, use markers ([§5.5](#55-markers-for-hook-less-workers)) and treat
|
||||
send-and-wait's answer as unreliable.
|
||||
|
||||
Spawning at a raw path:
|
||||
|
||||
@@ -238,11 +251,13 @@ fi
|
||||
|
||||
### 5.3 Send a task and wait
|
||||
|
||||
⚠️ **Precondition: this is the call to prefer only for a claude worker in a workspace
|
||||
Codeman created**, because it is trustworthy only when the `stop` hook exists. On a
|
||||
linked case or a raw path it is accepted, resolves on flapping `idle`, and reports a
|
||||
turn as finished while it is still running, with no error anywhere. Check hooks first
|
||||
([§5.1](#51-where-to-spawn)); where they are absent, use markers
|
||||
⚠️ **Precondition: a claude worker whose workspace has the hooks block**, because
|
||||
this is trustworthy only when the `stop` hook exists. Every claude create path installs
|
||||
it by default now, so that is the normal case, but where it is absent (the setting off,
|
||||
a remote session, an older server) the call is still accepted, resolves on flapping
|
||||
`idle`, and reports a turn as finished while it is still running, with no error
|
||||
anywhere. Check hooks first ([§5.1](#51-where-to-spawn)); where they are absent, use
|
||||
markers
|
||||
([§5.5](#55-markers-for-hook-less-workers)).
|
||||
|
||||
It registers the waiter *before* typing,
|
||||
|
||||
+20
-14
@@ -646,22 +646,28 @@ export async function writeHooksConfig(casePath: string): Promise<void> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures an explicitly managed case has the current Codeman hooks.
|
||||
* Ensures a workspace Codeman is about to run Claude in has the current Codeman hooks.
|
||||
*
|
||||
* Unlike `refreshStaleCodemanHooks`, this may add Codeman handlers to a valid
|
||||
* user-owned settings file. It is therefore reserved for case quick-starts,
|
||||
* where the user has explicitly asked Codeman to manage that workspace. A
|
||||
* malformed existing file is left untouched rather than replaced.
|
||||
* Unlike `refreshStaleCodemanHooks`, this may ADD Codeman handlers to a settings
|
||||
* file that has none (a linked case, a cloned repo, any directory Codeman did not
|
||||
* scaffold). It merges rather than replaces, so a user's own hook entries survive,
|
||||
* and a malformed existing file is left untouched rather than replaced.
|
||||
*
|
||||
* ⚠️ It has NO production call site: PR #233 landed it with the hook scripts and never
|
||||
* wired it up, and knip can't flag it (`test/**` are entry points, so its tests count as
|
||||
* a use). Kept anyway, because it is redundant with neither sibling: `writeHooksConfig`
|
||||
* REPLACES a malformed settings file and rewrites unconditionally, and
|
||||
* `refreshStaleCodemanHooks` deliberately never adds hooks to a case that has none. The
|
||||
* one place it fits is quick-start's existing-case branch in session-routes.ts, and
|
||||
* moving that branch onto this function is a POLICY change (hooks would come back for a
|
||||
* user who deleted them from their case, and linked cases would start getting a hooks
|
||||
* block they have never had), so that call is left to the owner rather than made here.
|
||||
* ⚠️ That "may add" is a deliberate POLICY, adopted 2026-08-15 after the symptom it
|
||||
* causes was reported: hooks were only ever written when Codeman CREATED a case
|
||||
* directory, so every session in a linked case ran with no hooks at all and each
|
||||
* hook-driven surface was silently dead there — an AskUserQuestion dialog blocking
|
||||
* the pane while the tab and the phone overview both read a calm `idle`, no
|
||||
* Approvals Inbox item, no push, no definitive `stop`/`idle_prompt` for respawn, and
|
||||
* no `stop`/`blocked` for the agent wait endpoints. The cost of the policy is the
|
||||
* other direction: a user who DELETES Codeman's hooks from a workspace gets them
|
||||
* back on the next session create there, because nothing on disk distinguishes
|
||||
* "removed on purpose" from "never had any".
|
||||
*
|
||||
* Called from both session-create paths (`POST /api/sessions`, `POST /api/quick-start`)
|
||||
* for claude mode, and from `restoreMuxSessions()` so sessions that predate this heal
|
||||
* on the next server start. Claude Code re-reads the file, so a session ALREADY running
|
||||
* in the workspace picks the hooks up without a restart (verified live, 2026-08-15).
|
||||
*/
|
||||
export async function ensureCodemanHooks(casePath: string): Promise<void> {
|
||||
await withSafeSettingsWrite(casePath, 'hooks (ensure)', async (claudeDir, settingsPath) => {
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface ConfigPort {
|
||||
getTerminalHistoryConfig(): Promise<TerminalHistoryConfig>;
|
||||
/** Synced `agentSkillEnabled` app setting (default OFF); gates per-case agent-skill injection. */
|
||||
getAgentSkillEnabled(): Promise<boolean>;
|
||||
/** Synced `workspaceHooksEnabled` app setting (default ON); gates INSTALLING hooks into a session's workspace. */
|
||||
getWorkspaceHooksEnabled(): Promise<boolean>;
|
||||
/** Synced `claudeVoiceEnabled` app setting (default OFF); gates the Claude voice dictation relay. */
|
||||
getClaudeVoiceEnabled(): Promise<boolean>;
|
||||
getDefaultClaudeMdPath(): Promise<string | undefined>;
|
||||
|
||||
@@ -437,94 +437,6 @@ function computeSseStale(input) {
|
||||
return now - lastMessageAt >= timeoutMs;
|
||||
}
|
||||
|
||||
// Home-screen session order: one comparator for both overviews.
|
||||
//
|
||||
// The phone overview (mobile-overview.js) and the desktop tab rail
|
||||
// (home-sessions.js) list the same sessions, so they answer the same question
|
||||
// and must answer it the same way: "which of these wants me next?".
|
||||
//
|
||||
// 1. Anything blocked on a human first (red question, then error, then a
|
||||
// yellow idle prompt), longest-blocked at the top: a session that has been
|
||||
// sitting on a permission dialog for 20 minutes is starving, one that
|
||||
// raised it 5 seconds ago is not.
|
||||
// 2. Then whatever is running, LONGEST-RUNNING first, since that is the turn most
|
||||
// likely to be finished, or stuck, by the time you look.
|
||||
// 3. Then everything quiet, MOST RECENTLY quiet first: when nothing is
|
||||
// running, the session that just finished is the one you came back for,
|
||||
// and the one you abandoned yesterday sinks.
|
||||
//
|
||||
// So the tiebreak flips direction halfway down the list, and that is the point:
|
||||
// for a state something is still doing, longer = more urgent; for a state
|
||||
// something has stopped in, more recent = more relevant.
|
||||
//
|
||||
// Pure: no DOM, no clock (every input is an epoch-ms stamp already on the
|
||||
// session payload), no `this`. Unit-tested in test/session-overview-order.test.ts.
|
||||
const SESSION_ACTIVITY_RANK = {
|
||||
needs: 0,
|
||||
error: 1,
|
||||
waiting: 2,
|
||||
working: 3,
|
||||
idle: 4,
|
||||
done: 5,
|
||||
};
|
||||
|
||||
/** States still in progress, where the OLDEST stamp sorts first. */
|
||||
const SESSION_ACTIVITY_OLDEST_FIRST = ['needs', 'error', 'waiting', 'working'];
|
||||
|
||||
/**
|
||||
* When the row entered the state it is in.
|
||||
*
|
||||
* For everything quiet that is `lastActivityAt`, the last byte the pane printed:
|
||||
* a Claude pane sitting at its composer prints nothing, so the end of the last
|
||||
* turn is exactly when it went quiet.
|
||||
*
|
||||
* A WORKING pane is the opposite: it repaints about once a second, so its
|
||||
* last-activity stamp is always "now" and would rank every running turn as
|
||||
* freshly started. Its real start is the pane's last Enter (`lastSubmitAt`),
|
||||
* persisted server-side and therefore stable across a Codeman restart. A
|
||||
* working pane that has never submitted (spawned with its prompt on the command
|
||||
* line, or an external CLI) falls back to last activity, which puts it at the
|
||||
* short end of the running group rather than falsely at the head of it.
|
||||
*/
|
||||
function sessionActivityAnchor(row) {
|
||||
const activeAt = Number(row && row.lastActivityAt) || 0;
|
||||
if (row && row.state === 'working') return Number(row.lastSubmitAt) || activeAt;
|
||||
return activeAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort comparator for one overview row against another.
|
||||
* @param {{state: string, lastActivityAt?: number, lastSubmitAt?: number, orderIndex?: number}} a
|
||||
* @param {{state: string, lastActivityAt?: number, lastSubmitAt?: number, orderIndex?: number}} b
|
||||
*/
|
||||
function compareSessionActivity(a, b) {
|
||||
const rankA = SESSION_ACTIVITY_RANK[a.state];
|
||||
const rankB = SESSION_ACTIVITY_RANK[b.state];
|
||||
const rank = (rankA === undefined ? 99 : rankA) - (rankB === undefined ? 99 : rankB);
|
||||
if (rank !== 0) return rank;
|
||||
|
||||
const atA = sessionActivityAnchor(a);
|
||||
const atB = sessionActivityAnchor(b);
|
||||
if (atA !== atB) {
|
||||
// A row with no stamp at all gets no opinion: it sorts last either way
|
||||
// rather than claiming to be the oldest (0) thing on the screen.
|
||||
if (!atA) return 1;
|
||||
if (!atB) return -1;
|
||||
return SESSION_ACTIVITY_OLDEST_FIRST.includes(a.state) ? atA - atB : atB - atA;
|
||||
}
|
||||
|
||||
// Equal stamps (or two unstamped rows): fall back to the user's tab order so
|
||||
// the list is deterministic and cannot shuffle between renders.
|
||||
const orderA = Number.isFinite(a.orderIndex) ? a.orderIndex : Number.MAX_SAFE_INTEGER;
|
||||
const orderB = Number.isFinite(b.orderIndex) ? b.orderIndex : Number.MAX_SAFE_INTEGER;
|
||||
return orderA - orderB;
|
||||
}
|
||||
|
||||
/** Copy of `rows`, in overview order. Never sorts in place, so callers keep their array. */
|
||||
function sortSessionsByActivity(rows) {
|
||||
return (Array.isArray(rows) ? rows.slice() : []).sort(compareSessionActivity);
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.WEBGL_FALLBACK = WEBGL_FALLBACK;
|
||||
window.evaluateWebGLLongTaskTrip = evaluateWebGLLongTaskTrip;
|
||||
@@ -552,12 +464,6 @@ if (typeof window !== 'undefined') {
|
||||
compute: computeSseStale,
|
||||
TIMEOUT_MS: SSE_STALE_TIMEOUT_MS,
|
||||
};
|
||||
window.CodemanSessionOrder = {
|
||||
RANK: SESSION_ACTIVITY_RANK,
|
||||
anchor: sessionActivityAnchor,
|
||||
compare: compareSessionActivity,
|
||||
sort: sortSessionsByActivity,
|
||||
};
|
||||
}
|
||||
|
||||
// Scheduler API — prioritize terminal writes over background UI updates.
|
||||
|
||||
@@ -5,13 +5,8 @@
|
||||
* The welcome screen centers ~560px of content in a window that is usually
|
||||
* 1400px+, so the two gutters are dead space. The left one now carries the same
|
||||
* list a phone gets on its home screen (mobile-overview.js), turned vertical:
|
||||
* one row per live tab.
|
||||
*
|
||||
* Rows are ordered by `CodemanSessionOrder` (constants.js), the same comparator
|
||||
* the phone overview uses: blocked on you first, then running longest-first,
|
||||
* then quiet most-recently-quiet first. The number badge stays the tab-strip
|
||||
* index (Alt+1..9), so it is deliberately NOT sequential down a sorted rail:
|
||||
* it names a shortcut, not a row position.
|
||||
* one row per live tab, in TAB ORDER (not sorted by state) so it reads as the
|
||||
* tab strip rotated, and so Alt+1..9 still matches what you see.
|
||||
*
|
||||
* DESKTOP ONLY, and only in a wide enough window: the rail is absolutely
|
||||
* positioned so the centered welcome content never moves, which means it can
|
||||
@@ -21,13 +16,11 @@
|
||||
* both scale with the viewport (see the `.home-sessions` block in styles.css) —
|
||||
* a fixed 256px card looks abandoned on a 2560px display.
|
||||
*
|
||||
* Each row carries when the session was FIRST CREATED and how long it has been
|
||||
* in the state it is in ("created 3d ago · working 12m"), and that second stamp is
|
||||
* the value the order above is computed from, so the rail explains itself
|
||||
* rather than looking arbitrarily shuffled. Both stamps go stale on their own
|
||||
* (a sitting session emits no event), so a slow clock refreshes them IN PLACE
|
||||
* from the epoch-ms values parked on the elements, rather than re-rendering: a
|
||||
* re-render would restart every row's blink animation and its working ring.
|
||||
* Each row carries when the session was FIRST CREATED and when it was LAST
|
||||
* ACTIVE, both relative. Those two stamps go stale on their own (a sitting
|
||||
* session emits no event), so a slow clock refreshes them IN PLACE from the
|
||||
* epoch-ms values parked on the elements, rather than re-rendering: a re-render
|
||||
* would restart every row's blink animation and its working ring.
|
||||
*
|
||||
* The working state is deliberately identical to the phone's: a pulsing green
|
||||
* dot ringed by the spinner a tab shows while it loads (`tab-load-spin`, reused
|
||||
@@ -41,7 +34,6 @@
|
||||
*
|
||||
* @mixin Extends CodemanApp.prototype via Object.assign
|
||||
* @dependency app.js (this.sessions, this.cases, this.pendingHooks, selectSession)
|
||||
* @dependency constants.js (CodemanSessionOrder, the shared row comparator)
|
||||
* @dependency mobile-overview.js (_mobileOverviewState, _mobileOverviewCaseFor, shouldUseMobileOverview)
|
||||
* @dependency ralph-panel.js (formatRelativeTime — the app's one relative-time formatter)
|
||||
* @dependency webview-tabs.js (this.webviews, this.webviewOrder, openWebview)
|
||||
@@ -166,18 +158,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* One row per live session, in overview order: whatever is blocked on you
|
||||
* first, then whatever is running (longest turn first), then the quiet ones
|
||||
* most-recently-quiet first. The comparator is `CodemanSessionOrder`
|
||||
* (constants.js), shared with the phone overview, and state classification is
|
||||
* `_mobileOverviewState()` (mobile-overview.js), so the two home screens can
|
||||
* neither disagree about what "working" means nor about what sorts first.
|
||||
*
|
||||
* `orderIndex` stays the position in the TAB STRIP, because that is what the
|
||||
* number badge means (Alt+1..9). Once the rows are sorted those badges no
|
||||
* longer run 1,2,3 down the rail: the badge answers "which key selects this",
|
||||
* not "how far down the list is it".
|
||||
*
|
||||
* One row per live session, in the user's tab order. State classification is
|
||||
* `_mobileOverviewState()` (mobile-overview.js) so both home screens agree on
|
||||
* what counts as needing you; the ORDER differs on purpose — the phone sorts
|
||||
* by urgency because it shows one screenful at a time, this column mirrors the
|
||||
* tab strip so the number badges line up with Alt+1..9.
|
||||
* @returns {Array<object>} row descriptors, ready to render
|
||||
*/
|
||||
buildHomeSessionRows() {
|
||||
@@ -188,14 +173,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
// invisible here while its tab already exists.
|
||||
for (const id of this.sessions?.keys() || []) if (!ids.includes(id)) ids.push(id);
|
||||
|
||||
const rows = ids.map((id, orderIndex) => {
|
||||
return ids.map((id, index) => {
|
||||
const session = this.sessions.get(id);
|
||||
const matched = this._mobileOverviewCaseFor(session.workingDir, cases);
|
||||
const state = this._mobileOverviewState(session, this.pendingHooks?.get(id));
|
||||
const mode = session.mode || 'claude';
|
||||
return {
|
||||
id,
|
||||
orderIndex,
|
||||
index,
|
||||
name: this.getSessionName ? this.getSessionName(session) : session.name || id.slice(0, 8),
|
||||
mode,
|
||||
modeBadge: HOME_SESSIONS_MODE_BADGE[mode] || '',
|
||||
@@ -207,19 +192,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
// render time so the clock below can redo it without a re-render.
|
||||
createdAt: Number(session.createdAt) || 0,
|
||||
lastActivityAt: Number(session.lastActivityAt) || 0,
|
||||
// The running group is ordered by the pane's last Enter, since a
|
||||
// working pane's last-activity stamp is always "now".
|
||||
lastSubmitAt: Number(session.lastSubmitAt) || 0,
|
||||
// "how long has it been like this", resolved by the phone overview's
|
||||
// helper so both home screens label the same stamp with the same word.
|
||||
since: this._mobileOverviewSince(state, session),
|
||||
};
|
||||
});
|
||||
|
||||
// Guarded like every other constants.js consumer: a stale cached
|
||||
// constants.js (iOS Safari serves old JS after a deploy) must degrade to
|
||||
// tab order, not TypeError the whole home screen away.
|
||||
return window.CodemanSessionOrder ? window.CodemanSessionOrder.sort(rows) : rows;
|
||||
},
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -260,40 +234,32 @@ Object.assign(CodemanApp.prototype, {
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* The "created 2h ago · working 12m" footer line. Both stamps keep their raw
|
||||
* The "created 2h ago · active 3m ago" footer line. Both stamps keep their raw
|
||||
* epoch-ms on the element (`data-hs-ts`) so `_tickHomeSessionsTimes()` can
|
||||
* rewrite the text without rebuilding the row.
|
||||
*
|
||||
* The second stamp is the row's state duration, NOT a plain last-active
|
||||
* stamp: it is the number the rail is sorted by, and a working row that reads
|
||||
* "active just now" (every working pane repaints about once a second) hides
|
||||
* exactly the value that decided its position. `_mobileOverviewSince()` owns
|
||||
* both the word and the anchor, so the phone says the same thing.
|
||||
*/
|
||||
_buildHomeSessionsMeta(row) {
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'home-sessions-row-meta';
|
||||
// Relative times are generated text, and "created"/"idle" here are the
|
||||
// Relative times are generated text, and "created"/"active" here are the
|
||||
// same generic words that mean something else on other surfaces.
|
||||
meta.setAttribute('data-i18n-skip', '');
|
||||
|
||||
meta.appendChild(this._buildHomeSessionsStamp('created', row.createdAt, 'ago', 'home-sessions-meta-created'));
|
||||
meta.appendChild(this._buildHomeSessionsStamp('created', row.createdAt, 'home-sessions-meta-created'));
|
||||
|
||||
if (row.since) {
|
||||
const sep = document.createElement('span');
|
||||
sep.className = 'home-sessions-meta-sep';
|
||||
sep.setAttribute('aria-hidden', 'true');
|
||||
sep.textContent = '·';
|
||||
meta.appendChild(sep);
|
||||
const sep = document.createElement('span');
|
||||
sep.className = 'home-sessions-meta-sep';
|
||||
sep.setAttribute('aria-hidden', 'true');
|
||||
sep.textContent = '·';
|
||||
meta.appendChild(sep);
|
||||
|
||||
meta.appendChild(this._buildHomeSessionsStamp(row.since.key, row.since.at, 'for', 'home-sessions-meta-since'));
|
||||
}
|
||||
meta.appendChild(this._buildHomeSessionsStamp('active', row.lastActivityAt, 'home-sessions-meta-active'));
|
||||
|
||||
return meta;
|
||||
},
|
||||
|
||||
/** One labelled stamp: a dim key, the value, full date in the title. */
|
||||
_buildHomeSessionsStamp(key, timestamp, format, className) {
|
||||
/** One labelled stamp: a dim key, the relative value, full date in the title. */
|
||||
_buildHomeSessionsStamp(key, timestamp, className) {
|
||||
const wrap = document.createElement('span');
|
||||
wrap.className = `home-sessions-meta-item ${className}`;
|
||||
|
||||
@@ -304,21 +270,18 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
const value = document.createElement('span');
|
||||
value.dataset.hsTs = String(timestamp || 0);
|
||||
value.dataset.hsFmt = format;
|
||||
value.textContent = this._homeSessionsStampText(timestamp, format);
|
||||
value.textContent = this._homeSessionsAgo(timestamp);
|
||||
wrap.appendChild(value);
|
||||
|
||||
if (timestamp) wrap.title = `${key === 'created' ? 'First created' : key}: ${new Date(timestamp).toLocaleString()}`;
|
||||
if (timestamp)
|
||||
wrap.title = `${key === 'created' ? 'First created' : 'Last active'}: ${new Date(timestamp).toLocaleString()}`;
|
||||
return wrap;
|
||||
},
|
||||
|
||||
/**
|
||||
* 'ago' points at a moment ("3d ago"), 'for' measures a span to now ("12m").
|
||||
* Both come from the phone overview's formatter, so a duration is written the
|
||||
* same way on both home screens.
|
||||
*/
|
||||
_homeSessionsStampText(timestamp, format) {
|
||||
return this._mobileOverviewStampText(timestamp, format);
|
||||
/** Relative label for a stamp. `formatRelativeTime` is the app's one formatter. */
|
||||
_homeSessionsAgo(timestamp) {
|
||||
if (!timestamp) return '—';
|
||||
return this.formatRelativeTime(timestamp) || '—';
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -348,7 +311,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
if (!el) return;
|
||||
for (const node of el.querySelectorAll('[data-hs-ts]')) {
|
||||
const ts = Number(node.dataset.hsTs) || 0;
|
||||
const text = this._homeSessionsStampText(ts, node.dataset.hsFmt);
|
||||
const text = this._homeSessionsAgo(ts);
|
||||
if (node.textContent !== text) node.textContent = text;
|
||||
}
|
||||
},
|
||||
@@ -385,14 +348,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
item.dataset.hsSession = row.id;
|
||||
item.title = row.dir ? `${row.name} (${row.dir})` : row.name;
|
||||
|
||||
// The badge is the Alt+N key for this tab, so it keeps the tab-strip index
|
||||
// even though the rows are sorted by activity: it will not read 1,2,3 down
|
||||
// the rail, and must not, or the shortcut it names would be wrong.
|
||||
if (row.orderIndex < 9) {
|
||||
if (row.index < 9) {
|
||||
const number = document.createElement('span');
|
||||
number.className = 'home-sessions-number';
|
||||
number.setAttribute('data-i18n-skip', '');
|
||||
number.textContent = String(row.orderIndex + 1);
|
||||
number.textContent = String(row.index + 1);
|
||||
item.appendChild(number);
|
||||
}
|
||||
|
||||
|
||||
@@ -1984,6 +1984,13 @@
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsAgentSkill"><span class="slider"></span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="workspace hooks alerts approvals notifications settings.local.json">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Workspace Hooks</span>
|
||||
<span class="set-row-desc">Install Codeman's hooks in each Claude workspace, so tab alerts, the Approvals Inbox and idle detection also work in linked cases and existing repos. Off leaves your repos untouched.</span>
|
||||
</div>
|
||||
<label class="switch switch-sm"><input type="checkbox" id="appSettingsWorkspaceHooks"><span class="slider"></span></label>
|
||||
</div>
|
||||
<div class="set-row" data-search="remote auto reconnect ssh">
|
||||
<div class="set-row-text">
|
||||
<span class="set-row-label">Remote auto-reconnect</span>
|
||||
|
||||
@@ -8,10 +8,6 @@
|
||||
* errored sessions), then SPACES (cases, expandable to their sessions), then
|
||||
* WORKING and IDLE / DONE.
|
||||
*
|
||||
* Rows inside a section are ordered by `CodemanSessionOrder` (constants.js),
|
||||
* the SAME comparator the desktop rail uses: blocked longest-first, then
|
||||
* running longest-first, then quiet most-recently-quiet first.
|
||||
*
|
||||
* PHONE ONLY. The gate is `shouldUseMobileOverview()` (viewport < 430px, not a
|
||||
* popped-out solo window, per-device setting on). Tablet and desktop keep the
|
||||
* welcome overlay untouched. The container ships with the `hidden` attribute and
|
||||
@@ -29,7 +25,6 @@
|
||||
* `buildMobileOverviewModel()` is pure and unit-tested (test/mobile-overview.test.ts).
|
||||
*
|
||||
* @mixin Extends CodemanApp.prototype via Object.assign
|
||||
* @dependency constants.js (CodemanSessionOrder, the shared row comparator)
|
||||
* @dependency app.js (this.sessions, this.cases, this.pendingHooks, selectSession, run)
|
||||
* @dependency ralph-panel.js (formatRelativeTime, the app's one relative-time formatter)
|
||||
* @dependency mobile-handlers.js (MobileDetection)
|
||||
@@ -40,6 +35,16 @@
|
||||
/** Viewport width that counts as a phone. Matches the mobile.css phone block. */
|
||||
const MOBILE_OVERVIEW_PHONE_QUERY = '(max-width: 430px)';
|
||||
|
||||
/** Sort rank per state: the most demanding thing sorts first inside a section. */
|
||||
const MOBILE_OVERVIEW_STATE_RANK = {
|
||||
needs: 0,
|
||||
error: 1,
|
||||
waiting: 2,
|
||||
working: 3,
|
||||
idle: 4,
|
||||
done: 5,
|
||||
};
|
||||
|
||||
/** How many past conversations show before the "Show all" toggle. */
|
||||
const MOBILE_OVERVIEW_PAST_LIMIT = 8;
|
||||
|
||||
@@ -183,25 +188,18 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Epoch ms, straight off the session payload; formatting happens at
|
||||
// render time so the clock can redo it without a re-render.
|
||||
createdAt: Number(session.createdAt) || 0,
|
||||
// Raw stamps for the shared order comparator; `since` above is the same
|
||||
// pair resolved for DISPLAY, and the two must not drift apart.
|
||||
lastActivityAt: Number(session.lastActivityAt) || 0,
|
||||
lastSubmitAt: Number(session.lastSubmitAt) || 0,
|
||||
since: this._mobileOverviewSince(state, session),
|
||||
orderIndex: orderIndex === -1 ? Number.MAX_SAFE_INTEGER : orderIndex,
|
||||
};
|
||||
});
|
||||
|
||||
// Order is `CodemanSessionOrder` (constants.js), shared with the desktop
|
||||
// rail: blocked first (longest-blocked at the top), then running
|
||||
// longest-first, then quiet most-recent-first.
|
||||
// Guarded: a stale cached constants.js (iOS Safari after a deploy) must
|
||||
// degrade to tab order, not TypeError the overview away.
|
||||
const inSection = (states) => {
|
||||
const filtered = rows.filter((r) => states.includes(r.state));
|
||||
return window.CodemanSessionOrder ? window.CodemanSessionOrder.sort(filtered) : filtered;
|
||||
const bySeverityThenOrder = (a, b) => {
|
||||
const rank = MOBILE_OVERVIEW_STATE_RANK[a.state] - MOBILE_OVERVIEW_STATE_RANK[b.state];
|
||||
return rank !== 0 ? rank : a.orderIndex - b.orderIndex;
|
||||
};
|
||||
|
||||
const inSection = (states) => rows.filter((r) => states.includes(r.state)).sort(bySeverityThenOrder);
|
||||
|
||||
// Past = conversations from the unified list that are not currently live.
|
||||
// The endpoint already folds a transcript into its owning session (via the
|
||||
// claudeSessionId alias map), so a plain id check is enough to avoid listing
|
||||
|
||||
@@ -409,6 +409,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Claude Permissions settings
|
||||
document.getElementById('appSettingsAgentTeams').checked = settings.agentTeamsEnabled ?? false;
|
||||
document.getElementById('appSettingsAgentSkill').checked = settings.agentSkillEnabled ?? false;
|
||||
// Default ON: an absent key is a user who has never seen this setting, and OFF
|
||||
// for them means no tab alerts in any workspace Codeman did not scaffold.
|
||||
document.getElementById('appSettingsWorkspaceHooks').checked = settings.workspaceHooksEnabled !== false;
|
||||
document.getElementById('appSettingsClaudeModel').value = settings.claudeModel ?? '';
|
||||
document.getElementById('appSettingsOpusContext1m').checked = settings.opusContext1mEnabled ?? false;
|
||||
document.getElementById('appSettingsRemoteAutoReconnect').checked = settings.remoteAutoReconnect ?? true;
|
||||
@@ -2017,6 +2020,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Claude Permissions settings
|
||||
agentTeamsEnabled: document.getElementById('appSettingsAgentTeams').checked,
|
||||
agentSkillEnabled: document.getElementById('appSettingsAgentSkill').checked,
|
||||
workspaceHooksEnabled: document.getElementById('appSettingsWorkspaceHooks').checked,
|
||||
claudeVoiceEnabled: document.getElementById('appSettingsClaudeVoice').checked,
|
||||
claudeModel: document.getElementById('appSettingsClaudeModel').value,
|
||||
opusContext1mEnabled: document.getElementById('appSettingsOpusContext1m').checked,
|
||||
|
||||
@@ -14902,9 +14902,8 @@ html[data-skin="daylight-blue"] .welcome-btn-tunnel.active:hover {
|
||||
}
|
||||
|
||||
/* The freshest signal on the row: while a session is actually doing something,
|
||||
how long it has been doing it is what the eye should land on (and it is what
|
||||
the rail is sorted by). */
|
||||
.home-sessions-row--working .home-sessions-meta-since {
|
||||
its "active" stamp is the one the eye should land on. */
|
||||
.home-sessions-row--working .home-sessions-meta-active {
|
||||
color: var(--green);
|
||||
opacity: 0.95;
|
||||
}
|
||||
|
||||
@@ -84,6 +84,7 @@ import {
|
||||
applyAgentSkill,
|
||||
refreshUserAgentSkill,
|
||||
seedAgentSessionPreamble,
|
||||
ensureCodemanHooks,
|
||||
refreshStaleCodemanHooks,
|
||||
} from '../../hooks-config.js';
|
||||
import { generateClaudeMd } from '../../templates/claude-md.js';
|
||||
@@ -625,6 +626,32 @@ async function injectAgentSkill(casePath: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hooks for the workspace a Claude session is about to run in. ONE decision point,
|
||||
* shared by every create path, so the setting cannot apply to some of them only.
|
||||
*
|
||||
* ON (`workspaceHooksEnabled`, the default): INSTALL Codeman's hooks block, merging
|
||||
* so a user's own hook entries and every other settings key survive. Hooks were
|
||||
* previously written only when Codeman CREATED the case DIRECTORY, so a linked case
|
||||
* or any pre-existing repo — where most sessions actually run — had none, and every
|
||||
* hook-driven surface was silently dead there: no tab alert or phone-overview row
|
||||
* when a dialog blocks the pane, no Approvals Inbox item, no push, no definitive
|
||||
* `stop`/`idle_prompt` for respawn, and no `stop`/`blocked` for the wait endpoints.
|
||||
* Measured 2026-08-15 in a linked case: an AskUserQuestion dialog on screen with the
|
||||
* tab reporting a calm `idle`. Claude Code re-reads the file, so a session already
|
||||
* running in that workspace starts firing hooks without a restart (verified live).
|
||||
*
|
||||
* OFF: the older, narrower behavior. A Codeman block that is already there is still
|
||||
* refreshed when stale (COD-91: a pre-secret block 401s once the hook-secret gate
|
||||
* went unconditional), but one is never added, so Codeman leaves the repo alone.
|
||||
*
|
||||
* Best-effort either way: a refusal or a thrown error must never fail the create.
|
||||
*/
|
||||
async function applyWorkspaceHooks(ctx: ConfigPort, workspace: string): Promise<void> {
|
||||
const install = await ctx.getWorkspaceHooksEnabled();
|
||||
await (install ? ensureCodemanHooks(workspace) : refreshStaleCodemanHooks(workspace)).catch(() => {});
|
||||
}
|
||||
|
||||
export function registerSessionRoutes(
|
||||
app: FastifyInstance,
|
||||
ctx: SessionPort & EventPort & ConfigPort & InfraPort & AuthPort
|
||||
@@ -765,11 +792,10 @@ export function registerSessionRoutes(
|
||||
await applyStatusLineConfig(workingDir, true);
|
||||
}
|
||||
|
||||
// COD-91 self-heal: refresh a pre-secret hooks block in an existing case so the now
|
||||
// unconditional hook-secret gate keeps accepting its hook events. No-op for fresh
|
||||
// cases (writeHooksConfig already wrote the secret) and for non-Codeman/absent hooks.
|
||||
// Hooks for the workspace this session runs in (install vs refresh-only is the
|
||||
// `workspaceHooksEnabled` setting; see applyWorkspaceHooks).
|
||||
if ((body.mode ?? 'claude') === 'claude') {
|
||||
await refreshStaleCodemanHooks(workingDir).catch(() => {});
|
||||
await applyWorkspaceHooks(ctx, workingDir);
|
||||
// Agent skill (docs/agent-control-plan.md §2): ADD-ONLY on create, same shared-
|
||||
// .claude rationale as the statusLine above: a create must never remove the
|
||||
// skill from under other live sessions in the repo. Marker-guarded, so a
|
||||
@@ -2899,11 +2925,17 @@ export function registerSessionRoutes(
|
||||
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, `Failed to create case: ${getErrorMessage(err)}`);
|
||||
}
|
||||
} else if (!remote && !docker && mode !== 'opencode') {
|
||||
// COD-91 self-heal for an EXISTING case: refresh a pre-secret hooks block so the
|
||||
// now-unconditional hook-secret gate keeps accepting its hook events. No-op when
|
||||
// the hooks aren't ours or already carry the secret. Skipped for remote cases —
|
||||
// resolvedCasePath is a REMOTE path that doesn't exist on the local filesystem.
|
||||
await refreshStaleCodemanHooks(resolvedCasePath).catch(() => {});
|
||||
// EXISTING case directory (a linked case, a cloned repo, anything Codeman did
|
||||
// not scaffold): install-or-refresh per the setting (see applyWorkspaceHooks).
|
||||
// Other modes keep the narrower COD-91 self-heal unconditionally: only claude
|
||||
// reads `.claude` hooks, so a shell/codex quick-start should not author a block
|
||||
// of its own. Skipped for remote cases — resolvedCasePath is a REMOTE path that
|
||||
// doesn't exist on the local filesystem.
|
||||
if (mode === 'claude') {
|
||||
await applyWorkspaceHooks(ctx, resolvedCasePath);
|
||||
} else {
|
||||
await refreshStaleCodemanHooks(resolvedCasePath).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
// Agent skill injection (docs/agent-control-plan.md §2): ADD-ONLY on create,
|
||||
@@ -2936,7 +2968,10 @@ export function registerSessionRoutes(
|
||||
if (!existsSync(join(resolvedCasePath, '.claude', 'settings.local.json'))) {
|
||||
await writeHooksConfig(resolvedCasePath);
|
||||
} else {
|
||||
await refreshStaleCodemanHooks(resolvedCasePath).catch(() => {});
|
||||
// A settings file with no hooks in it is the same dead-surface case as a
|
||||
// linked case. This branch is already gated on `docker.hooksEnabled`, and
|
||||
// applyWorkspaceHooks adds the user-level gate on top.
|
||||
await applyWorkspaceHooks(ctx, resolvedCasePath);
|
||||
}
|
||||
} catch {
|
||||
/* non-fatal — the session still runs, hooks may be degraded */
|
||||
|
||||
@@ -906,6 +906,17 @@ export const SettingsUpdateSchema = z
|
||||
* add-only at create; a marker keeps user-authored copies untouched.
|
||||
*/
|
||||
agentSkillEnabled: z.boolean().optional(),
|
||||
/**
|
||||
* Install Codeman's hooks block into the workspace of every Claude session,
|
||||
* not only into cases Codeman scaffolded itself. SYNCED, default ON: without
|
||||
* it a linked case or an existing repo runs with no hooks at all, and each
|
||||
* hook-driven surface is silently dead there (tab alert, Approvals Inbox,
|
||||
* push, respawn's definitive idle signals, the wait endpoints' stop/blocked).
|
||||
* Turning it OFF restores the older, narrower behavior — a Codeman hooks
|
||||
* block that is already present is still refreshed when stale, but one is
|
||||
* never added — for a user who wants Codeman to leave their repos alone.
|
||||
*/
|
||||
workspaceHooksEnabled: z.boolean().optional(),
|
||||
/**
|
||||
* Let browser dictation transcribe through this machine's Claude Code login,
|
||||
* the same speech-to-text service the CLI's own `/voice` mode uses
|
||||
|
||||
@@ -76,6 +76,7 @@ import { RunSummaryTracker } from '../run-summary.js';
|
||||
import { PlanOrchestrator } from '../plan-orchestrator.js';
|
||||
import { OrchestratorLoop } from '../orchestrator-loop.js';
|
||||
import { getLifecycleLog } from '../session-lifecycle-log.js';
|
||||
import { ensureCodemanHooks } from '../hooks-config.js';
|
||||
import { PushSubscriptionStore } from '../push-store.js';
|
||||
import webpush from 'web-push';
|
||||
import { SseStreamManager } from './sse-stream-manager.js';
|
||||
@@ -636,6 +637,7 @@ export class WebServer extends EventEmitter {
|
||||
getClaudeModeConfig: this.getClaudeModeConfig.bind(this),
|
||||
getTerminalHistoryConfig: this.getTerminalHistoryConfig.bind(this),
|
||||
getAgentSkillEnabled: this.getAgentSkillEnabled.bind(this),
|
||||
getWorkspaceHooksEnabled: this.getWorkspaceHooksEnabled.bind(this),
|
||||
getClaudeVoiceEnabled: this.getClaudeVoiceEnabled.bind(this),
|
||||
getDefaultClaudeMdPath: this.getDefaultClaudeMdPath.bind(this),
|
||||
getLightState: this.getLightState.bind(this),
|
||||
@@ -1710,6 +1712,16 @@ export class WebServer extends EventEmitter {
|
||||
return settings.agentSkillEnabled === true;
|
||||
}
|
||||
|
||||
// Whether a Claude session installs Codeman's hooks block into its workspace
|
||||
// (synced `workspaceHooksEnabled` setting). Default ON — an absent key means a
|
||||
// user who has never seen this setting, and OFF for them would mean no tab
|
||||
// alerts, no Approvals Inbox and no respawn idle signals in every workspace
|
||||
// Codeman did not scaffold itself.
|
||||
private async getWorkspaceHooksEnabled(): Promise<boolean> {
|
||||
const settings = await this.readSettings();
|
||||
return settings.workspaceHooksEnabled !== false;
|
||||
}
|
||||
|
||||
// Whether browser dictation may use this machine's Claude Code credentials
|
||||
// (synced `claudeVoiceEnabled` setting, default OFF; docs/claude-voice-plan.md).
|
||||
// OFF by default because turning it on spends the operator's Claude subscription
|
||||
@@ -2819,6 +2831,13 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// Sessions recovered from a previous run predate the create-path hook
|
||||
// install, and these are long-lived: by the time a server restart comes
|
||||
// round a session may be days old and has been running hook-blind the
|
||||
// whole time. Claude Code re-reads settings.local.json, so writing the
|
||||
// block now arms the RUNNING CLI, no session restart needed.
|
||||
await this.ensureHooksForRecoveredWorkspaces();
|
||||
|
||||
// Start stats collection for mux sessions
|
||||
this.mux.startStatsCollection(STATS_COLLECTION_INTERVAL_MS);
|
||||
}
|
||||
@@ -2845,6 +2864,37 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install Codeman's hooks into the workspaces of the sessions just recovered.
|
||||
*
|
||||
* Deduped by workspace, because sessions in one repo share a single
|
||||
* `.claude/settings.local.json` and the write is otherwise repeated per tab.
|
||||
* Claude mode only (nothing else reads `.claude` hooks), never for remote
|
||||
* sessions (their `workingDir` is a path on ANOTHER host, so writing it here
|
||||
* would scaffold a stray directory locally), and never for a docker case that
|
||||
* opted out of hooks.
|
||||
*
|
||||
* Failures are swallowed per workspace: `ensureCodemanHooks` already refuses
|
||||
* unsafe targets with a warning, and a workspace we cannot write to must not
|
||||
* stop the rest of recovery.
|
||||
*
|
||||
* Skipped entirely when `workspaceHooksEnabled` is OFF: that setting exists so a
|
||||
* user can keep Codeman out of their repos, and a boot-time sweep is the last
|
||||
* place that should ignore it.
|
||||
*/
|
||||
private async ensureHooksForRecoveredWorkspaces(): Promise<void> {
|
||||
if (!(await this.getWorkspaceHooksEnabled())) return;
|
||||
const workspaces = new Set<string>();
|
||||
for (const session of this.sessions.values()) {
|
||||
if (session.mode !== 'claude' || session.remote) continue;
|
||||
if (session.docker && !session.docker.hooksEnabled) continue;
|
||||
if (session.workingDir) workspaces.add(session.workingDir);
|
||||
}
|
||||
for (const workspace of workspaces) {
|
||||
await ensureCodemanHooks(workspace).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* COD-108 — handle a `remoteSessionDropped` emit from the watcher: reattach
|
||||
* the dropped remote session and report the outcome back to the watcher so it
|
||||
|
||||
@@ -224,11 +224,6 @@ export function createSessionListeners(session: Session, deps: SessionListenerDe
|
||||
// re-capture instead).
|
||||
approvalInbox.resolveForSession(session.id, 'resolved_in_terminal', ['idle']);
|
||||
deps.broadcast(SseEvent.SessionWorking, { id: session.id });
|
||||
// Full state ride-along: the home screens sort the running group on
|
||||
// lastSubmitAt, and without this the browser keeps the stamp it loaded
|
||||
// with (a turn started after page load ranks by the PREVIOUS turn's
|
||||
// Enter). Debounced, so working-signal flaps cost one broadcast.
|
||||
deps.broadcastSessionStateDebounced(session.id);
|
||||
const tracker = deps.getRunSummaryTracker(session.id);
|
||||
if (tracker) {
|
||||
tracker.recordWorking();
|
||||
|
||||
+19
-48
@@ -2,11 +2,11 @@
|
||||
//
|
||||
// The desktop home screen's tab column (src/web/public/home-sessions.js) fills
|
||||
// the welcome overlay's left gutter. Two things about it can silently go wrong
|
||||
// and are pinned here: the row ORDER (shared with the phone overview via
|
||||
// CodemanSessionOrder, with the number badge still carrying the TAB index so
|
||||
// Alt+N keeps working), and the WIDTH GATE, which lives in two places at once —
|
||||
// the JS constant and a CSS media query — because the column is absolutely
|
||||
// positioned and would overlap the search panel in a narrow window.
|
||||
// and are pinned here: the row ORDER (it mirrors the tab strip, unlike the phone
|
||||
// overview which sorts by urgency, and the number badges are only correct if it
|
||||
// does), and the WIDTH GATE, which lives in two places at once — the JS constant
|
||||
// and a CSS media query — because the column is absolutely positioned and would
|
||||
// overlap the search panel in a narrow window.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
@@ -35,10 +35,9 @@ function fakeElement(): any {
|
||||
|
||||
/**
|
||||
* home-sessions.js reuses `_mobileOverviewState` / `_mobileOverviewCaseFor` /
|
||||
* `shouldUseMobileOverview` from mobile-overview.js and the row comparator from
|
||||
* constants.js, so all three files run in the same context, which is also the
|
||||
* point: if that reuse ever breaks, these tests stop loading rather than
|
||||
* quietly testing a divergent copy.
|
||||
* `shouldUseMobileOverview` from mobile-overview.js, so both files run in the
|
||||
* same context — which is also the point: if that reuse ever breaks, these
|
||||
* tests stop loading rather than quietly testing a divergent copy.
|
||||
*/
|
||||
function loadHomeSessionsApp(overrides: Record<string, any> = {}, innerWidth = 1512) {
|
||||
const CodemanApp = function CodemanApp(this: any) {};
|
||||
@@ -53,7 +52,7 @@ function loadHomeSessionsApp(overrides: Record<string, any> = {}, innerWidth = 1
|
||||
},
|
||||
MobileDetection: { getDeviceType: () => (innerWidth < 430 ? 'mobile' : 'desktop') },
|
||||
});
|
||||
for (const file of ['constants.js', 'mobile-overview.js', 'home-sessions.js']) {
|
||||
for (const file of ['mobile-overview.js', 'home-sessions.js']) {
|
||||
vm.runInContext(readFileSync(resolve(PUBLIC, file), 'utf8'), context, { filename: file });
|
||||
}
|
||||
|
||||
@@ -77,9 +76,9 @@ function sessionMap(list: Array<Record<string, any>>) {
|
||||
}
|
||||
|
||||
describe('home sessions column: model', () => {
|
||||
it('hoists a session blocked on you, and keeps its badge on the TAB index', () => {
|
||||
// The badge names the Alt+N shortcut, so a sorted rail shows 2,1,3 rather
|
||||
// than renumbering itself 1,2,3 and lying about which key selects what.
|
||||
it('lists rows in TAB order, not by urgency, so the number badges match Alt+1..9', () => {
|
||||
// The phone overview would hoist 'needy' to the top; this surface must not,
|
||||
// because its badges are the Alt+N indices.
|
||||
const app = loadHomeSessionsApp({
|
||||
sessions: sessionMap([{ id: 'first' }, { id: 'needy' }, { id: 'third' }]),
|
||||
sessionOrder: ['first', 'needy', 'third'],
|
||||
@@ -88,34 +87,10 @@ describe('home sessions column: model', () => {
|
||||
});
|
||||
|
||||
const rows = app.buildHomeSessionRows();
|
||||
expect(rows.map((r: any) => r.id)).toEqual(['needy', 'first', 'third']);
|
||||
expect(rows.map((r: any) => r.orderIndex)).toEqual([1, 0, 2]);
|
||||
expect(rows[0].state).toBe('needs');
|
||||
expect(rows[0].pill).toBe('needs you');
|
||||
});
|
||||
|
||||
it('orders running sessions longest-turn-first and quiet ones most-recent-first', () => {
|
||||
// The same rule the phone overview follows, and the reason the rail exists:
|
||||
// what is running longest is what is most likely to be done or stuck, and
|
||||
// once nothing is running the session that just stopped is the one you came
|
||||
// back for.
|
||||
const app = loadHomeSessionsApp({
|
||||
sessions: sessionMap([
|
||||
{ id: 'young-turn', status: 'busy', lastSubmitAt: 9_000, lastActivityAt: 10_000 },
|
||||
{ id: 'old-turn', status: 'busy', lastSubmitAt: 1_000, lastActivityAt: 10_000 },
|
||||
{ id: 'stale-idle', status: 'idle', lastActivityAt: 2_000 },
|
||||
{ id: 'fresh-idle', status: 'idle', lastActivityAt: 8_000 },
|
||||
]),
|
||||
sessionOrder: ['young-turn', 'old-turn', 'stale-idle', 'fresh-idle'],
|
||||
cases: CASES,
|
||||
});
|
||||
|
||||
expect(app.buildHomeSessionRows().map((r: any) => r.id)).toEqual([
|
||||
'old-turn',
|
||||
'young-turn',
|
||||
'fresh-idle',
|
||||
'stale-idle',
|
||||
]);
|
||||
expect(rows.map((r: any) => r.id)).toEqual(['first', 'needy', 'third']);
|
||||
expect(rows.map((r: any) => r.index)).toEqual([0, 1, 2]);
|
||||
expect(rows[1].state).toBe('needs');
|
||||
expect(rows[1].pill).toBe('needs you');
|
||||
});
|
||||
|
||||
it('shows a session that is not in the order list yet', () => {
|
||||
@@ -142,13 +117,11 @@ describe('home sessions column: model', () => {
|
||||
cases: CASES,
|
||||
});
|
||||
|
||||
// Unstamped rows fall back to the tab order inside a state, so this reads
|
||||
// as the state ranking alone: an errored session is blocked on you.
|
||||
expect(app.buildHomeSessionRows().map((r: any) => [r.state, r.pill])).toEqual([
|
||||
['error', 'error'],
|
||||
['working', 'working'],
|
||||
['idle', 'idle'],
|
||||
['done', 'done'],
|
||||
['error', 'error'],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -263,10 +236,8 @@ describe('home sessions column: wiring', () => {
|
||||
expect(aside).toBeGreaterThan(overlayStart);
|
||||
expect(aside).toBeLessThan(content);
|
||||
// Load order: the module reuses prototype methods installed by
|
||||
// mobile-overview.js and the comparator installed by constants.js. Compare
|
||||
// the <script> tags, not any mention: both files are named in explanatory
|
||||
// comments earlier in the document.
|
||||
// mobile-overview.js. Compare the <script> tags, not any mention: both
|
||||
// files are named in explanatory comments earlier in the document.
|
||||
expect(html.indexOf('src="home-sessions.js"')).toBeGreaterThan(html.indexOf('src="mobile-overview.js"'));
|
||||
expect(html.indexOf('src="mobile-overview.js"')).toBeGreaterThan(html.indexOf('src="constants.js"'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -42,12 +42,9 @@ function loadOverviewApp(overrides: Record<string, any> = {}) {
|
||||
},
|
||||
MobileDetection: { getDeviceType: () => 'mobile' },
|
||||
});
|
||||
// constants.js first: it installs the row comparator (window.CodemanSessionOrder)
|
||||
// that buildMobileOverviewModel() sorts every section with, shared with the
|
||||
// desktop rail so the two home screens cannot order the same list differently.
|
||||
for (const file of ['constants.js', 'mobile-overview.js']) {
|
||||
vm.runInContext(readFileSync(resolve(PUBLIC, file), 'utf8'), context, { filename: file });
|
||||
}
|
||||
vm.runInContext(readFileSync(resolve(PUBLIC, 'mobile-overview.js'), 'utf8'), context, {
|
||||
filename: 'mobile-overview.js',
|
||||
});
|
||||
|
||||
const app = new (CodemanApp as any)();
|
||||
app.getSessionName = (session: any) => session.name || session.workingDir?.split('/').pop() || session.id.slice(0, 8);
|
||||
@@ -126,7 +123,7 @@ describe('mobile overview model', () => {
|
||||
expect(model.sessionCount).toBe(4);
|
||||
});
|
||||
|
||||
it('keeps the user tab order as the tiebreak when nothing is stamped', () => {
|
||||
it('keeps the user tab order as the tiebreak inside a section', () => {
|
||||
const app = loadOverviewApp();
|
||||
const model = app.buildMobileOverviewModel({
|
||||
sessions: [session({ id: 'first' }), session({ id: 'second' }), session({ id: 'third' })],
|
||||
@@ -137,42 +134,6 @@ describe('mobile overview model', () => {
|
||||
expect(model.current.map((r: any) => r.id)).toEqual(['third', 'first', 'second']);
|
||||
});
|
||||
|
||||
it('sorts running sessions longest-turn-first and quiet ones most-recent-first', () => {
|
||||
// A working pane repaints about once a second, so its last-activity stamp
|
||||
// is always "now": the running group has to key off the pane's last Enter
|
||||
// instead, or every turn ranks as freshly started.
|
||||
const app = loadOverviewApp();
|
||||
const model = app.buildMobileOverviewModel({
|
||||
sessions: [
|
||||
session({ id: 'quiet-old', status: 'idle', lastActivityAt: 2_000 }),
|
||||
session({ id: 'turn-young', status: 'busy', lastSubmitAt: 9_000, lastActivityAt: 10_000 }),
|
||||
session({ id: 'quiet-new', status: 'idle', lastActivityAt: 8_000 }),
|
||||
session({ id: 'turn-old', status: 'busy', lastSubmitAt: 1_000, lastActivityAt: 10_000 }),
|
||||
],
|
||||
cases: CASES,
|
||||
sessionOrder: ['quiet-old', 'turn-young', 'quiet-new', 'turn-old'],
|
||||
});
|
||||
|
||||
expect(model.current.map((r: any) => r.id)).toEqual(['turn-old', 'turn-young', 'quiet-new', 'quiet-old']);
|
||||
});
|
||||
|
||||
it('puts the longest-blocked session at the top of NEEDS YOU', () => {
|
||||
const app = loadOverviewApp();
|
||||
const model = app.buildMobileOverviewModel({
|
||||
sessions: [
|
||||
session({ id: 'just-asked', lastActivityAt: 9_000 }),
|
||||
session({ id: 'starving', lastActivityAt: 1_000 }),
|
||||
],
|
||||
cases: CASES,
|
||||
pendingHooks: new Map([
|
||||
['just-asked', new Set(['permission_prompt'])],
|
||||
['starving', new Set(['permission_prompt'])],
|
||||
]),
|
||||
});
|
||||
|
||||
expect(model.needsYou.map((r: any) => r.id)).toEqual(['starving', 'just-asked']);
|
||||
});
|
||||
|
||||
it('matches a session started in a subdirectory to its case (longest prefix)', () => {
|
||||
const app = loadOverviewApp();
|
||||
const model = app.buildMobileOverviewModel({
|
||||
|
||||
@@ -19,6 +19,7 @@ export function createMockRouteContext(options?: {
|
||||
sessionId?: string;
|
||||
agentSkillEnabled?: boolean;
|
||||
claudeVoiceEnabled?: boolean;
|
||||
workspaceHooksEnabled?: boolean;
|
||||
}) {
|
||||
const sessionId = options?.sessionId ?? 'test-session-1';
|
||||
const session = createMockSession(sessionId);
|
||||
@@ -96,6 +97,9 @@ export function createMockRouteContext(options?: {
|
||||
getAgentSkillEnabled: vi.fn(async () => options?.agentSkillEnabled ?? false),
|
||||
// Default OFF mirrors the shipped setting: no test opens a voice relay by accident.
|
||||
getClaudeVoiceEnabled: vi.fn(async () => options?.claudeVoiceEnabled ?? false),
|
||||
// Default ON mirrors the shipped setting, so a route test sees what a user sees.
|
||||
// Writes land in the test's temp working dir, never in a real repo.
|
||||
getWorkspaceHooksEnabled: vi.fn(async () => options?.workspaceHooksEnabled ?? true),
|
||||
getDefaultClaudeMdPath: vi.fn(async () => undefined),
|
||||
getLightState: vi.fn(() => ({ sessions: [], status: 'ok' })),
|
||||
getLightSessionsState: vi.fn(() => {
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* @fileoverview Hooks are installed into the workspace a claude session starts in.
|
||||
*
|
||||
* Regression cover for the 2026-08-15 report: a session in a LINKED case (the user's
|
||||
* own repo, where most sessions live) ran with no hooks block at all, because
|
||||
* `writeHooksConfig` only fires when Codeman CREATES a case directory and the old
|
||||
* self-heal call deliberately never ADDED one. The visible symptom was an
|
||||
* AskUserQuestion dialog blocking the pane while the tab and the phone overview both
|
||||
* showed a calm `idle` — no hook event, so no pending-hook state, so no alert.
|
||||
*
|
||||
* Asserts bytes on disk (the real `ensureCodemanHooks`), not a spy call.
|
||||
* Uses app.inject(), so no real HTTP port is needed.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { mkdtemp, rm, readFile, mkdir, writeFile } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createMockRouteContext } from '../mocks/index.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
import { generateHooksConfig } from '../../src/hooks-config.js';
|
||||
|
||||
interface HooksFile {
|
||||
hooks?: Record<string, Array<{ matcher?: string; hooks?: Array<{ command?: string }> }>>;
|
||||
permissions?: unknown;
|
||||
model?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* A faithful PRE-SECRET Codeman hooks block (what a case created before COD-54
|
||||
* contains): it targets /api/hook-event, so it is recognisably ours, but carries
|
||||
* no X-Codeman-Hook-Secret header and no -k. Used to prove the self-heal still
|
||||
* runs with the setting OFF.
|
||||
*/
|
||||
function staleCodemanHooks() {
|
||||
return {
|
||||
Stop: [
|
||||
{
|
||||
matcher: '',
|
||||
hooks: [
|
||||
{
|
||||
type: 'command',
|
||||
command:
|
||||
"HOOK_DATA=$(cat 2>/dev/null || echo '{}'); " +
|
||||
'printf \'{"event":"stop","sessionId":"%s","data":%s}\' "$CODEMAN_SESSION_ID" "$HOOK_DATA" | ' +
|
||||
'curl -s -X POST "$CODEMAN_API_URL/api/hook-event" -H \'Content-Type: application/json\' --data @- 2>/dev/null || true',
|
||||
timeout: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe('POST /api/sessions workspace hooks', () => {
|
||||
let app: FastifyInstance;
|
||||
let workingDir: string;
|
||||
|
||||
const settingsPath = () => join(workingDir, '.claude', 'settings.local.json');
|
||||
const readSettings = async (): Promise<HooksFile> => JSON.parse(await readFile(settingsPath(), 'utf-8'));
|
||||
|
||||
const createSession = (payload: Record<string, unknown>) =>
|
||||
app.inject({ method: 'POST', url: '/api/sessions', payload });
|
||||
|
||||
/** Rebuild the app with the `workspaceHooksEnabled` gate in a given position. */
|
||||
const useApp = async (workspaceHooksEnabled: boolean) => {
|
||||
await app?.close();
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
registerSessionRoutes(app, createMockRouteContext({ workspaceHooksEnabled }));
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
workingDir = await mkdtemp(join(tmpdir(), 'codeman-workspace-hooks-'));
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
registerSessionRoutes(app, createMockRouteContext());
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
await rm(workingDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('installs hooks in a workspace that has none (the linked-case bug)', async () => {
|
||||
const res = await createSession({ name: 'hooks-fresh', mode: 'claude', workingDir });
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
const settings = await readSettings();
|
||||
const matchers = (settings.hooks?.Notification ?? []).map((entry) => entry.matcher);
|
||||
// permission_prompt is the one an AskUserQuestion dialog raises; the
|
||||
// elicitation pair is what CLOSES the resulting Approvals Inbox item.
|
||||
expect(matchers).toEqual(
|
||||
expect.arrayContaining([
|
||||
'idle_prompt',
|
||||
'permission_prompt',
|
||||
'elicitation_dialog',
|
||||
'elicitation_complete',
|
||||
'elicitation_response',
|
||||
])
|
||||
);
|
||||
expect(settings.hooks?.Stop?.length).toBeGreaterThan(0);
|
||||
|
||||
const serialized = JSON.stringify(settings.hooks);
|
||||
// The two shapes that have historically shipped dead hooks: no secret header
|
||||
// (401 once the gate went unconditional) and no -k (exit 60 on HTTPS installs).
|
||||
expect(serialized).toContain('X-Codeman-Hook-Secret');
|
||||
expect(serialized).toContain('curl -sk -X POST');
|
||||
});
|
||||
|
||||
it('merges into a user-owned settings file without disturbing it', async () => {
|
||||
await mkdir(join(workingDir, '.claude'), { recursive: true });
|
||||
const userHook = { matcher: 'Write', hooks: [{ type: 'command', command: './my-formatter.sh' }] };
|
||||
await writeFile(
|
||||
settingsPath(),
|
||||
JSON.stringify({ model: 'opus[1m]', permissions: { allow: ['Read'] }, hooks: { PostToolUse: [userHook] } })
|
||||
);
|
||||
|
||||
expect((await createSession({ name: 'hooks-merge', mode: 'claude', workingDir })).statusCode).toBe(200);
|
||||
|
||||
const settings = await readSettings();
|
||||
expect(settings.model).toBe('opus[1m]');
|
||||
expect(settings.permissions).toEqual({ allow: ['Read'] });
|
||||
expect(JSON.stringify(settings.hooks)).toContain('./my-formatter.sh');
|
||||
expect((settings.hooks?.Notification ?? []).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('leaves a non-claude session alone (only claude reads .claude hooks)', async () => {
|
||||
expect((await createSession({ name: 'hooks-shell', mode: 'shell', workingDir })).statusCode).toBe(200);
|
||||
expect(existsSync(settingsPath())).toBe(false);
|
||||
});
|
||||
|
||||
it('leaves a malformed settings file untouched rather than replacing it', async () => {
|
||||
await mkdir(join(workingDir, '.claude'), { recursive: true });
|
||||
await writeFile(settingsPath(), '{ not json');
|
||||
|
||||
expect((await createSession({ name: 'hooks-malformed', mode: 'claude', workingDir })).statusCode).toBe(200);
|
||||
expect(await readFile(settingsPath(), 'utf-8')).toBe('{ not json');
|
||||
});
|
||||
|
||||
it('adds nothing when workspaceHooksEnabled is OFF', async () => {
|
||||
await useApp(false);
|
||||
|
||||
expect((await createSession({ name: 'hooks-off', mode: 'claude', workingDir })).statusCode).toBe(200);
|
||||
expect(existsSync(settingsPath())).toBe(false);
|
||||
});
|
||||
|
||||
it('still heals a stale Codeman block when workspaceHooksEnabled is OFF', async () => {
|
||||
// The setting turns off ADDING hooks, not the COD-91 self-heal: a pre-secret
|
||||
// block 401s against the now-unconditional hook-secret gate, so a workspace that
|
||||
// already opted in must not be left with hooks that silently fail.
|
||||
await useApp(false);
|
||||
await mkdir(join(workingDir, '.claude'), { recursive: true });
|
||||
await writeFile(settingsPath(), JSON.stringify({ model: 'opus', hooks: staleCodemanHooks() }));
|
||||
|
||||
expect((await createSession({ name: 'hooks-off-stale', mode: 'claude', workingDir })).statusCode).toBe(200);
|
||||
|
||||
const settings = await readSettings();
|
||||
expect(settings.model).toBe('opus');
|
||||
expect(JSON.stringify(settings.hooks)).toContain('X-Codeman-Hook-Secret');
|
||||
});
|
||||
|
||||
it('writes the hooks the generator produces, so the two cannot drift', async () => {
|
||||
expect((await createSession({ name: 'hooks-parity', mode: 'claude', workingDir })).statusCode).toBe(200);
|
||||
|
||||
const written = (await readSettings()).hooks ?? {};
|
||||
expect(Object.keys(written).sort()).toEqual(Object.keys(generateHooksConfig().hooks).sort());
|
||||
});
|
||||
});
|
||||
@@ -1,175 +0,0 @@
|
||||
// Port: none (pure comparator — no browser, no server).
|
||||
//
|
||||
// `CodemanSessionOrder` (src/web/public/constants.js) is the single row order
|
||||
// behind both home screens: the phone overview and the desktop tab rail. It is
|
||||
// the one place the two surfaces can disagree about which session you should
|
||||
// look at next, which is why it is pure and pinned here rather than living
|
||||
// inside either renderer.
|
||||
//
|
||||
// The rule it encodes, and the thing worth protecting: the tiebreak FLIPS
|
||||
// direction halfway down the list. For a state a session is still in, older is
|
||||
// more urgent (blocked longest, running longest). For a state it has stopped
|
||||
// in, newer is more relevant (just finished beats abandoned yesterday).
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
state: string;
|
||||
lastActivityAt?: number;
|
||||
lastSubmitAt?: number;
|
||||
orderIndex?: number;
|
||||
};
|
||||
|
||||
function loadOrderHelper() {
|
||||
const context = vm.createContext({ window: {}, globalThis: {} });
|
||||
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/constants.js'), 'utf8');
|
||||
vm.runInContext(source, context, { filename: 'constants.js' });
|
||||
return (
|
||||
context.window as {
|
||||
CodemanSessionOrder: {
|
||||
RANK: Record<string, number>;
|
||||
anchor: (row: Row) => number;
|
||||
compare: (a: Row, b: Row) => number;
|
||||
sort: (rows: Row[]) => Row[];
|
||||
};
|
||||
}
|
||||
).CodemanSessionOrder;
|
||||
}
|
||||
|
||||
const order = loadOrderHelper();
|
||||
const ids = (rows: Row[]) => order.sort(rows).map((r) => r.id);
|
||||
|
||||
describe('session overview order: state ranking', () => {
|
||||
it('puts everything blocked on a human above everything else', () => {
|
||||
// Red question, then a hard error, then the yellow "waiting for input"
|
||||
// prompt, then work, then whatever has stopped.
|
||||
const rows: Row[] = [
|
||||
{ id: 'done', state: 'done' },
|
||||
{ id: 'idle', state: 'idle' },
|
||||
{ id: 'working', state: 'working' },
|
||||
{ id: 'waiting', state: 'waiting' },
|
||||
{ id: 'error', state: 'error' },
|
||||
{ id: 'needs', state: 'needs' },
|
||||
];
|
||||
expect(ids(rows)).toEqual(['needs', 'error', 'waiting', 'working', 'idle', 'done']);
|
||||
});
|
||||
|
||||
it('sorts an unknown state last instead of dropping it or crashing', () => {
|
||||
// A state added to one renderer and not to the rank map must still render,
|
||||
// just at the bottom — a missing row is a worse failure than a misplaced one.
|
||||
const rows: Row[] = [
|
||||
{ id: 'mystery', state: 'quantum' },
|
||||
{ id: 'done', state: 'done' },
|
||||
];
|
||||
expect(ids(rows)).toEqual(['done', 'mystery']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('session overview order: in-progress states sort oldest first', () => {
|
||||
it('ranks the longest-running turn above a turn that just started', () => {
|
||||
const rows: Row[] = [
|
||||
{ id: 'young', state: 'working', lastSubmitAt: 9_000, lastActivityAt: 10_000 },
|
||||
{ id: 'old', state: 'working', lastSubmitAt: 1_000, lastActivityAt: 10_000 },
|
||||
];
|
||||
expect(ids(rows)).toEqual(['old', 'young']);
|
||||
});
|
||||
|
||||
it('measures a running turn from the last Enter, not the last repaint', () => {
|
||||
// A working pane repaints about once a second, so last-activity is always
|
||||
// "now" and would rank every running turn identically.
|
||||
expect(order.anchor({ id: 'w', state: 'working', lastSubmitAt: 1_000, lastActivityAt: 999_000 })).toBe(1_000);
|
||||
expect(order.anchor({ id: 'i', state: 'idle', lastSubmitAt: 1_000, lastActivityAt: 999_000 })).toBe(999_000);
|
||||
});
|
||||
|
||||
it('falls back to last activity for a working pane that never submitted', () => {
|
||||
// Spawned with its prompt on the command line, or an external CLI whose
|
||||
// Enter never went through Codeman. Its fallback stamp is ~now, so it sits
|
||||
// at the SHORT end of the running group rather than falsely leading it.
|
||||
const rows: Row[] = [
|
||||
{ id: 'no-submit', state: 'working', lastActivityAt: 10_000 },
|
||||
{ id: 'submitted', state: 'working', lastSubmitAt: 1_000, lastActivityAt: 10_000 },
|
||||
];
|
||||
expect(ids(rows)).toEqual(['submitted', 'no-submit']);
|
||||
});
|
||||
|
||||
it('ranks the longest-blocked session above one that just asked', () => {
|
||||
const rows: Row[] = [
|
||||
{ id: 'just-asked', state: 'needs', lastActivityAt: 9_000 },
|
||||
{ id: 'starving', state: 'needs', lastActivityAt: 1_000 },
|
||||
];
|
||||
expect(ids(rows)).toEqual(['starving', 'just-asked']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('session overview order: stopped states sort newest first', () => {
|
||||
it('puts the session that just went quiet above one idle since yesterday', () => {
|
||||
const rows: Row[] = [
|
||||
{ id: 'yesterday', state: 'idle', lastActivityAt: 1_000 },
|
||||
{ id: 'just-now', state: 'idle', lastActivityAt: 9_000 },
|
||||
{ id: 'this-morning', state: 'idle', lastActivityAt: 5_000 },
|
||||
];
|
||||
expect(ids(rows)).toEqual(['just-now', 'this-morning', 'yesterday']);
|
||||
});
|
||||
|
||||
it('applies the same recency rule to finished sessions', () => {
|
||||
const rows: Row[] = [
|
||||
{ id: 'old-exit', state: 'done', lastActivityAt: 1_000 },
|
||||
{ id: 'fresh-exit', state: 'done', lastActivityAt: 9_000 },
|
||||
];
|
||||
expect(ids(rows)).toEqual(['fresh-exit', 'old-exit']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('session overview order: tiebreaks', () => {
|
||||
it('falls back to the tab order when two rows share a stamp', () => {
|
||||
const rows: Row[] = [
|
||||
{ id: 'third', state: 'idle', lastActivityAt: 5_000, orderIndex: 2 },
|
||||
{ id: 'first', state: 'idle', lastActivityAt: 5_000, orderIndex: 0 },
|
||||
];
|
||||
expect(ids(rows)).toEqual(['first', 'third']);
|
||||
});
|
||||
|
||||
it('sorts an unstamped row last within its state, never first', () => {
|
||||
// 0 is "we have no stamp", not "the epoch": treating it as a timestamp
|
||||
// would park a brand-new session at the head of the oldest-first groups.
|
||||
expect(
|
||||
ids([
|
||||
{ id: 'none', state: 'idle', orderIndex: 0 },
|
||||
{ id: 'stamped', state: 'idle', lastActivityAt: 1_000, orderIndex: 1 },
|
||||
])
|
||||
).toEqual(['stamped', 'none']);
|
||||
expect(
|
||||
ids([
|
||||
{ id: 'none', state: 'working', orderIndex: 0 },
|
||||
{ id: 'stamped', state: 'working', lastSubmitAt: 1_000, orderIndex: 1 },
|
||||
])
|
||||
).toEqual(['stamped', 'none']);
|
||||
});
|
||||
|
||||
it('is deterministic: two unstamped rows keep tab order in both directions', () => {
|
||||
const a: Row = { id: 'a', state: 'idle', orderIndex: 0 };
|
||||
const b: Row = { id: 'b', state: 'idle', orderIndex: 1 };
|
||||
expect(order.compare(a, b)).toBeLessThan(0);
|
||||
expect(order.compare(b, a)).toBeGreaterThan(0);
|
||||
expect(order.compare(a, a)).toBe(0);
|
||||
});
|
||||
|
||||
it('copies rather than sorting the caller array in place', () => {
|
||||
// Both renderers hand it a filtered slice of a shared row array; mutating
|
||||
// that would reorder the other surface's list as a side effect.
|
||||
const rows: Row[] = [
|
||||
{ id: 'b', state: 'idle', lastActivityAt: 1_000 },
|
||||
{ id: 'a', state: 'idle', lastActivityAt: 9_000 },
|
||||
];
|
||||
order.sort(rows);
|
||||
expect(rows.map((r) => r.id)).toEqual(['b', 'a']);
|
||||
});
|
||||
|
||||
it('survives junk input rather than throwing inside a render', () => {
|
||||
expect(order.sort(undefined as unknown as Row[])).toEqual([]);
|
||||
expect(order.anchor({} as Row)).toBe(0);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user