chore: version packages

Persist the 'I checked it' state of yellow idle tab alerts across reloads and devices.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer
2026-08-17 00:46:03 +02:00
parent fa8ebe0068
commit f4ba4d2cb1
12 changed files with 232 additions and 14 deletions
+10
View File
@@ -1,5 +1,15 @@
# aicodeman
## 1.19.2
### Patch Changes
- Yellow "waiting for input" tab alerts now stay cleared once you have checked them, on every device.
Viewing a session used to clear its idle alert in that browser's memory only. The server-side approval store still held the prompt, so the next page load seeded the alert straight back and a tab you had already checked went yellow again, while your other devices never heard about the click at all. Opening a session now acknowledges its pending idle prompt server-side (`POST /api/approvals/session/:sessionId/viewed`, a new `acknowledgedAt` field on approval items, broadcast as `approval:updated`), so the clear survives reloads and reaches every connected client.
Acknowledgement is deliberately not resolution: the prompt is still unanswered, so the item stays in the Approvals Inbox, stays answerable, and stays available as Read My Mind context, it just stops arming the tab alert. Permission and question dialogs are never acknowledged this way, since looking at a dialog does not answer it, so the red "needs you" alert survives being viewed. Clicking the tab you are already on now clears the alert as well; that path returned early before, so an alert armed on the active tab could not be cleared by clicking at all.
## 1.19.1
### Patch Changes
+2 -2
View File
@@ -74,7 +74,7 @@ When user says "COM":
CI runs `npm run check:lockfile` on every push/PR, so lockfile drift fails the build even if the `version-packages` script is bypassed.
**Version**: 1.19.1 (must match `package.json`)
**Version**: 1.19.2 (must match `package.json`)
## Project Overview
@@ -210,7 +210,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**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 hooks-config.ts → `ensureCodemanHooks`, an add-only merge that keeps a user's own handlers), from EVERY claude create path — both interactive routes, cron fires, legacy scheduled runs, the plan-orchestrator one-shots — and from `restoreMuxSessions()` for sessions recovered on server start (that boot sweep skips a workspace that no longer exists, so a deleted repo with a surviving tmux session is never resurrected as an empty dir). 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`.
**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). ⚠️ **Viewing a session ACKNOWLEDGES its idle item, it does not resolve it** (`POST /api/approvals/session/:sessionId/viewed` → `acknowledgedAt` → `approval:updated`): the item stays pending (still answerable, still Read My Mind context) and only stops arming the yellow tab alert. That flag is what makes the clear durable, since the view-clears-idle rule used to live in one browser's memory and `seedApprovals()` re-armed the alert on the next reload while other devices never heard about it at all; the local half is `markIdleAlertSeen()` (app.js), called from BOTH `selectSession` paths, including the already-active early return, where a click could otherwise never clear the alert. Idle-only by construction (`acknowledge()` defaults to `['idle']`): looking at a permission/question dialog does not answer it. 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`.
**Read My Mind intent profiles** (phase 1 of `docs/readmymind-plan.md`; `readMyMindEnabled`, SYNCED, default OFF): per-CASE profiles (user-stated `goals` + the user's recent real prompts), keyed by owner + realpath(workingDir) so they survive `/clear`/respawns and multi-user scoping is structural. Capture rides the transcript (`transcript:user_prompt` from `transcript-watcher.ts`), NOT the input paths: `POST /input` sees only programmatic prompts and the WS channel is raw keystrokes. The listener lives inside `startTranscriptWatcher()`'s `if (!watcher)` block (outside it would duplicate per hook event) and is claude-only + gated on the setting per event. Store: `src/intent-store.ts` singleton, `intents.json` written 0600 tmp+rename (prompts can contain secrets; never fed to `/api/search`). Endpoints: GET/PUT/DELETE `/api/sessions/:id/intent` + POST `/api/sessions/:id/readmymind` (`readmymind-routes.ts`, ownership via `findSessionOrFail` WITH `req`; registrations stay the bare `app.<method>('path')` shape, the endpoints.md drift scanner cannot see generics). **Phase 2 (predictor + 🧠 button)**: `readmymind-context.ts` is the PURE budgeted assembler (9 ranked sources, drop order siblings→away→workspace→tools, sections 1-4 truncate only); IO lives in `readmymind-collectors.ts` (transcript TAIL read — the live watcher keeps only a 500-char snippet — + git signals, skipped for remote-SSH cases) and the route; `readmymind-predictor.ts` reuses the AiCheckerBase spawn mechanics standalone (verdict-shaped base vs freeform JSON) as a mutable singleton routes call and tests stub. Claude-mode only (400), one in flight per session (409 CONFLICT), model = `readMyMindModel` setting defaulting to `AI_CHECK_MODEL` (opus, decided). Frontend `readmymind-ui.js`: header 🧠 marker-hidden (`btn-readmymind--hidden`) until the setting is ON; phones hide it in mobile.css and get a keyboard-accessory 🧠 key instead (ships in BOTH bar templates, revealed by the `rmm-enabled` class on the BAR element — setMode() rebuilds button innerHTML, so per-key state would be wiped; synced at init + every `applyHeaderVisibilitySettings()`). Alternate suggestions render as tappable rows that swap into the editable field without losing edits; Rethink rejects the whole shown set and carries the optional steer note (`#readMyMindSteer`, sent as `steer`, shown in ready + empty-result phases, cleared on each open). Suggestions render via value/`textContent` ONLY and Send/Insert go through `POST /input` (server-side, so the sendEnterKey/local-echo trap does not apply) — nothing auto-sends, ever. User guide: `docs/readmymind.md`.
+14 -4
View File
@@ -442,9 +442,11 @@ Design: [`approvals-inbox-plan.md`](approvals-inbox-plan.md).
- `GET /api/v1/approvals` → `{ approvals: ApprovalItem[] }`, oldest first,
ownership-scoped in multi-user mode. `ApprovalItem`: `{ id, sessionId,
sessionName, kind: 'permission'|'question'|'idle', createdAt, toolName?,
toolSummary?, message?, cwd?, context?, options?: {n, label}[] }`. `context`
is the ANSI-stripped visible pane frame; `options` is present only when the
dialog's numbered choices parsed confidently.
toolSummary?, message?, cwd?, context?, options?: {n, label}[],
acknowledgedAt? }`. `context` is the ANSI-stripped visible pane frame;
`options` is present only when the dialog's numbered choices parsed
confidently; `acknowledgedAt` marks an item a human has already looked at
(see `/viewed` below) and tells clients not to re-arm its tab alert.
- `POST /api/v1/approvals/:id/answer` with `{ action: 'approve' }` (sends the
digit `1`), `{ action: 'deny' }` (sends Esc), `{ action: 'option', option: n }`
(sends the digit; accepted only when `n` is among the item's parsed
@@ -453,9 +455,17 @@ Design: [`approvals-inbox-plan.md`](approvals-inbox-plan.md).
`409 CONFLICT` when the dialog left the screen or another actor answered
first, `422 OPERATION_FAILED` when the session refused input.
- `POST /api/v1/approvals/:id/dismiss` removes the item without keystrokes.
- `POST /api/v1/approvals/session/:sessionId/viewed` → `{ sessionId,
acknowledged: itemId | null }`. Marks the session's pending **idle** item as
seen by a human (the web UI calls it when you open the session's tab): the
item stays pending and answerable, but stops arming the yellow tab alert on
every client, including after a reload. Permission/question items are never
acknowledged this way, since looking at a dialog does not answer it. `404`
for an unknown or inaccessible session; acknowledging twice is a no-op
(`acknowledged: null`).
SSE events: `approval:pending` (full item), `approval:updated` (context/options
re-captured), `approval:resolved` (`{ id, sessionId, kind, resolution }` with
re-captured, or the item acknowledged), `approval:resolved` (`{ id, sessionId, kind, resolution }` with
`resolution` one of `answered | resolved_in_terminal | superseded |
session_ended | dismissed | expired`).
+2 -1
View File
@@ -68,6 +68,7 @@ Normal authed API (NOT the hook-secret bypass), `ApiResponse` envelope, Zod sche
- `text` → `idle` items only: single line, embedded newlines stripped, sent as `text\r` (the `\r` discipline from CLAUDE.md).
- Guards: item still pending (404 otherwise), session exists + ownership via `findSessionOrFail`, session mode installs hooks. **Answer-time re-capture**: for items whose frame parsed options, the pane is re-captured before sending; if the dialog no longer parses, the item resolves and the answer is refused with 409 (the keystroke would land in whatever now has focus). Marks `answered` BEFORE the write so a double-tap cannot double-send; rolls back to pending if the write fails.
- `POST /api/approvals/:id/dismiss` → remove without keystrokes.
- `POST /api/approvals/session/:sessionId/viewed` → acknowledge the session's pending **idle** item (`acknowledgedAt`, emitted as `approval:updated`). Added after the owner reported that a yellow tab clicked and checked went yellow again on reload: the view-clears-idle rule lived in one browser's memory, so the seed re-armed it and other devices never saw the clear. Acknowledgement is deliberately **not** resolution (the prompt is still unanswered, so it stays in the inbox and stays available as Read My Mind context), and deliberately **idle-only** (looking at a permission/question dialog does not answer it, so the red alert survives being viewed).
### SSE
@@ -84,7 +85,7 @@ Normal authed API (NOT the hook-secret bypass), `ApiResponse` envelope, Zod sche
New module `approvals-ui.js` (@loadorder 11.2, after panels-ui.js), prettier-formatted (not added to `.prettierignore`).
- **Seed on connect**: `GET /api/approvals` on init and SSE reconnect; each pending item re-feeds `setPendingHook(...)` so tab alerts and the phone overview survive reload (fixes problem 2 with zero changes to the alert state machine).
- **Seed on connect**: `GET /api/approvals` on init and SSE reconnect; each pending item re-feeds `setPendingHook(...)` so tab alerts and the phone overview survive reload (fixes problem 2 with zero changes to the alert state machine). Items carrying `acknowledgedAt` are skipped, and `markIdleAlertSeen()` (app.js) is what sets it: viewing a session clears its yellow locally and POSTs `.../viewed`, so "I checked it" survives the reload and reaches the user's other devices through `approval:updated`.
- **Desktop**: header bell `btn-approvals` with count badge. Ships default-hidden via marker class `btn-approvals--hidden` (same policy as the attachments button, so `test/mobile-header-buttons-policy.test.ts` excludes it from the default-visible enumeration); JS shows it only while count > 0. Click toggles a drawer of cards: session name + kind, tool/message summary, mono context block, buttons rendered from parsed options (else Approve/Deny), plus Dismiss and Open session. Esc closes; existing z-index layers respected.
- **Phone**: header button stays hidden (`mobile.css`); the phone surface is the overview's NEEDS YOU section, whose rows gain inline ✓/✗ buttons for permission items (tap-through to the session remains the row's main action). Toolbar classes/status language rules from the mobile-overview section of CLAUDE.md apply.
- **i18n**: new strings registered in i18n.js (en + zh-CN); status words carry `data-i18n-skip` where they would collide (mirroring the overview pills).
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "aicodeman",
"version": "1.19.1",
"version": "1.19.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "aicodeman",
"version": "1.19.1",
"version": "1.19.2",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "aicodeman",
"version": "1.19.1",
"version": "1.19.2",
"description": "Mission control for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
"type": "module",
"main": "dist/index.js",
+29
View File
@@ -19,6 +19,8 @@
* - Answer flow is take-then-write: `take()` removes the item BEFORE keystrokes
* are sent so a double-tap cannot double-send; `restore()` re-inserts on a
* failed write unless a newer prompt arrived meanwhile.
* - Acknowledgement (`acknowledge()`, idle items only) is NOT resolution: the
* item stays pending, it just stops arming the tab alert on every client.
*
* @dependencies utils (stripAnsi)
* @consumedby web/routes/hook-event-routes (notePrompt/resolve), web/routes/approval-routes,
@@ -61,6 +63,14 @@ export interface ApprovalItem {
cwd?: string;
/** ANSI-stripped tail of the visible pane frame at capture time. */
context?: string;
/**
* Set when a human looked at the session (the web UI selecting its tab). The
* item stays PENDING and answerable, only its tab alert is spent: clients
* skip re-arming the alert for an acknowledged item when they seed from
* `GET /api/approvals`, which is what makes "I checked it" survive a reload
* and reach the user's other devices. See `acknowledge()`.
*/
acknowledgedAt?: number;
/**
* Present only when the frame parsed confidently. Gates which digits the
* answer endpoint accepts; absent → only approve('1')/deny(Esc) are allowed.
@@ -306,6 +316,25 @@ export class ApprovalInbox {
this.onPending?.(item);
}
/**
* Mark a session's pending item as SEEN by a human, and return it (undefined
* when there is nothing to acknowledge or it is already acknowledged). The
* item is NOT resolved: an idle prompt a human glanced at is still unanswered,
* so it stays in the inbox, stays answerable, and stays available as Read My
* Mind context. Only the tab alert it armed is spent.
*
* ⚠️ `kinds` defaults to `['idle']` and callers must keep it that narrow:
* looking at a permission/question dialog does not answer it, so the red
* "needs you" alert has to survive being viewed.
*/
acknowledge(sessionId: string, kinds: ApprovalKind[] = ['idle']): ApprovalItem | undefined {
const item = this.getForSession(sessionId);
if (!item || !kinds.includes(item.kind) || item.acknowledgedAt) return undefined;
item.acknowledgedAt = Date.now();
if (!this.stopped) this.onUpdated?.(item);
return item;
}
/** Remove an item without keystrokes (user chose Dismiss). */
dismiss(id: string): boolean {
const item = this.getById(id);
+31 -3
View File
@@ -845,6 +845,24 @@ class CodemanApp {
this.updateTabAlertFromHooks(sessionId);
}
/**
* "I looked at this session": spend its pending IDLE tab alert (the yellow
* one), locally AND server-side. The clear used to live only in this tab's
* memory, so `seedApprovals()` re-armed it from `GET /api/approvals` on the
* next reload (a tab you had already checked went yellow again), and the
* user's other devices never heard about it. The server marks the approval
* item acknowledged (it stays pending and answerable) and broadcasts
* `approval:updated`, which is what clears the alert everywhere else.
*
* ⚠️ Idle only: action alerts (permission/question) mean an unanswered dialog
* is on screen, and looking at one does not answer it.
*/
markIdleAlertSeen(sessionId) {
if (!this.pendingHooks.get(sessionId)?.has('idle_prompt')) return;
this.clearPendingHooks(sessionId, 'idle_prompt');
this.acknowledgeIdleApprovalOnView?.(sessionId);
}
updateTabAlertFromHooks(sessionId) {
const hooks = this.pendingHooks.get(sessionId);
if (!hooks || hooks.size === 0) {
@@ -5144,7 +5162,15 @@ class CodemanApp {
if (this._raiseDetached(sessionId)) return;
}
const forceReload = options?.forceReload === true;
if (this.activeSessionId === sessionId && !forceReload) return;
if (this.activeSessionId === sessionId && !forceReload) {
// Clicking the tab you are already on is still "I checked it". The alert
// can be armed on the ACTIVE tab (a live idle_prompt fires regardless of
// which tab is showing, and so does the reload seed), and every other
// clear path runs on the switch this early return skips, leaving a
// yellow tab that no click could clear.
this.markIdleAlertSeen(sessionId);
return;
}
if (this.activeSessionId === sessionId && forceReload) {
this.terminalBufferCache?.delete(sessionId);
this._xtermSnapshots?.delete(sessionId);
@@ -5200,8 +5226,10 @@ class CodemanApp {
// switch when that option is on. Transform/opacity/clip-path only, xterm's
// FitAddon reads the untransformed layout box, so this cannot reach the PTY.
this.playTerminalEntrance?.(sessionId);
// Clear idle hooks on view, but keep action hooks until user interacts
this.clearPendingHooks(sessionId, 'idle_prompt');
// Clear idle hooks on view, but keep action hooks until user interacts.
// Also acknowledged server-side, so the yellow does not come back on the
// next reload and the user's other devices clear it too.
this.markIdleAlertSeen(sessionId);
// Instant active-class toggle (no 100ms debounce), then schedule full render for badges/status
this._updateActiveTabImmediate(sessionId);
// Handheld: the session drawer overlays the terminal, so slide it away now
+30 -1
View File
@@ -50,6 +50,11 @@ Object.assign(CodemanApp.prototype, {
const inboxOn = this.approvalsInboxEnabled();
for (const item of (data && data.approvals) || []) {
if (inboxOn) this.approvals.set(item.id, item);
// ⚠ Skip items a human already looked at (`acknowledgedAt`, set by
// markIdleAlertSeen → POST .../viewed). Re-arming those is exactly the
// bug this flag exists for: clicking a yellow tab cleared the alert in
// this tab's memory only, so the next reload seeded it right back.
if (item.acknowledgedAt) continue;
// Re-arm the tab alert state machine (idempotent set-add).
this.setPendingHook(item.sessionId, approvalKindToHook(item.kind));
}
@@ -70,7 +75,14 @@ Object.assign(CodemanApp.prototype, {
},
_onApprovalUpdated(item) {
if (!item || !item.id || !this.approvals?.has(item.id)) return;
if (!item || !item.id) return;
// Acknowledged elsewhere (this user opened the session on another device):
// spend the tab alert UNCONDITIONALLY, for the same reason
// _onApprovalResolved does: with the inbox setting OFF the item was never
// stored in `this.approvals`, yet seedApprovals armed its alert, so gating
// this on a map hit would strand a yellow tab on every other device.
if (item.acknowledgedAt) this.clearPendingHooks(item.sessionId, approvalKindToHook(item.kind));
if (!this.approvals?.has(item.id)) return;
this.approvals.set(item.id, item);
this.renderApprovals();
},
@@ -89,6 +101,23 @@ Object.assign(CodemanApp.prototype, {
// ─── Actions ─────────────────────────────────────────────────
/**
* Tell the server the session's pending IDLE prompt has been looked at, so
* the yellow tab alert stays gone: `seedApprovals()` skips acknowledged
* items on the next reload, and the resulting `approval:updated` broadcast
* clears the alert on the user's other devices. Called by markIdleAlertSeen
* (app.js), which owns the local half of the clear.
*
* Fire-and-forget: the alert is already down locally, `_apiJson` swallows
* failures, and the worst case of a lost POST is today's behavior (yellow
* returns after a reload). Runs regardless of `approvalsInboxEnabled`,
* since the tab alert predates the inbox and is not gated on it.
*/
acknowledgeIdleApprovalOnView(sessionId) {
if (!sessionId) return;
this._apiJson(`/api/approvals/session/${encodeURIComponent(sessionId)}/viewed`, { method: 'POST' });
},
async answerApproval(id, action, option) {
const body = option !== undefined ? { action, option } : { action };
const data = await this._apiJson(`/api/approvals/${encodeURIComponent(id)}/answer`, {
+20
View File
@@ -7,6 +7,8 @@
* - `POST /api/approvals/:id/answer`: answer in place by sending the
* corresponding keystrokes to the session (digit / Esc / idle-prompt text)
* - `POST /api/approvals/:id/dismiss`: drop the item without keystrokes
* - `POST /api/approvals/session/:sessionId/viewed`: mark the session's pending
* IDLE prompt as seen (tab alert spent, item still pending)
*
* Normal authed API surface (NOT the localhost hook-secret bypass). Answering
* is take-then-write: the item is removed BEFORE keystrokes go out so a
@@ -113,6 +115,24 @@ export function registerApprovalRoutes(app: FastifyInstance, ctx: SessionPort):
return { success: true, data: { id: item.id, sessionId: item.sessionId, action: answer.action } };
});
/**
* "A human is looking at this session": acknowledge its pending IDLE prompt.
* The yellow tab alert used to be cleared in the browser's memory only, so
* `GET /api/approvals` re-armed it on the next reload (a tab you had already
* checked went yellow again) and the user's other devices never heard about
* it at all. The item is NOT resolved, only marked seen; the
* `approval:updated` broadcast is what clears the alert everywhere else.
*
* ⚠️ Idle only, by construction (`acknowledge()` defaults to `['idle']`):
* viewing a permission/question dialog does not answer it, so the red alert
* must survive being viewed.
*/
app.post<{ Params: { sessionId: string } }>('/api/approvals/session/:sessionId/viewed', async (req) => {
const session = findSessionOrFail(ctx, req.params.sessionId, req);
const item = approvalInbox.acknowledge(session.id);
return { success: true, data: { sessionId: session.id, acknowledged: item?.id ?? null } };
});
app.post<{ Params: { id: string } }>('/api/approvals/:id/dismiss', async (req) => {
const item = approvalInbox.getById(req.params.id);
if (!item) {
+38
View File
@@ -216,6 +216,44 @@ describe('ApprovalInbox', () => {
expect(inbox.getForSession('s1')?.id).toBe(newer.id);
});
it('acknowledge marks an idle item seen without resolving it, and emits onUpdated once', () => {
const { updated, resolved } = collect(inbox);
const item = inbox.notePrompt({ sessionId: 's1', sessionName: 'w1', kind: 'idle' });
const acked = inbox.acknowledge('s1');
expect(acked?.id).toBe(item.id);
expect(acked?.acknowledgedAt).toBeGreaterThan(0);
// Still pending and still answerable: the human looked, they did not answer.
expect(inbox.getById(item.id)?.acknowledgedAt).toBeGreaterThan(0);
expect(inbox.listPending()).toHaveLength(1);
expect(resolved).toHaveLength(0);
expect(updated).toEqual([expect.objectContaining({ id: item.id })]);
// Idempotent: a second view does not re-broadcast.
expect(inbox.acknowledge('s1')).toBeUndefined();
expect(updated).toHaveLength(1);
});
it('acknowledge never touches a permission/question item (viewing is not answering)', () => {
const { updated } = collect(inbox);
const permission = inbox.notePrompt({ sessionId: 's1', sessionName: 'w1', kind: 'permission' });
expect(inbox.acknowledge('s1')).toBeUndefined();
expect(inbox.getById(permission.id)?.acknowledgedAt).toBeUndefined();
const question = inbox.notePrompt({ sessionId: 's2', sessionName: 'w2', kind: 'question' });
expect(inbox.acknowledge('s2')).toBeUndefined();
expect(inbox.getById(question.id)?.acknowledgedAt).toBeUndefined();
expect(updated).toHaveLength(0);
expect(inbox.acknowledge('nope')).toBeUndefined();
});
it('a new prompt after an acknowledgement arms the alert again', () => {
inbox.notePrompt({ sessionId: 's1', sessionName: 'w1', kind: 'idle' });
inbox.acknowledge('s1');
const next = inbox.notePrompt({ sessionId: 's1', sessionName: 'w1', kind: 'idle' });
expect(next.acknowledgedAt).toBeUndefined();
expect(inbox.getForSession('s1')?.acknowledgedAt).toBeUndefined();
});
it('dismiss removes without answering', () => {
const { resolved } = collect(inbox);
const item = inbox.notePrompt({ sessionId: 's1', sessionName: 'w1', kind: 'question' });
+53
View File
@@ -283,6 +283,59 @@ describe('approval routes', () => {
expect(await listApprovals(harness)).toHaveLength(0);
});
it('viewing a session acknowledges its idle prompt (item stays pending) and broadcasts it', async () => {
session.terminalBuffer = 'claude> waiting at the composer';
await postHook(harness, 'idle_prompt', {});
const [before] = await listApprovals(harness);
expect(before.acknowledgedAt).toBeUndefined();
const res = await harness.app.inject({
method: 'POST',
url: `/api/approvals/session/${SESSION_ID}/viewed`,
payload: {},
});
expect(res.statusCode).toBe(200);
expect(res.json().data).toMatchObject({ sessionId: SESSION_ID, acknowledged: before.id });
// Seen, not answered: still listed (so it stays answerable), no keystrokes,
// and clients skip re-arming the tab alert because of acknowledgedAt.
const [after] = await listApprovals(harness);
expect(after.id).toBe(before.id);
expect(after.acknowledgedAt).toBeGreaterThan(0);
expect(session.writeBuffer).toEqual([]);
// Second view is a no-op (nothing new to tell the other devices).
const again = await harness.app.inject({
method: 'POST',
url: `/api/approvals/session/${SESSION_ID}/viewed`,
payload: {},
});
expect(again.json().data.acknowledged).toBeNull();
});
it('viewing a session leaves a permission dialog alerting (looking is not answering)', async () => {
await postHook(harness, 'permission_prompt', {});
const res = await harness.app.inject({
method: 'POST',
url: `/api/approvals/session/${SESSION_ID}/viewed`,
payload: {},
});
expect(res.statusCode).toBe(200);
expect(res.json().data.acknowledged).toBeNull();
const [item] = await listApprovals(harness);
expect(item.kind).toBe('permission');
expect(item.acknowledgedAt).toBeUndefined();
});
it('viewing an unknown session 404s', async () => {
const res = await harness.app.inject({
method: 'POST',
url: '/api/approvals/session/not-a-session/viewed',
payload: {},
});
expect(res.statusCode).toBe(404);
});
it('non-claude sessions never get inbox items', async () => {
session.mode = 'codex';
await postHook(harness, 'permission_prompt', {});