From ee73f3a84814c2333793bc166fe443cf98e49495 Mon Sep 17 00:00:00 2001 From: HeavyGee <133152184+heavygee@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:37:02 +0000 Subject: [PATCH] feat: show progress bar on session for hours-long jobs (#1424) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: session-attached long-running jobs (#1404) Hub-persisted jobs that outlive the agent process: register/update/clear via REST + `hapi job`, surface primary running progress on the session list even when active=false. Opt-in registration only — not thinking progress. Co-authored-by: Cursor * feat(jobs): agent guidance + wall-clock elapsed on list chrome Document the session-job contract for agents and always show startedAt elapsed next to remaining/fraction/running so indeterminate drains still read as wall time without inventing an ETA. Co-authored-by: Cursor * fix(jobs): address Opus cold-review Majors for #1404 Add hapi job run supervisor (auto-heartbeat + exit status), follow post-merge job-owner redirects so $HAPI_SESSION_ID heartbeats keep working, cover the CLI parser/resolve/run paths with tests, and steer agents toward the supervisor instead of an idle-agent heartbeat myth. Co-authored-by: Cursor * fix(jobs): honor explicit startedAt on PUT; document late-attach clock Beets dogfood: PATCH rejects startedAt; sticky PUT clock made elapsed lie after late attach. Explicit upsert startedAt now corrects; CLI --started-at; clear+set recipe kept for older hubs. Co-authored-by: Cursor * fix(jobs): keep merge redirect keys in MetadataSchema (#1404) SessionCache.refreshSession stripped jobsAcceptedFromSessionIds / jobsTransferredToSessionId as unknown keys, so resolveAttachedJobSessionId could not follow post-merge heartbeats. Declare the fields, add a real SessionCache integration test, and pass full UUIDs through the CLI when the merge source is missing from GET /sessions. Co-authored-by: Cursor * feat(jobs): MCP session_job tool for catalog-level discoverability Expose session-attached jobs in the same HAPI MCP catalog as ping_peer / inspect_peer so Cursor/ACP and steered flavors see outliving-work meters as first-class tooling, not docs-only. Auto-approve own-session calls; steer prefers MCP set/update or CLI job run for supervised children. Co-authored-by: Cursor * feat(web): tri-state pin — default long-running jobs with #1404 Replace boolean pin-in-progress with off / jobs / all. Unset preference defaults to jobs so outliving attached-job sessions float to In progress by default; legacy true→all, false→off. Settings Display gets a 3-way control. Co-authored-by: Cursor * fix(jobs): cold-review pass 3 Blocker + Majors (#1404) CI: bump migration tip expects to SCHEMA 22; stub list attachedJobs mocks; align Codex/OpenCode/ACP fixtures with job steer + session_job tool list. Merge: write jobsAccepted/Transferred redirects after metadata merge so a name/summary copy cannot clobber the post-merge job owner map. MCP: session_job is own-session only (drop sessionId from schema) so auto-approve cannot silently write peer meters. Prefer hapi job run in steer. Co-authored-by: Cursor * fix(jobs): close pass-3 minors — stable primary, own-client heartbeats Resolve JWT/session once for job run heartbeats; order primary job by started_at ASC; cover job redirect 404 + invalid key/body; idle jobs get a Jobs bucket (not Running); treat attachedJob.startedAt as render-relevant. Co-authored-by: Cursor * fix(jobs): refresh JWT for long job-run heartbeats (#1404) Cache sessionId once but re-exchange JWT before hub's 4h expiry and on 401 retry so days-long supervised jobs keep heartbeating and can still mark completed/failed. Log the first heartbeat failure to stderr. Co-authored-by: Cursor * test(jobs): cover proactive JWT refresh; map 401 to auth_failed Co-authored-by: Cursor * fix(jobs): stamp fresh startedAt on job run; prefer supervisor Re-running the same job key was sticky-reusing a prior row's startedAt, so elapsed lied. Drain in-flight heartbeats before terminal status. Align AGENTS/guide: CLI supervisor first, MCP as manual path. Co-authored-by: Cursor * fix(jobs): typecheck-safe assertion for run startedAt Co-authored-by: Cursor * fix(jobs): type put mock args so startedAt assertion typechecks Co-authored-by: Cursor * fix(jobs): address Codex Majors — redirect ancestry, heartbeat status, ACP allowlist Inherit jobsAcceptedFromSessionIds across A→B→C merges; heartbeat PATCH omits status so late ticks cannot resurrect running; drop session_job from global name-only auto-approve (bridge/--allowedTools remain the trust path). Co-authored-by: Cursor * fix(jobs): type from-session metadata when inheriting job redirects Co-authored-by: Cursor * fix(jobs): version attachedJob SSE; keep live job on merge collision Gate list cache on versioned attachedJob patches so dual EventSources cannot resurrect a cleared meter. On transfer key collision, prefer a running source over a terminal target (heartbeats no longer rewrite status). Co-authored-by: Cursor * fix(jobs): monotonic attachedJob emit watermark (not primary.updatedAt) Primary switches can go backwards in updatedAt and strand the list cache. Emit versions are Math.max(Date.now(), prev+1); REST list stamps a fresh wall-clock watermark so null jobs do not reset the client gate to 0. Co-authored-by: Cursor * fix(jobs): one attachedJob watermark allocator for REST and SSE GET /sessions and emitAttachedJobChanged share allocateAttachedJobVersion so equal-ms terminal patches are not rejected after a list refetch. Also preserve real Unix signal exit codes in hapi job run. Co-authored-by: Cursor * fix(jobs): stub allocateAttachedJobVersion in sessions route mocks Co-authored-by: Cursor * fix(jobs): always record merge redirects even with zero jobs transferred Agents may attach the first outliving job after merge while still holding the pre-merge HAPI_SESSION_ID; redirects must exist before that first set. Co-authored-by: Cursor * fix(jobs): install source redirect before merge awaits; allow empty update Point jobsTransferredToSession immediately after transfer so mid-merge heartbeats follow the new owner during scratchlist I/O. Empty CLI/MCP update bodies are heartbeat-only (hub stamps heartbeatAt). Co-authored-by: Cursor * fix(jobs): expect empty MCP update as heartbeat Co-authored-by: Cursor * fix(jobs): treat merge redirect metadata as hub-owned CLI update-metadata must not forge or erase jobsAcceptedFromSessionIds / jobsTransferredToSessionId — same strip/restore as supersede/clear links. Co-authored-by: Cursor * fix(jobs): reconcile REST list against attachedJob watermark Slow /api/sessions can finish after SSE clear/progress and resurrect a stale attachedJob. Also prefer newer terminal results on merge key collisions. Co-authored-by: Cursor * fix(jobs): retry terminal status write; reject startedAt on update Supervisor exit is the only running→terminal transition — retry transient hub failures. --started-at / startedAt only apply to set, not update/run. Co-authored-by: Cursor * fix(jobs): keep both live jobs on same-key merge Dual-running collisions remap the source key and record jobKeyRedirects so pre-merge supervisors cannot terminal-mark the winner. Also raise the flaky claudeRemote first-result test timeout under CI load. Co-authored-by: Cursor * fix(jobs): hard-refuse MCP set; louder stale heartbeat chrome Process-shaped work must use Shell hapi job run. MCP set is refused with the run recipe (wardrobe freeze). Stale rows show "no heartbeat · age". Co-authored-by: Cursor * fix(jobs): preserve jobKeyRedirects across metadata merge + A→B→C Recompute merge metadata from latest target so early key remaps are not clobbered; compose inherited redirects through the current remaps. Localize stale/progress chip strings (en + zh-CN). Co-authored-by: Cursor * fix(jobs): keep running-job stubs in sidebar; align bar precedence Empty idle stubs with a live attachedJob must survive prepareSidebarSessions before title metadata lands. Match fraction to remaining-first label order. Co-authored-by: Cursor * fix(jobs): block delete while job running; keep jobful dedup losers CASCADE would erase outliving meters on inactive delete. Sidebar dedup must not hide a running attachedJob behind a jobless duplicate winner. Co-authored-by: Cursor * fix(jobs): guard store delete for running jobs; transfer on Codex merge Route-only 409 still left Codex duplicate consolidation and other callers cascading live meters. Refuse in DELETE SQL, clear watermarks, and transfer+redirect before Codex hard-deletes duplicates. Co-authored-by: Cursor * test(jobs): stub transferAttachedJobs in Codex duplicate-merge mock Co-authored-by: Cursor * fix(jobs): fence supervisor PATCH with expectedStartedAt Stale hapi job run processes must not heartbeat or terminal-write a newer run that reused the same job key. Treat startedAt as the run generation: supervisors send expectedStartedAt; hub rejects mismatches with 409 (CAS in SQL too). Co-authored-by: Cursor * fix(jobs): CAS supervisor writes with UUID runId (schema V24) Date.now()/startedAt is not unique across concurrent job-run processes. Persist run_id, mint UUID on PUT (client or hub), and reject PATCH when expectedRunId does not match. Replaces the interim expectedStartedAt fence. Co-authored-by: Cursor * fix(jobs): heartbeat PATCH must not re-send launch --detail Supervisor timer only needs expectedRunId so MCP/CLI progress detail updates are not clobbered by the next heartbeat. Co-authored-by: Cursor * fix(jobs): stamp heartbeatAt on the hub only Drop heartbeatAt from upsert/patch schemas and always persist Date.now() on the hub so a skewed/future client clock cannot keep a dead job green. Co-authored-by: Cursor * docs(jobs): note schema tip V25 after A2A V23 collision Co-authored-by: Cursor * fix(jobs): clear stale jobsTransferred redirect on reclaim When A→B then B→A makes A canonical again, drop A's outgoing jobsTransferredToSessionId so resolve(A) no longer hops to deleted B. Co-authored-by: Cursor * fix(jobs): transfer attached jobs on OpenCode /clear finishOpenCodeClear already wrote supersededBySessionId (which job APIs follow) without moving session_jobs. Transfer first so heartbeats on the retained source id reach the replacement row. Co-authored-by: Cursor * fix(jobs): follow job redirects with cycle detection Replace the five-hop cap so supervisors that retain the original HAPI_SESSION_ID across many OpenCode /clear replacements still resolve to the canonical owner. Visited-set stops redirect cycles. Co-authored-by: Cursor * fix(jobs): defer no-engine Codex merge; pending outranks Jobs Refuse duplicate merge when SyncEngine is unavailable and the source still has attached jobs (redirects cannot be persisted). Sidebar: put operator-pending ahead of the Jobs bucket when both apply. Co-authored-by: Cursor * fix(jobs): allocate list watermark before reading jobs GET /api/sessions was labeling snapshots with a version allocated after the job read, so a concurrent SSE emit could lose to a stale REST value. Co-authored-by: Cursor * fix(jobs): stamp supervised startedAt on the hub clock hapi job run omits startedAt; hub uses now when runId starts a new generation so runner/hub skew cannot zero or inflate elapsed time. Co-authored-by: Cursor * fix(cli): preserve -- for hapi job run under normalizeCliArgs Runtime-wrapper handoff was dropping everything before `--` (or stripping `--` itself), so `job run … -- ` fell through to Claude. Keep `--` when a HAPI command already precedes it; only treat bare `bun entry -- ` as a wrapper handoff. Co-authored-by: Cursor * fix(jobs): allow PATCH null clears from CLI and MCP Hub already accepts null to drop stale remaining/done/total so done+total can take over. Expose that via MCP nullable fields and hapi job update --clear-remaining (and siblings). Co-authored-by: Cursor * fix(jobs): scope -- keep to job run; expose runId fence on CLI Only preserve the child `--` separator for `job run`. Re-inserting it for `hapi -- auth` / `codex --` broke resolveCommand. Manual wrappers can now stamp `--run-id` / `--expected-run-id` to match hub CAS. Co-authored-by: Cursor * fix(jobs): fence DELETE/clear with expectedRunId Stale manual wrappers must not clear a newer run after key reuse; hub DELETE and CLI/MCP clear now honor the same run fence as PATCH. Co-authored-by: Cursor * fix(jobs): include runId on listSessionJobs for fence recovery Safe PATCH/DELETE need expectedRunId; list/MCP/CLI must return the generation so reconnecting wrappers can fence without guessing. Co-authored-by: Cursor * fix(web): stamp attachedJob on new SessionSummary test helpers Upstream share-picker / row-summary fixtures landed without #1404 fields; restore typecheck after rebase onto main. Co-authored-by: Cursor * fix(jobs): fail job run when terminal status never persists Child exit 0 with a frozen running meter lied to wrappers; surface hub write failure as exit 1 (run-mismatch still non-fatal). Clarify Active-sessions-only copy for attached jobs. Co-authored-by: Cursor * fix(cursor,web): stop attached-job sessions bouncing Running/Jobs (#1553) Rebase onto upstream/main (#1503). Ignore ambient ACP thinking bumps while the message queue is idle and prompt() is not in flight. Prefer the Jobs in-progress bucket and suppress the thinking spinner when a running attached job is the honest outliving signal. Co-authored-by: Cursor * fix(web): do not mask foreground thinking when attached job runs (#1553) Keep the CLI queue-idle ACP guard; web now trusts hub thinking during real prompts instead of treating every attached job as ambient chatter. Co-authored-by: Cursor * fix: rebase onto upstream/main — resolve test mock conflicts Merge upstream title/summary stubs with attached-job mocks; drop duplicate showSessionSummaryInChat key introduced during rebase. Co-authored-by: Cursor * fix(jobs): preserve child exit 0 when meter cleared during job run Treat terminal PATCH not_found as detached (operator cleared via session_job) instead of a supervision failure. Retry transient 404s; accept absence on the last attempt. Regression test covers successful child after external clear. Co-authored-by: Cursor * fix(cursor): filter only debounced running chatter while queue-idle (#1553) Tag agent-activity listener callbacks with source in AcpSdkBackend so the Cursor launcher can ignore queue-idle state_update:running without hiding harness resume (requires_action, permission). Regression test updated. Co-authored-by: Cursor * fix(#1424): trust ACP foreground signals; preflight merge job check Drop queue-idle running suppression in Cursor launcher — it hid autonomous harness work. Attached-job Running/Jobs flicker stays in web/sessionInProgress. Refuse no-engine Codex merge before copying history when sources have jobs. Co-authored-by: Cursor * fix(cli): steer agents away from sleep-stub jobs and remaining=0 traps MCP update-before-create and hapi job run -- sleep while real work runs elsewhere can leave a misleading running meter. Return job-run recipe on not_found, warn when remaining hits zero without completion, and tighten session_job agent instructions. Co-authored-by: Cursor * fix(cli): steer MCP session_job not_found even when instanceof breaks MCP HTTP server bundles can load duplicate SessionJobError identities so update-before-create fell through to bare "job not found". Detect not_found by code and message, not instanceof alone. Co-authored-by: Cursor * fix(cli): idempotent MCP clear-not-found; reject --heartbeat-sec off run Clear on an already-absent job returns success without steering to hapi job run. Parser rejects --heartbeat-sec on set/update/clear/list. Co-authored-by: Cursor * fix(cli): reject mutation flags on job list/clear and status on run Parser now fails fast when list/clear receive label/status/progress fields, or when run receives --status, instead of silently discarding them. Co-authored-by: Cursor * fix(cli): reject stray MCP fields and non-run command suffix MCP list/clear reject incompatible fields; CLI rejects -- unless action is run so clear/set cannot silently drop a trailing command. Co-authored-by: Cursor * fix(hub): preserve runId on corrective job PUT without runId Started-at corrections via job set must not mint a new generation and break an in-flight supervisor's expectedRunId fence. Docs heartbeat recipe now shows run-id + expected-run-id. Co-authored-by: Cursor * docs: mark ALL_DONE late-attach example as completed status job set defaults to running; remaining=0 alone does not finish the meter. Co-authored-by: Cursor * fix(web,cli): finish #1424 rebase onto upstream pin buckets Keep Jobs in the In progress section after upstream split Active/Running. Preserve Cursor ACP retry fields and Codex prompt test names from main. Quiet connected sessions stay in directories (#1404 stand). Co-authored-by: Cursor * fix(web): rename All activity — quiet connected is not in-progress Connected-but-idle sessions stay in project folders in every pin mode. UI mode label is now Working & pending; drop the unreachable Active pin bucket and the copy that claimed quiet actives floated under All. Co-authored-by: Cursor * docs(guide): session-id contract and remaining vs bar fill Document hub-row vs worker HAPI_SESSION_ID bug and that --remaining alone does not move the progress bar without total. Co-authored-by: Cursor * fix(web): bind isNewerVersionedPatch after sessionPatch extract `export … from` does not put the helper in module scope, so attachedJob list patches failed typecheck after the rebase onto upstream's extract. Guide copy now matches Working & pending; quiet connected stays in folders. Co-authored-by: Cursor * fix(hub): commit job-row move and owner redirects together A failed metadata write after sessionJobs.transfer left the old session id pointing at an emptied source, so heartbeats 404ed. Co-authored-by: Cursor * fix(jobs): fail-closed session id for remote Cursor job run AGENTS and recipe copy no longer treat \$HAPI_SESSION_ID as always safe; remote Cursor may export a worker row. Cursor resume bootstrap test asserts the requested existingSessionId is exported into the child env. Co-authored-by: Cursor * fix(hub): refresh job redirects before scratchlist merge await persistAttachedJobRedirects wrote SQLite while resolveAttachedJobSessionId still read stale cache; heartbeats via the old id could 404 during attachment I/O. Refresh both sessions immediately after persist. Co-authored-by: Cursor * fix(cursor): ignore ambient ACP running without a prompt in flight state_update_running chatter while the queue is idle was setting hub thinking and floating quiet sessions (with jobs) into Working. Permission and requires_action still bump; prompt-owned running still bumps. Co-authored-by: Cursor * fix(cursor): drop leftover rebase conflict markers in ACP launcher Co-authored-by: Cursor * fix(cli): sanitize job text before terminal stdout Strip VT/ANSI and remaining C0 controls from job key/label/unit/detail/runId in formatJobLine so list/set/update cannot emit OSC escapes from persisted fields. Co-authored-by: Cursor * fix(cli): sanitize MCP session_job output via shared formatter Move terminalText/formatJobLine into modules so CLI stdout and MCP tool results both strip VT/ANSI/C0 before agents render job fields. Co-authored-by: Cursor * fix(cli): scrub C1 controls in shared job-output sanitizer Co-authored-by: Cursor * test(cli): fix C1 sanitizer assertion (content may remain) Co-authored-by: Cursor * fix(hub): remap late job PUT when merge left no key redirect When a merged-away session registers a new runId for a key the target already owns as a different running generation, allocate a remapped key and persist jobKeyRedirects so the target's live meter is not overwritten. Co-authored-by: Cursor * fix(hub): also remap redirected job set without runId on collision Co-authored-by: Cursor * fix(cli): tree-kill supervised job children on SIGINT/SIGTERM Bare process.kill only hit the immediate child; a shell grandchild could keep running after the wrapper marked the job terminal. Use killProcessByChildProcess. Co-authored-by: Cursor * fix(cli): preserve SIGINT on job tree-kill and await teardown Forward the received signal through killProcessByChildProcess so Ctrl-C stays exit 130, and wait for verified tree termination before writing the terminal job meter. Co-authored-by: Cursor * test(cli): type the tree-kill teardown patch mock for typecheck Co-authored-by: Cursor * test(web): supply attachedJob fields in upstream session fixtures After rebasing onto main, mark-all-read and app-badge helpers need attachedJob / attachedJobUpdatedAt for SessionSummary typecheck. Co-authored-by: Cursor * fix(hub): record identity jobKeyRedirects on no-collision transfer A→B transfers that keep the original key must still map A/key→key so a later B→C remap can compose A through to the remapped key instead of resolving onto C's unrelated live same-key job. Co-authored-by: Cursor * fix(hub): resolve job owner after PUT/PATCH body parse A merge/clear during the JSON await must not leave mutations targeting the pre-merge session id. Validate the body first, then resolve owner and key synchronously before upsert/patch. Co-authored-by: Cursor * fix(hub): honor identity jobKeyRedirects on corrective PUT Explicit A/key→key maps from no-collision transfers must short-circuit late-registration remapping so job set without runId updates the same row instead of allocating a second key and orphaning the supervisor. Co-authored-by: Cursor * fix(hub): persist identity redirects on late free-key job PUT Empty A→B then late register left no A/batch map, so B→C remaps could not compose and A targeted C's live meter. Co-authored-by: Cursor * fix(hub): skip redirect inheritance on late job-key PUT Recording a free-key identity via retained B was reimporting B's stale A/batch map onto C and undoing composed A→B→C remaps. Co-authored-by: Cursor * test(web): supply attachedJob on new upstream search fixtures Rebase onto main brought search-rank helpers that omit SessionSummary.attachedJob fields required by #1424. Co-authored-by: Cursor * fix(cli): pass XDG_CACHE_HOME through vitest hub globalSetup Estate bun installs pin the cache via XDG_CACHE_HOME; the test hub whitelist omitted it and `bun run hub` hung before ready. Co-authored-by: Cursor * test(web): retarget bucketRunningSessions for jobs pin modes Upstream #1820 idle/active boolean buckets no longer exist after the quiet-connected never-floats contract; cover jobs/working/pending instead. Co-authored-by: Cursor * fix(web): add Russian strings for session jobs pin modes Upstream shipped ru locale after the jobs pin UI; fill attachedJob and tri-state pin copy so Display settings are not missing keys. Co-authored-by: Cursor * docs(cli): steer agents to list session jobs before done/archive MCP session_job description and always-on SESSION_JOB_INSTRUCTION now require list on resume and before done; clear zombie running meters without asking the operator. No hub auto-clear. Co-authored-by: Cursor * test(cli): keep ACP MCP tool list without video/media after rebase Co-authored-by: Cursor * docs(jobs): forbid frozen 0/N job run for display meters Split alive-only vs fraction bars in the guide and always-on steer: heartbeats do not advance launch --done/--total; name hapi-job-run-metered and the continuous-update portable path; note exit≠semantic failure. Co-authored-by: Cursor * test(cli): expect Codex autoReview in set-mode allowed lists Upstream #2090 added autoReview after #2095 set-mode tests; update the allowed-mode strings so CI matches the catalog. Co-authored-by: Cursor * fix(web): use SessionSpinner for foreground thinking after merge Keep isAgentForegroundThinking gate; match upstream SessionSpinner markup so background/thinking spinner equality tests pass. Co-authored-by: Cursor * test(hub): expect schema tip v29 in migration-v26 after jobs remap Co-authored-by: Cursor * test(web): expect fixed-order + jobs pin after merge with upstream display Upstream asserted Fixed session order was gone; #1424 keeps it with the tri-state pin choice group. Co-authored-by: Cursor * fix(web): honor Fixed session order with creation-time sort Tip Minor: the setting only paused pin float while directories still sorted by lastUserMessageAt. Use createdAt comparators for rows, groups, and global pins when fixed mode is on. Co-authored-by: Cursor * test(web): cover Fixed session order vs activity list promotion Upstream order test forced obsolete fixed-order=true and expected activity promotion; with #1424 keeping the setting, split default vs fixed cases. Co-authored-by: Cursor * fix(hub): preserve composed jobKeyRedirects on cleanup re-merge A second B→C merge with empty remaps was reimporting retained B's stale A/batch→batch and clobbering C's composed A/batch→batch. mapping. Co-authored-by: Cursor * fix(jobs): survive hub-down after job run child exit Terminal completed/failed PATCH now retries connection/502–504 failures for up to ~10m so a brief hub restart cannot leave a zombie running meter. Refuse wrapping hapi-restart-hub / stack-switch argv in job run; document the hard rule in the guide and CLI help. Co-authored-by: Cursor * fix(jobs): classify HTTP 502–504 via SessionJobError.httpStatus Structured hub outage bodies (e.g. 503 "Not connected") no longer drop the status code, so terminal PATCH keeps the hub-down retry window instead of exiting after three short attempts. Co-authored-by: Cursor * chore: nudge GitHub PR head sync for #1424 Fork tip already includes the upstream/main merge; empty commit to re-fire the cross-repo PR head webhook (API still showed prior SHA). Co-authored-by: Cursor * fix(web): honor jobs exception and fixed order under list view Active status filter keeps idle running attachedJob rows (and keeps them out of archived). Fixed session order forces created sort with activeFirst off, not only pin-off. Co-authored-by: Cursor * fix(web): ignore obsolete fixed-order key under SessionListView Upstream #2263 made hapi-fixed-session-order obsolete; reading it overrode last-message promotion. Keep jobs-aware status filtering; list sort stays on SessionListView. Co-authored-by: Cursor * fix(hub): include attachedJob on content-search summaries Content-search replaces live list rows; omitting jobs dropped meters and the active-filter exception for matching idle sessions (#1424). Co-authored-by: Cursor * fix(web): remove obsolete fixed session order setting SessionListView owns list order (#2263); the switch only wrote a dead localStorage key and kept recycling tip Findings on #1424. Co-authored-by: Cursor * chore: nudge GitHub PR head sync for #1424 Co-authored-by: Cursor * test(web): drop Fixed session order assertion from display settings Matches removal of the obsolete switch under SessionListView (#2263). Co-authored-by: Cursor * fix(web): drop fake 1/3 fill for indeterminate attached jobs Remaining-only jobs have no fraction; the old pulse bar painted a constant w-1/3 that looked like progress. Keep honest text; show a bar only when done/remaining+total yields a real fraction. Co-authored-by: Cursor * feat(jobs): wake owning session on terminal status (#1489) Fold opt-in wakeOnTerminal into the #1424 tip for dogfood-lane ship. Schema v33→v34 additive wake columns + runId one-shot claim. Co-authored-by: Cursor * fix(jobs): release terminal wake claim on delivery failure Provisional wake_emitted claims must clear when resume/send fails so a reconnect retry can reclaim; schedule capped backoff and use a run-scoped localId for send dedupe (#1489 tip Finding). Co-authored-by: Cursor * fix(jobs): requeue wakes after retry budget and follow ownership Keep undelivered terminal wakes eligible after rapid-retry exhaustion and rescan on hub start / machine offline→online. Resolve job-owner and key redirects before claim, release, and deferred retry so merges cannot strand a provisional wake_emitted claim. Co-authored-by: Cursor * fix(jobs): provisional pending wake claims + run fence Persist wake delivery as pending: until send succeeds so hub restart can clearAbandoned and reclaim. Before send, fence the live row to the claimed run/terminal/opt-in so key reuse mid-resume cannot mis-prompt. Co-authored-by: Cursor * fix(web): classic indeterminate marquee for unknown attached jobs Session list claimed an "indeterminate bar" but only rendered the pulse dot when fraction was null. Show a track with a sliding segment (no %) in the same slot as determinate fill, with unit coverage and docs/help aligned to shapes A/B. Co-authored-by: Cursor * fix(web): quiet striped indeterminate job bar Replace the loud sliding-chunk marquee with CSS-Tricks-style diagonal stripes that drift slowly at low contrast — still reads as moving, not carnival mode. Co-authored-by: Cursor * fix(web): seamless loop for indeterminate job stripes Animate background-position by exactly one 8px tile on both axes so the diagonal stripe phase matches at the loop boundary (was -12px → jump). Co-authored-by: Cursor * fix(jobs): requeue wakes on machine-update-state online Connect marks active via runner-state update before the first heartbeat, so heartbeat offline→online never fired. Requeue pending terminal wakes when machine-updated refreshes an offline machine to active. Co-authored-by: Cursor * test(hub): cast private machineCache in wake reconnect coverage CI typecheck failed on private SyncEngine.machineCache access from the machine-updated requeue test. Co-authored-by: Cursor * fix(hub): monotonic machine active_at on runner-state online refreshMachine only adopts store activity when storedActiveAt is strictly newer than the cache. Same-ms create→updateMachineRunnerState left the cache stuck inactive and skipped #1489 wake requeue. Bump active_at past the activity floor; align the reconnect test with memory-only expiry. Co-authored-by: Cursor * feat(cli): require --progress mode on job run/set Forces an explicit affordance (unknown|fraction|until) so known-duration countdowns cannot silently fall into indeterminate stripes. until stamps remaining/total and job-run heartbeats re-stamp remaining from the deadline. Co-authored-by: Cursor * docs(session-jobs): require --progress in create examples Bot Minor: wake/set/heartbeat/CLI recipes and AGENTS.md omitted the now-mandatory progress mode, so copy-paste creates would fail parse. Co-authored-by: Cursor * fix(cli): refuse numeric sleep without until; honor --started-at on countdown Closes the dogfood footgun: sleep N under unknown/fraction is rejected. Until-mode job run accepts --started-at so mid-window re-attach keeps the original window total; heartbeats stamp against that start. Docs demote estate-only hapi-job-run-metered as non-upstream. Co-authored-by: Cursor * test(cli): type heartbeat mock args in until startedAt coverage Fixes CI TS2493 on patch.mock.calls[0][1] from an untyped vi.fn. Co-authored-by: Cursor * fix(hub): exempt job-wake prompts from session-end sweep Session-end was synthetically consuming unacked hapi-job-wake: rows, so a completion wake queued behind an active turn could be lost when the CLI disconnected before messages-consumed. Mirror the ping-peer- exemption so wakes stay replayable until a real runtime ACK. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- AGENTS.md | 15 + cli/README.md | 1 + cli/src/agent/backends/acp/AcpSdkBackend.ts | 28 +- cli/src/agent/runners/runAgentSession.test.ts | 4 +- cli/src/agent/sessionFactory.test.ts | 35 + cli/src/claude/utils/startHappyServer.test.ts | 48 +- cli/src/claude/utils/startHappyServer.ts | 22 + cli/src/claude/utils/systemPrompt.ts | 3 +- cli/src/codex/happyMcpStdioBridge.test.ts | 37 +- cli/src/codex/happyMcpStdioBridge.ts | 45 +- cli/src/codex/utils/appServerConfig.test.ts | 28 +- .../codex/utils/buildHapiMcpBridge.test.ts | 16 +- cli/src/codex/utils/buildHapiMcpBridge.ts | 4 + cli/src/codex/utils/systemPrompt.ts | 3 +- cli/src/commands/job.test.ts | 360 ++++++ cli/src/commands/job.ts | 628 +++++++++++ cli/src/commands/registry.ts | 2 + .../cursor/cursorAcpRemoteLauncher.test.ts | 72 +- cli/src/cursor/cursorAcpRemoteLauncher.ts | 12 +- cli/src/grok/utils/systemPrompt.ts | 3 +- .../permission/BasePermissionHandler.test.ts | 12 + .../permission/BasePermissionHandler.ts | 3 + .../common/sessionJobInstruction.test.ts | 32 + .../modules/common/sessionJobInstruction.ts | 49 + cli/src/modules/sessionJob/formatJobLine.ts | 69 ++ .../sessionJob/jobProgressMode.test.ts | 115 ++ cli/src/modules/sessionJob/jobProgressMode.ts | 161 +++ .../modules/sessionJob/runSessionJob.test.ts | 1000 +++++++++++++++++ cli/src/modules/sessionJob/runSessionJob.ts | 380 +++++++ cli/src/modules/sessionJob/sessionJob.ts | 458 ++++++++ .../modules/sessionJob/sessionJobMcp.test.ts | 197 ++++ cli/src/modules/sessionJob/sessionJobMcp.ts | 236 ++++ cli/src/opencode/utils/systemPrompt.test.ts | 4 +- cli/src/opencode/utils/systemPrompt.ts | 5 +- cli/src/runner/buildCliArgs.test.ts | 4 +- cli/src/test/globalSetup.ts | 8 + cli/src/utils/cliArgs.test.ts | 82 ++ cli/src/utils/process.ts | 39 +- docs/.vitepress/config.ts | 1 + docs/guide/faq.md | 5 + docs/guide/session-jobs.md | 318 ++++++ .../handlers/cli/sessionHandlers.test.ts | 40 +- .../socket/handlers/cli/sessionHandlers.ts | 5 + hub/src/store/index.ts | 124 +- hub/src/store/machines.ts | 9 +- hub/src/store/migration-v13.test.ts | 6 +- hub/src/store/migration-v15.test.ts | 6 +- hub/src/store/migration-v18.test.ts | 2 +- hub/src/store/migration-v19.test.ts | 2 +- hub/src/store/migration-v20.test.ts | 2 +- hub/src/store/migration-v23.test.ts | 12 +- hub/src/store/migration-v24.test.ts | 6 +- hub/src/store/migration-v25.test.ts | 2 +- hub/src/store/migration-v26.test.ts | 2 +- hub/src/store/migration-v28.test.ts | 2 +- hub/src/store/migration-v30.test.ts | 4 +- hub/src/store/sessionJobWakeClaim.test.ts | 165 +++ hub/src/store/sessionJobs.ts | 579 ++++++++++ hub/src/store/sessionJobsStore.ts | 112 ++ hub/src/store/sessions.ts | 9 + hub/src/store/types.ts | 21 + hub/src/sync/machineCache.test.ts | 21 + hub/src/sync/messageService.test.ts | 41 + hub/src/sync/messageService.ts | 19 +- hub/src/sync/opencodeClear.test.ts | 54 + hub/src/sync/sessionCache-merge-jobs.test.ts | 971 ++++++++++++++++ hub/src/sync/sessionCache.ts | 535 +++++++++ hub/src/sync/sessionJobWake.engine.test.ts | 417 +++++++ hub/src/sync/sessionJobWake.test.ts | 80 ++ hub/src/sync/sessionJobWake.ts | 77 ++ hub/src/sync/syncEngine.ts | 450 +++++++- hub/src/web/routes/codexDesktop.test.ts | 53 + hub/src/web/routes/codexDesktop.ts | 15 + hub/src/web/routes/sessions-jobs.test.ts | 376 +++++++ hub/src/web/routes/sessions.test.ts | 70 +- hub/src/web/routes/sessions.ts | 218 +++- shared/src/index.ts | 12 + shared/src/schemas.clear.test.ts | 17 + shared/src/schemas.sessionPatch.test.ts | 38 +- shared/src/schemas.ts | 94 +- shared/src/sessionOrder.test.ts | 19 +- shared/src/sessionOrder.ts | 10 + shared/src/sessionSummary.test.ts | 21 + shared/src/sessionSummary.ts | 24 +- shared/src/types.ts | 4 + .../SessionAttentionIndicator.test.tsx | 2 + .../SessionList.directory-action.test.tsx | 171 ++- .../SessionList.machine-filter.test.tsx | 2 + .../SessionList.mark-all-read.test.tsx | 2 + .../SessionList.quick-archive.test.tsx | 1 + .../SessionList.search-pin-divider.test.tsx | 2 + web/src/components/SessionList.test.ts | 172 ++- web/src/components/SessionList.tsx | 173 ++- .../SessionList.unread-visibility.test.tsx | 2 + web/src/components/SessionRowSummary.test.tsx | 108 ++ web/src/components/SessionRowSummary.tsx | 96 +- .../settings/SettingsPrimitives.tsx | 10 +- .../queries/reconcileAttachedJobs.test.ts | 101 ++ .../hooks/queries/reconcileAttachedJobs.ts | 34 + web/src/hooks/queries/useSessions.test.tsx | 1 + web/src/hooks/queries/useSessions.ts | 4 +- web/src/hooks/useAppBadge.test.ts | 2 + .../hooks/usePinInProgressSessions.test.ts | 48 + web/src/hooks/usePinInProgressSessions.ts | 116 +- web/src/hooks/useSSE.test.ts | 19 + web/src/hooks/useSSE.ts | 37 +- web/src/index.css | 44 + web/src/lib/attachedJob.test.ts | 83 ++ web/src/lib/attachedJob.ts | 92 ++ web/src/lib/locales/en.ts | 16 +- web/src/lib/locales/ru.ts | 15 +- web/src/lib/locales/zh-CN.ts | 16 +- web/src/lib/sessionAttention.test.ts | 2 + web/src/lib/sessionInProgress.test.ts | 72 ++ web/src/lib/sessionInProgress.ts | 32 + web/src/lib/sessionListSearch.test.ts | 2 + web/src/lib/sessionReference.test.ts | 2 + web/src/lib/sharePickerSessions.test.ts | 2 + web/src/routes/settings/display.tsx | 15 +- web/src/routes/settings/index.test.tsx | 9 +- 120 files changed, 10463 insertions(+), 332 deletions(-) create mode 100644 cli/src/commands/job.test.ts create mode 100644 cli/src/commands/job.ts create mode 100644 cli/src/modules/common/sessionJobInstruction.test.ts create mode 100644 cli/src/modules/common/sessionJobInstruction.ts create mode 100644 cli/src/modules/sessionJob/formatJobLine.ts create mode 100644 cli/src/modules/sessionJob/jobProgressMode.test.ts create mode 100644 cli/src/modules/sessionJob/jobProgressMode.ts create mode 100644 cli/src/modules/sessionJob/runSessionJob.test.ts create mode 100644 cli/src/modules/sessionJob/runSessionJob.ts create mode 100644 cli/src/modules/sessionJob/sessionJob.ts create mode 100644 cli/src/modules/sessionJob/sessionJobMcp.test.ts create mode 100644 cli/src/modules/sessionJob/sessionJobMcp.ts create mode 100644 docs/guide/session-jobs.md create mode 100644 hub/src/store/sessionJobWakeClaim.test.ts create mode 100644 hub/src/store/sessionJobs.ts create mode 100644 hub/src/store/sessionJobsStore.ts create mode 100644 hub/src/sync/sessionCache-merge-jobs.test.ts create mode 100644 hub/src/sync/sessionJobWake.engine.test.ts create mode 100644 hub/src/sync/sessionJobWake.test.ts create mode 100644 hub/src/sync/sessionJobWake.ts create mode 100644 hub/src/web/routes/sessions-jobs.test.ts create mode 100644 web/src/hooks/queries/reconcileAttachedJobs.test.ts create mode 100644 web/src/hooks/queries/reconcileAttachedJobs.ts create mode 100644 web/src/hooks/usePinInProgressSessions.test.ts create mode 100644 web/src/lib/attachedJob.test.ts create mode 100644 web/src/lib/attachedJob.ts create mode 100644 web/src/lib/sessionInProgress.test.ts create mode 100644 web/src/lib/sessionInProgress.ts diff --git a/AGENTS.md b/AGENTS.md index 99277c95..e5d883c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,6 +24,7 @@ Start with the task's files; read only relevant sections of these references, no | Shared wire types and validation | `shared/src/types.ts`, `schemas.ts`, `socket.ts`, `modes.ts` | | Native API contract, chat conformance | [client contract](docs/api/client-contract/index.md), [iOS](ios/README.md), [Android](android/README.md) | | Encrypted native push relay | [relay/README.md](relay/README.md) | +| Session-attached jobs (outliving work) | [session jobs guide](docs/guide/session-jobs.md), `cli/src/commands/job.ts` | | User docs / marketing site | `docs/` (VitePress) / `website/` | ## Repository conventions @@ -39,6 +40,20 @@ Start with the task's files; read only relevant sections of these references, no - Metadata/state updates are versioned; preserve stale-update rejection. Permission controls use per-flavor catalogs in `shared/src/modes.ts`, further constrained by session capabilities. - `shared/fixtures/**` is generated from the web chat pipeline, the source of truth for native conformance. Never hand-edit fixtures. For changes to fixture inputs or generation (paths in [.github/workflows/fixtures.yml](.github/workflows/fixtures.yml)), run `bun run gen:fixtures` and include any generated changes in the deliverable. CI checks drift and runs native conformance on fixture changes. +## Session-attached jobs (outliving work) + +When an agent starts process-shaped work that will keep running after the agent goes idle (`nohup`, batch imports, long scripts, external daemons), attach it so the session list stays truthful while `active: false`. This is **not** thinking progress / todos / in-agent background tools. + +Agent contract (idle agents cannot heartbeat — bare set + nohup freezes the bar): + +1. **Required for process-shaped work:** Shell `hapi job run --label … --progress unknown|fraction|until … -- ` (auto-heartbeat + exit status; `--progress` required). Use `"$HAPI_SESSION_ID"` only when it matches the operator chat row (`/sessions/` in the web URL). +2. MCP `session_job` **refuses `action=set`**. Use it only for `update` / `clear` / `list` on a job the supervisor already created. +3. Manual CLI `set` only with a self-heartbeating wrapper (`update` ≥~10m); never MCP set + nohup. +4. Prefer honest `--remaining`+`--total` or `--done`/`--total` for a determinate fill; omit counts if unknown — list shows a subtle indeterminate striped bar (no %). Never invent a percent. +5. Elapsed wall clock is always shown from `startedAt` (not an ETA). + +Full guide: [docs/guide/session-jobs.md](docs/guide/session-jobs.md). CLI: `hapi job --help`. + ## Verification and completion Choose checks by the change's impact, not by the number of workflow steps: diff --git a/cli/README.md b/cli/README.md index 2a303e95..fe1962cd 100644 --- a/cli/README.md +++ b/cli/README.md @@ -47,6 +47,7 @@ Choose a supported coding agent from your terminal and control its sessions remo - `hapi usage [--since 24h|7d||] [--until …] [--json]` - When agents were working across every machine on the hub, from `GET /api/activity`. `--json` prints one `hapi.activity.v1` report for other tools (time trackers); errors go to stderr with exit codes 2 (arguments), 3 (no token or refused), 4 (hub too old), 1 (other). - `hapi inspect-peer ` - Read-only peer metadata + recent message text (no resume). Prefer this or MCP `inspect_peer` when a user cites `[title](/sessions/)` or Copy-reference `See session "…" (/sessions/) for context`. `/sessions/` is a hub path, not a local file. Optional `--limit`. - `hapi set-mode ` - Change the permission mode of an existing session, like the web permission picker. Active sessions switch immediately; inactive ones use it on next resume. An invalid mode prints the modes allowed for that agent. +- `hapi job set|update|clear|list|run` - Attach long-running outliving work to a session so the list UI shows progress while the agent is idle (`tiann/hapi#1404`). Prefer `"$HAPI_SESSION_ID"`. Heartbeat via `update` (or `run`); honest `--remaining` or `--done`/`--total` (omit counts if unknown — never invent a percent). Late-attach clock fix: `set --started-at ` or clear+set. See `docs/guide/session-jobs.md` and `hapi job --help`. Peer messages default to `auto`: use the target's live capabilities and turn state to steer an active, eligible turn; otherwise queue. Inactive peers require explicit `wake: true`; awakened peers enter the ordinary queue. This applies to every steering-supported diff --git a/cli/src/agent/backends/acp/AcpSdkBackend.ts b/cli/src/agent/backends/acp/AcpSdkBackend.ts index 7a744de1..ecf5737d 100644 --- a/cli/src/agent/backends/acp/AcpSdkBackend.ts +++ b/cli/src/agent/backends/acp/AcpSdkBackend.ts @@ -5,6 +5,16 @@ import { AcpStdioTransport, type AcpStderrError } from './AcpStdioTransport'; import { AcpMessageHandler, type AcpTextChunkMode } from './AcpMessageHandler'; import { ACP_SESSION_UPDATE_TYPES, OPENCODE_CHILD_SESSION_UPDATES, OPENCODE_CHILD_UPDATE_METHOD } from './constants'; import { thinkingHintFromSessionUpdate } from './shouldBumpThinkingFromSessionUpdate'; + +/** Why the backend is bumping/clearing hub thinking — launchers filter chatter here (#1553). */ +export type AgentActivitySource = + | 'state_update_running' + | 'state_update_idle' + | 'state_update_requires_action' + | 'permission' + | 'form_elicitation'; + +export type AgentActivityListener = (thinking: boolean, source: AgentActivitySource) => void; import { logger } from '@/ui/logger'; import { withRetry } from '@/utils/time'; import packageJson from '../../../../package.json'; @@ -135,7 +145,7 @@ export class AcpSdkBackend implements AgentBackend { private sessionInfoUpdateListener: ((update: AcpSessionInfoUpdate) => void) | null = null; private userMessageChunkListener: ((text: string) => void) | null = null; /** Fired on foreground ACP state / permission so launchers can bump hub thinking (#1470). */ - private agentActivityListener: ((thinking: boolean) => void) | null = null; + private agentActivityListener: AgentActivityListener | null = null; /** Debounce timer for state_update running → thinking (#1502 chatter). */ private runningThinkingTimer: ReturnType | null = null; private lastForwardedUsageUpdate: AcpUsageUpdate | null = null; @@ -664,7 +674,7 @@ export class AcpSdkBackend implements AgentBackend { * `false` = `state_update` idle (skipped while a HAPI prompt turn is still draining). * Launchers should ignore no-ops when session.thinking already matches. */ - setAgentActivityListener(listener: ((thinking: boolean) => void) | null): void { + setAgentActivityListener(listener: AgentActivityListener | null): void { this.agentActivityListener = listener; } @@ -1030,7 +1040,7 @@ export class AcpSdkBackend implements AgentBackend { } }; this.pendingElicitations.add(pending); - this.agentActivityListener?.(true); + this.agentActivityListener?.(true, 'form_elicitation'); this.formElicitationHandler!(request).then( (response) => pending.settle(response), (error) => { @@ -1370,7 +1380,7 @@ export class AcpSdkBackend implements AgentBackend { if (this.isProcessingMessage) { return; } - this.agentActivityListener(false); + this.agentActivityListener(false, 'state_update_idle'); return; } @@ -1381,13 +1391,17 @@ export class AcpSdkBackend implements AgentBackend { } this.runningThinkingTimer = setTimeout(() => { this.runningThinkingTimer = null; - this.agentActivityListener?.(true); + this.agentActivityListener?.(true, 'state_update_running'); }, AcpSdkBackend.RUNNING_THINKING_DEBOUNCE_MS); return; } this.clearRunningThinkingTimer(); - this.agentActivityListener(true); + const source: AgentActivitySource = update.sessionUpdate === 'state_update' + && update.state === 'requires_action' + ? 'state_update_requires_action' + : 'state_update_running'; + this.agentActivityListener(true, source); } private clearRunningThinkingTimer(): void { @@ -1573,7 +1587,7 @@ export class AcpSdkBackend implements AgentBackend { if (this.permissionHandler) { try { // Permission prompts imply the agent is awake (#1470). - this.agentActivityListener?.(true); + this.agentActivityListener?.(true, 'permission'); this.permissionHandler(request); } catch (error) { this.pendingPermissions.delete(toolCallId); diff --git a/cli/src/agent/runners/runAgentSession.test.ts b/cli/src/agent/runners/runAgentSession.test.ts index b81ffe26..72044b4c 100644 --- a/cli/src/agent/runners/runAgentSession.test.ts +++ b/cli/src/agent/runners/runAgentSession.test.ts @@ -76,7 +76,7 @@ vi.mock('@/claude/utils/startHappyServer', () => ({ harness.startHappyServerOptions = options return { url: 'http://127.0.0.1:1234', - toolNames: ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'skill_lookup'], + toolNames: ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'session_job', 'skill_lookup'], stop: harness.stopServer } }) @@ -169,7 +169,7 @@ describe('runAgentSession', () => { '--url', 'http://127.0.0.1:1234', '--tools', - 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,skill_lookup', + 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,session_job,skill_lookup', '--hapi-session-id', 'hub-session-acp-1', ]) diff --git a/cli/src/agent/sessionFactory.test.ts b/cli/src/agent/sessionFactory.test.ts index 8270b251..027f0bff 100644 --- a/cli/src/agent/sessionFactory.test.ts +++ b/cli/src/agent/sessionFactory.test.ts @@ -159,6 +159,41 @@ describe('bootstrapExistingSession', () => { ) }) + it('exports the requested existing session id for Cursor runner resume (#1404)', async () => { + // Runner passes --existing-session-id (buildCliArgs); child bootstrap must + // publish that same hub row into HAPI_SESSION_ID for shell `hapi job run`. + const session = createSession() + session.metadata = { + ...session.metadata!, + flavor: 'cursor', + cursorSessionId: 'cursor-csid-1', + cursorSessionProtocol: 'acp' + } + const sessionClient = { updateMetadata: vi.fn() } + getSessionMock.mockResolvedValue(session) + getOrCreateMachineMock.mockResolvedValue({ id: 'machine-1' }) + sessionSyncClientMock.mockReturnValue(sessionClient) + readSettingsMock.mockResolvedValue({ machineId: 'machine-1' }) + + await bootstrapExistingSession({ + sessionId: 'hapi-session-1', + flavor: 'cursor', + startedBy: 'runner', + workingDirectory: '/tmp/project' + }) + + expect(getSessionMock).toHaveBeenCalledWith('hapi-session-1') + expect(process.env[HAPI_SESSION_ID_ENV]).toBe('hapi-session-1') + expect(notifyRunnerSessionStartedMock).toHaveBeenCalledWith( + 'hapi-session-1', + expect.objectContaining({ + flavor: 'cursor', + startedBy: 'runner', + startedFromRunner: true + }) + ) + }) + it('refuses to reopen a hub-archived session (hub-archive resurrection guard)', async () => { // #1911 M1 belt: hub-archived only (matches store merge-preserve scope). const session = createSession() diff --git a/cli/src/claude/utils/startHappyServer.test.ts b/cli/src/claude/utils/startHappyServer.test.ts index 575f5482..a56d8db1 100644 --- a/cli/src/claude/utils/startHappyServer.test.ts +++ b/cli/src/claude/utils/startHappyServer.test.ts @@ -111,15 +111,16 @@ describe('startHappyServer skill_lookup', () => { const mcp = await connect(false) const tools = await mcp.listTools() - expect(tools.tools.map((tool) => tool.name)).toEqual([ + expect(tools.tools.map((tool) => tool.name).sort()).toEqual([ 'change_title', 'display_image', - 'display_video', 'display_media', - 'ping_peer', - 'spawn_peer', + 'display_video', 'inspect_peer', - 'list_peers' + 'list_peers', + 'ping_peer', + 'session_job', + 'spawn_peer', ]) }) @@ -439,6 +440,7 @@ describe('startHappyServer skill_lookup', () => { it('does not expose change_title when native ACP titles are enabled', async () => { const sessionClient = { + sessionId: 'test-session-id', updateMetadata: vi.fn(), sendAgentMessage: vi.fn(), sendClaudeSessionMessage: vi.fn() @@ -451,15 +453,25 @@ describe('startHappyServer skill_lookup', () => { await mcp.connect(new StreamableHTTPClientTransport(new URL(server.url))) const tools = await mcp.listTools() - expect(server.toolNames).toEqual(['display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer']) - expect(tools.tools.map((tool) => tool.name)).toEqual([ + expect(server.toolNames).toEqual([ 'display_image', 'display_video', 'display_media', + 'list_peers', 'ping_peer', - 'spawn_peer', 'inspect_peer', - 'list_peers' + 'spawn_peer', + 'session_job', + ]) + expect(tools.tools.map((tool) => tool.name).sort()).toEqual([ + 'display_image', + 'display_media', + 'display_video', + 'inspect_peer', + 'list_peers', + 'ping_peer', + 'session_job', + 'spawn_peer', ]) }) @@ -677,11 +689,13 @@ describe('toClaudeAllowedHapiMcpTools', () => { 'ping_peer', 'inspect_peer', 'spawn_peer', + 'session_job', 'skill_lookup' ])).toEqual([ 'mcp__hapi__change_title', 'mcp__hapi__display_image', 'mcp__hapi__list_peers', + 'mcp__hapi__session_job', 'mcp__hapi__skill_lookup' ]) expect(toClaudeAllowedHapiMcpTools(['display_video'])).not.toContain('mcp__hapi__display_video') @@ -787,13 +801,25 @@ describe('startHappyServer peer tools kill switch', () => { it('omits peer tools from registration and toolNames when HAPI_DISABLE_PEER_TOOLS is set', async () => { process.env.HAPI_DISABLE_PEER_TOOLS = '1' const { toolNames } = await startServer() - expect(toolNames).toEqual(['change_title', 'display_image', 'display_video', 'display_media']) + // session_job is own-session (not peer) — stays available when peer tools are off. + expect(toolNames).toEqual([ + 'change_title', + 'display_image', + 'display_video', + 'display_media', + 'session_job', + ]) const tools = await client!.listTools() const names = tools.tools.map((tool) => tool.name) expect(names).not.toContain('list_peers') expect(names).not.toContain('ping_peer') expect(names).not.toContain('inspect_peer') expect(names).not.toContain('spawn_peer') - expect(names).toEqual(expect.arrayContaining(['display_image', 'display_video', 'display_media'])) + expect(names).toEqual(expect.arrayContaining([ + 'display_image', + 'display_video', + 'display_media', + 'session_job', + ])) }) }) diff --git a/cli/src/claude/utils/startHappyServer.ts b/cli/src/claude/utils/startHappyServer.ts index a3750f4e..0e7eba4b 100644 --- a/cli/src/claude/utils/startHappyServer.ts +++ b/cli/src/claude/utils/startHappyServer.ts @@ -39,6 +39,13 @@ import { CREATABLE_AGENT_FLAVORS } from '@hapi/protocol/modes' import { PermissionModeSchema } from '@hapi/protocol/schemas' import { PingPeerError, formatInspectPeerReport, formatPeerSessionsList, forwardPeerReply, inspectPeer, listPeerSessions, peerListFetchLimit, pingPeer, supportsPeerReply } from "@/modules/pingPeer/pingPeer"; import { applySessionDisplayRename, normalizeSessionDisplayTitle } from "@/agent/sessionDisplayRename"; +import { + SESSION_JOB_TOOL_DESCRIPTION, + SESSION_JOB_TOOL_NAME, + handleSessionJobTool, + sessionJobInputSchema, + type SessionJobToolArgs, +} from "@/modules/sessionJob/sessionJobMcp"; import { SpawnPeerError, spawnPeer } from "@/modules/spawnPeer/spawnPeer"; export type HapiMcpToolName = @@ -50,6 +57,7 @@ export type HapiMcpToolName = | 'ping_peer' | 'inspect_peer' | 'spawn_peer' + | 'session_job' | 'skill_lookup'; type StartHappyServerOptions = { @@ -432,6 +440,19 @@ function createHapiMcpServer( } }); + registerTool(SESSION_JOB_TOOL_NAME, { + description: SESSION_JOB_TOOL_DESCRIPTION, + title: 'Session-Attached Job', + inputSchema: sessionJobInputSchema, + }, async (args: SessionJobToolArgs) => { + logger.debug('[hapiMCP] session_job:', args.action, args.jobKey); + const result = await handleSessionJobTool(args, client.sessionId); + return { + content: [{ type: 'text' as const, text: result.text }], + isError: result.isError, + }; + }); + if (!peerToolsDisabled) { registerTool('ping_peer', { description: PING_PEER_TOOL_DESCRIPTION, @@ -710,6 +731,7 @@ export async function startHappyServer(client: ApiSessionClient, options: StartH if (includeTool(name)) toolNames.push(name); } } + if (includeTool(SESSION_JOB_TOOL_NAME)) toolNames.push(SESSION_JOB_TOOL_NAME); if (options.skillLookup && includeTool('skill_lookup')) toolNames.push('skill_lookup'); if (toolNames.length === 0) { throw new Error('startHappyServer requires at least one enabled tool'); diff --git a/cli/src/claude/utils/systemPrompt.ts b/cli/src/claude/utils/systemPrompt.ts index 8a49b1d0..b90d4ecf 100644 --- a/cli/src/claude/utils/systemPrompt.ts +++ b/cli/src/claude/utils/systemPrompt.ts @@ -3,6 +3,7 @@ import { buildSessionCitationSteerInstruction, SESSION_CITATION_DISABLED_STEER } import { isPeerToolsDisabled } from "@/modules/common/peerTools"; import { shouldIncludeCoAuthoredBy } from "./claudeSettings"; import { DISPLAY_IMAGE_PROMPT_CLAUDE, DISPLAY_MEDIA_PROMPT_CLAUDE, DISPLAY_VIDEO_PROMPT_CLAUDE } from "@/modules/common/displayImagePrompt"; +import { withSessionJobInstruction } from "@/modules/common/sessionJobInstruction"; import { withSessionSummaryInstruction } from "@/modules/common/sessionSummaryInstruction"; /** @@ -44,5 +45,5 @@ export function getSystemPrompt(): string { const base = includeCoAuthored ? BASE_SYSTEM_PROMPT + '\n\n' + CO_AUTHORED_CREDITS : BASE_SYSTEM_PROMPT; - return withSessionSummaryInstruction(base); + return withSessionSummaryInstruction(withSessionJobInstruction(base)); } diff --git a/cli/src/codex/happyMcpStdioBridge.test.ts b/cli/src/codex/happyMcpStdioBridge.test.ts index a8930dd7..0a169e88 100644 --- a/cli/src/codex/happyMcpStdioBridge.test.ts +++ b/cli/src/codex/happyMcpStdioBridge.test.ts @@ -70,16 +70,20 @@ describe('runHappyMcpStdioBridge tool forwarding', () => { '--url', 'http://127.0.0.1:43006', '--tools', - 'change_title,display_image,display_video,display_media,skill_lookup' + 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,session_job,skill_lookup' ]) - expect([...harness.tools.keys()]).toEqual([ + expect([...harness.tools.keys()].sort()).toEqual([ 'change_title', 'display_image', - 'display_video', 'display_media', - 'skill_lookup' - ]) + 'display_video', + 'inspect_peer', + 'list_peers', + 'ping_peer', + 'session_job', + 'skill_lookup', + ].sort()) const handler = harness.tools.get('skill_lookup') expect(handler).toBeDefined() @@ -140,6 +144,24 @@ describe('runHappyMcpStdioBridge tool forwarding', () => { ]) }) + it('registers session_job when included in --tools', async () => { + await runHappyMcpStdioBridge([ + '--url', + 'http://127.0.0.1:43006', + '--tools', + 'change_title,display_image,list_peers,ping_peer,inspect_peer,session_job' + ]) + + expect([...harness.tools.keys()].sort()).toEqual([ + 'change_title', + 'display_image', + 'inspect_peer', + 'list_peers', + 'ping_peer', + 'session_job', + ].sort()) + }) + it.each(['auto', 'queue', 'steer'])('advertises and forwards ping_peer delivery mode %s', async (deliveryMode) => { await runHappyMcpStdioBridge(['--url', 'http://127.0.0.1:43006', '--tools', 'ping_peer']) const schema = harness.configs.get('ping_peer')?.inputSchema as { @@ -234,6 +256,7 @@ describe('runHappyMcpStdioBridge tool forwarding', () => { 'display_image', 'display_video', 'display_media', + 'session_job', 'ping_peer', 'spawn_peer', 'inspect_peer', @@ -247,11 +270,13 @@ describe('runHappyMcpStdioBridge tool forwarding', () => { try { await runHappyMcpStdioBridge(['--url', 'http://127.0.0.1:43006']) + // session_job is own-session — kept when peer tools are stripped. expect([...harness.tools.keys()]).toEqual([ 'change_title', 'display_image', 'display_video', - 'display_media' + 'display_media', + 'session_job', ]) } finally { delete process.env.HAPI_DISABLE_PEER_TOOLS diff --git a/cli/src/codex/happyMcpStdioBridge.ts b/cli/src/codex/happyMcpStdioBridge.ts index e0ccdb95..225eabe9 100644 --- a/cli/src/codex/happyMcpStdioBridge.ts +++ b/cli/src/codex/happyMcpStdioBridge.ts @@ -33,8 +33,23 @@ import { SESSION_NAME_MAX_LENGTH } from '@hapi/protocol'; import { CREATABLE_AGENT_FLAVORS } from '@hapi/protocol/modes'; import { PermissionModeSchema } from '@hapi/protocol/schemas'; import { isPeerToolsDisabled, PEER_TOOL_NAMES } from '@/modules/common/peerTools'; +import { + SESSION_JOB_TOOL_DESCRIPTION, + SESSION_JOB_TOOL_NAME, + sessionJobInputSchema, +} from '@/modules/sessionJob/sessionJobMcp'; -const DEFAULT_TOOL_NAMES = ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer']; +const DEFAULT_TOOL_NAMES = [ + 'change_title', + 'display_image', + 'display_video', + 'display_media', + 'list_peers', + 'ping_peer', + 'inspect_peer', + 'spawn_peer', + SESSION_JOB_TOOL_NAME, +]; function parseArgs(argv: string[]): { url: string | null; toolNames: Set } { let url: string | null = null; @@ -219,6 +234,34 @@ export async function runHappyMcpStdioBridge(argv: string[]): Promise { ); } + if (toolNames.has(SESSION_JOB_TOOL_NAME)) { + server.registerTool( + SESSION_JOB_TOOL_NAME, + { + description: SESSION_JOB_TOOL_DESCRIPTION, + title: 'Session-Attached Job', + inputSchema: sessionJobInputSchema, + }, + async (args: Record) => { + try { + const client = await ensureHttpClient(); + const response = await client.callTool({ name: SESSION_JOB_TOOL_NAME, arguments: args }); + return response as any; + } catch (error) { + return { + content: [ + { + type: 'text' as const, + text: `Failed to run session_job: ${error instanceof Error ? error.message : String(error)}`, + }, + ], + isError: true, + }; + } + } + ); + } + const pingPeerInputSchema: z.ZodTypeAny = z.object({ sessionIdPrefix: z.string().trim().min(1).describe(SESSION_ID_PREFIX_PARAM_DESCRIPTION), message: z.string().min(1).describe('Message text to deliver to the target session'), diff --git a/cli/src/codex/utils/appServerConfig.test.ts b/cli/src/codex/utils/appServerConfig.test.ts index 2a45177e..9c002c6b 100644 --- a/cli/src/codex/utils/appServerConfig.test.ts +++ b/cli/src/codex/utils/appServerConfig.test.ts @@ -7,7 +7,7 @@ import { codexCollaborationSpawnAgentInstructions, supportsReasoningSummary } from './appServerConfig'; -import { codexSystemPrompt } from './systemPrompt'; +import { getCodexSystemPrompt } from './systemPrompt'; describe('appServerConfig', () => { const mcpServers = { hapi: { command: 'node', args: ['mcp'] } }; @@ -23,7 +23,7 @@ describe('appServerConfig', () => { }); expect(params).not.toHaveProperty('baseInstructions'); - expect(params.developerInstructions).toBe(codexSystemPrompt); + expect(params.developerInstructions).toBe(getCodexSystemPrompt()); }); it('keeps an explicit base instruction override separate from HAPI developer instructions', () => { @@ -35,7 +35,7 @@ describe('appServerConfig', () => { }); expect(params.baseInstructions).toBe('Custom base instructions.'); - expect(params.developerInstructions).toBe(codexSystemPrompt); + expect(params.developerInstructions).toBe(getCodexSystemPrompt()); }); it('applies CLI overrides when permission mode is default', () => { @@ -50,13 +50,13 @@ describe('appServerConfig', () => { expect(params.sandbox).toBe('danger-full-access'); expect(params.approvalPolicy).toBe('never'); expect(params.baseInstructions).toBeUndefined(); - expect(params.developerInstructions).toBe(codexSystemPrompt); + expect(params.developerInstructions).toBe(getCodexSystemPrompt()); expect(params.config).toEqual({ 'mcp_servers.hapi': { command: 'node', args: ['mcp'] }, - developer_instructions: codexSystemPrompt + developer_instructions: getCodexSystemPrompt() }); }); @@ -98,7 +98,7 @@ describe('appServerConfig', () => { } } }, - developer_instructions: codexSystemPrompt + developer_instructions: getCodexSystemPrompt() }); }); @@ -184,13 +184,13 @@ describe('appServerConfig', () => { }); expect(params.baseInstructions).toBeUndefined(); - expect(params.developerInstructions).toBe(`${codexSystemPrompt}\n\nOnly respond in Chinese.`); + expect(params.developerInstructions).toBe(`${getCodexSystemPrompt()}\n\nOnly respond in Chinese.`); expect(params.config).toEqual({ 'mcp_servers.hapi': { command: 'node', args: ['mcp'] }, - developer_instructions: `${codexSystemPrompt}\n\nOnly respond in Chinese.` + developer_instructions: `${getCodexSystemPrompt()}\n\nOnly respond in Chinese.` }); }); @@ -206,7 +206,7 @@ describe('appServerConfig', () => { command: 'node', args: ['mcp'] }, - developer_instructions: codexSystemPrompt, + developer_instructions: getCodexSystemPrompt(), model_reasoning_effort: 'ultra' }); }); @@ -372,7 +372,7 @@ describe('appServerConfig', () => { settings: { model: 'o3', reasoning_effort: 'high', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); expect(params.model).toBeUndefined(); @@ -398,7 +398,7 @@ describe('appServerConfig', () => { settings: { model: 'gpt-5.3-codex-spark', reasoning_effort: 'high', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); }); @@ -562,7 +562,7 @@ describe('appServerConfig', () => { mode: 'default', settings: { model: 'o3', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); }); @@ -582,7 +582,7 @@ describe('appServerConfig', () => { mode: 'default', settings: { model: 'o3', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); }); @@ -601,7 +601,7 @@ describe('appServerConfig', () => { mode: 'default', settings: { model: 'gpt-5', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); expect(params.model).toBeUndefined(); diff --git a/cli/src/codex/utils/buildHapiMcpBridge.test.ts b/cli/src/codex/utils/buildHapiMcpBridge.test.ts index ad66b538..f5012502 100644 --- a/cli/src/codex/utils/buildHapiMcpBridge.test.ts +++ b/cli/src/codex/utils/buildHapiMcpBridge.test.ts @@ -14,8 +14,8 @@ vi.mock('@/claude/utils/startHappyServer', () => ({ return { url: 'http://127.0.0.1:43006/', toolNames: options.skillLookup - ? ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'skill_lookup'] - : ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'], + ? ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'session_job', 'skill_lookup'] + : ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'session_job'], stop: vi.fn() } }) @@ -73,16 +73,17 @@ describe('buildHapiMcpBridge skill lookup config', () => { '--url', 'http://127.0.0.1:43006/', '--tools', - 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,skill_lookup', + 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,session_job,skill_lookup', '--hapi-session-id', 'hub-session-1', ]) expect(bridge.mcpServers.hapi.tools).toEqual({ - change_title: { approval_mode: 'approve' }, display_image: { approval_mode: 'prompt' }, display_video: { approval_mode: 'prompt' }, display_media: { approval_mode: 'prompt' }, + change_title: { approval_mode: 'approve' }, list_peers: { approval_mode: 'approve' }, + session_job: { approval_mode: 'approve' }, skill_lookup: { approval_mode: 'approve' } }) }) @@ -95,16 +96,17 @@ describe('buildHapiMcpBridge skill lookup config', () => { '--url', 'http://127.0.0.1:43006/', '--tools', - 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer', + 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,session_job', '--hapi-session-id', 'hub-session-1', ]) expect(bridge.mcpServers.hapi.tools).toEqual({ - change_title: { approval_mode: 'approve' }, display_image: { approval_mode: 'prompt' }, display_video: { approval_mode: 'prompt' }, display_media: { approval_mode: 'prompt' }, - list_peers: { approval_mode: 'approve' } + change_title: { approval_mode: 'approve' }, + list_peers: { approval_mode: 'approve' }, + session_job: { approval_mode: 'approve' } }) }) diff --git a/cli/src/codex/utils/buildHapiMcpBridge.ts b/cli/src/codex/utils/buildHapiMcpBridge.ts index 085e41d6..d41928dd 100644 --- a/cli/src/codex/utils/buildHapiMcpBridge.ts +++ b/cli/src/codex/utils/buildHapiMcpBridge.ts @@ -124,6 +124,10 @@ export async function buildHapiMcpBridge( approval_mode: 'approve' }; } + // Own-session progress meter (tiann/hapi#1404) — hub REST, not peer inject. + tools.session_job = { + approval_mode: 'approve' + }; // ping_peer / inspect_peer / spawn_peer are registered on the HTTP MCP // server / stdio bridge, but are not auto-approved: they target another // session (resume + inject, read peer histories, or create + inject). diff --git a/cli/src/codex/utils/systemPrompt.ts b/cli/src/codex/utils/systemPrompt.ts index 8ed6b658..cdab5534 100644 --- a/cli/src/codex/utils/systemPrompt.ts +++ b/cli/src/codex/utils/systemPrompt.ts @@ -9,6 +9,7 @@ import { trimIdent } from '@/utils/trimIdent'; import { buildSessionCitationSteerInstruction, SESSION_CITATION_DISABLED_STEER } from '@hapi/protocol/sessionCitation'; import { DISPLAY_IMAGE_PROMPT_CODEX, DISPLAY_MEDIA_PROMPT_CODEX, DISPLAY_VIDEO_PROMPT_CODEX } from '@/modules/common/displayImagePrompt'; import { isPeerToolsDisabled } from '@/modules/common/peerTools'; +import { withSessionJobInstruction } from '@/modules/common/sessionJobInstruction'; import { withSessionSummaryInstruction } from '@/modules/common/sessionSummaryInstruction'; /** @@ -38,7 +39,7 @@ export const TITLE_INSTRUCTION = trimIdent(` * Session-summary contract is resolved at call time (hub toggle / env). */ export function getCodexSystemPrompt(env: NodeJS.ProcessEnv = process.env): string { - return withSessionSummaryInstruction(TITLE_INSTRUCTION, env) + return withSessionSummaryInstruction(withSessionJobInstruction(TITLE_INSTRUCTION), env) } /** Alias kept for existing call sites / tests that expect a string constant name. */ diff --git a/cli/src/commands/job.test.ts b/cli/src/commands/job.test.ts new file mode 100644 index 00000000..7b8a1133 --- /dev/null +++ b/cli/src/commands/job.test.ts @@ -0,0 +1,360 @@ +import { describe, expect, it } from 'vitest' +import { formatJobLine, parseJobArgs } from '@/commands/job' +import { + SessionJobError, + exitCodeForSessionJobError, + resolveSessionByPrefix, + resolveSessionIdForJobCli +} from '@/modules/sessionJob/sessionJob' + +describe('parseJobArgs', () => { + it('parses set with long flags', () => { + const parsed = parseJobArgs([ + 'set', + 'abcd1234', + 'beets', + '--label', + 'beets import', + '--progress=fraction', + '--remaining', + '12', + '--total', + '100', + '--unit=tracks' + ]) + expect(parsed.action).toBe('set') + expect(parsed.sessionIdPrefix).toBe('abcd1234') + expect(parsed.jobKey).toBe('beets') + expect(parsed.label).toBe('beets import') + expect(parsed.progress).toBe('fraction') + expect(parsed.remaining).toBe(12) + expect(parsed.total).toBe(100) + expect(parsed.unit).toBe('tracks') + }) + + it('parses run with command after --', () => { + const parsed = parseJobArgs([ + 'run', + 'sid', + 'drain', + '--label=rsync', + '--progress=unknown', + '--heartbeat-sec=60', + '--', + 'bash', + '-c', + 'echo hi' + ]) + expect(parsed.action).toBe('run') + expect(parsed.label).toBe('rsync') + expect(parsed.progress).toBe('unknown') + expect(parsed.heartbeatSec).toBe(60) + expect(parsed.command).toEqual(['bash', '-c', 'echo hi']) + }) + + it('parses wake-on-terminal flags', () => { + const parsed = parseJobArgs([ + 'run', + 'sid', + 'drain', + '--label=rsync', + '--progress=unknown', + '--wake-on-terminal', + '--wake-prompt=Next chunk', + '--', + 'true' + ]) + expect(parsed.wakeOnTerminal).toBe(true) + expect(parsed.wakePrompt).toBe('Next chunk') + expect(parsed.command).toEqual(['true']) + }) + + it('requires --progress on run/set and stamps until mode', () => { + expect(() => parseJobArgs([ + 'run', + 'sid', + 'drain', + '--label=rsync', + '--', + 'true' + ])).toThrow(/requires --progress/) + + const until = parseJobArgs([ + 'run', + 'sid', + 'dogfood', + '--label=countdown', + '--progress=until', + '--until=2099-01-01T00:00:00.000Z', + '--', + 'sleep', + '1' + ]) + expect(until.progress).toBe('until') + expect(until.untilMs).toBe(Date.parse('2099-01-01T00:00:00.000Z')) + expect(until.remaining).toBeGreaterThan(0) + expect(until.total).toBe(until.remaining) + expect(until.unit).toBe('s') + }) + + it('parses --wake-on-terminal and --wake-prompt on update (dogfood arm-later)', () => { + const parsed = parseJobArgs([ + 'update', + 'sid', + 'oos-llm-from-studio', + '--done', + '1', + '--total', + '2', + '--wake-on-terminal', + '--wake-prompt', + 'delete studio dupes' + ]) + expect(parsed.action).toBe('update') + expect(parsed.wakeOnTerminal).toBe(true) + expect(parsed.wakePrompt).toBe('delete studio dupes') + expect(parsed.done).toBe(1) + expect(parsed.total).toBe(2) + }) + + it('rejects --wake-prompt without a value', () => { + expect(() => parseJobArgs([ + 'update', + 'sid', + 'k', + '--wake-on-terminal', + '--wake-prompt' + ])).toThrow(/--wake-prompt requires a value/) + }) + + it('rejects bad status', () => { + expect(() => parseJobArgs(['update', 's', 'k', '--status', 'nope'])).toThrow(SessionJobError) + }) + + it('parses --started-at for set', () => { + const parsed = parseJobArgs([ + 'set', + 'sid', + 'beets', + '--label=beets', + '--progress=unknown', + '--started-at=1785304595000' + ]) + expect(parsed.startedAt).toBe(1_785_304_595_000) + }) + + it('allows --started-at on until run and stamps full-window total', () => { + const until = Date.now() + 48 * 3600 * 1000 + const windowStart = until - 48 * 3600 * 1000 + const parsed = parseJobArgs([ + 'run', + 'sid', + 'dogfood', + '--label=countdown', + '--progress=until', + `--until=${until}`, + `--started-at=${windowStart}`, + '--', + 'sleep', + '999999' + ]) + expect(parsed.startedAt).toBe(windowStart) + expect(parsed.total).toBe(48 * 3600) + expect(parsed.remaining).toBeLessThanOrEqual(parsed.total!) + expect(parsed.remaining).toBeGreaterThan(47 * 3600) + }) + + it('rejects numeric sleep under --progress unknown', () => { + expect(() => parseJobArgs([ + 'run', + 'sid', + 'dogfood', + '--label=countdown', + '--progress=unknown', + '--', + 'sleep', + '150747' + ])).toThrow(/--progress until/) + }) + + it('rejects --started-at on update', () => { + expect(() => parseJobArgs([ + 'update', + 'sid', + 'beets', + '--started-at=1785304595000' + ])).toThrow(/--started-at is only valid with job set/) + }) + + it('rejects --started-at on unknown run', () => { + expect(() => parseJobArgs([ + 'run', + 'sid', + 'k', + '--label=x', + '--progress=unknown', + '--started-at=1785304595000', + '--', + 'true' + ])).toThrow(/only valid with --progress until/) + }) + + it('rejects --heartbeat-sec on non-run actions', () => { + expect(() => parseJobArgs([ + 'set', + 'sid', + 'beets', + '--label=beets', + '--progress=unknown', + '--heartbeat-sec=300' + ])).toThrow(/--heartbeat-sec is only valid with job run/) + expect(() => parseJobArgs([ + 'update', + 'sid', + 'beets', + '--heartbeat-sec=60' + ])).toThrow(/--heartbeat-sec is only valid with job run/) + }) + + it.each([ + ['list', ['list', 'sid', '--label=x'], /job list does not accept mutation flags/], + ['clear+status', ['clear', 'sid', 'beets', '--status', 'completed'], /job clear only accepts --expected-run-id/], + ['run+status', ['run', 'sid', 'beets', '--label=x', '--progress=unknown', '--status', 'completed', '--', 'true'], /--status is not valid with job run/], + ['clear+cmd', ['clear', 'sid', 'beets', '--', 'rm', '-rf', '/'], /-- is only valid with job run/] + ] as const)('rejects unsupported flags for %s', (_name, argv, pattern) => { + expect(() => parseJobArgs([...argv])).toThrow(pattern) + }) + + it('parses --clear-remaining as null for update patches', () => { + const parsed = parseJobArgs([ + 'update', + 'sid', + 'beets', + '--clear-remaining', + '--done', + '3', + '--total', + '10' + ]) + expect(parsed.remaining).toBeNull() + expect(parsed.done).toBe(3) + expect(parsed.total).toBe(10) + }) + + it('parses --run-id on set and --expected-run-id on update/clear', () => { + const setParsed = parseJobArgs([ + 'set', + 'sid', + 'beets', + '--label=beets', + '--progress=unknown', + '--run-id=11111111-1111-1111-1111-111111111111' + ]) + expect(setParsed.runId).toBe('11111111-1111-1111-1111-111111111111') + + const updateParsed = parseJobArgs([ + 'update', + 'sid', + 'beets', + '--remaining=9', + '--expected-run-id=11111111-1111-1111-1111-111111111111' + ]) + expect(updateParsed.expectedRunId).toBe('11111111-1111-1111-1111-111111111111') + + const clearParsed = parseJobArgs([ + 'clear', + 'sid', + 'beets', + '--expected-run-id=11111111-1111-1111-1111-111111111111' + ]) + expect(clearParsed.expectedRunId).toBe('11111111-1111-1111-1111-111111111111') + }) + + it('rejects --run-id on update and --expected-run-id on set', () => { + expect(() => parseJobArgs([ + 'update', + 'sid', + 'beets', + '--run-id=11111111-1111-1111-1111-111111111111' + ])).toThrow(/--run-id is only valid with job set/) + expect(() => parseJobArgs([ + 'set', + 'sid', + 'beets', + '--label=beets', + '--progress=unknown', + '--expected-run-id=11111111-1111-1111-1111-111111111111' + ])).toThrow(/--expected-run-id is only valid with job update or clear/) + }) +}) + +describe('resolveSessionByPrefix', () => { + const sessions = [ + { id: 'aaaaaaaa-1111-1111-1111-111111111111' }, + { id: 'bbbbbbbb-2222-2222-2222-222222222222' }, + { id: 'bbbbcccc-3333-3333-3333-333333333333' } + ] + + it('matches exact id', () => { + expect(resolveSessionByPrefix(sessions, sessions[0]!.id).id).toBe(sessions[0]!.id) + }) + + it('matches unique prefix', () => { + expect(resolveSessionByPrefix(sessions, 'aaaa').id).toBe(sessions[0]!.id) + }) + + it('errors on ambiguous prefix', () => { + expect(() => resolveSessionByPrefix(sessions, 'bbbb')).toThrow(/matches 2 sessions/) + }) + + it('errors on no match', () => { + expect(() => resolveSessionByPrefix(sessions, 'zzzz')).toThrow(/no session matching/) + }) +}) + +describe('resolveSessionIdForJobCli', () => { + it('passes a full UUID through when missing from the session list', () => { + const deleted = 'cccccccc-4444-4444-4444-444444444444' + expect(resolveSessionIdForJobCli([], deleted)).toBe(deleted) + }) + + it('still errors for a non-uuid prefix with no list match', () => { + expect(() => resolveSessionIdForJobCli([], 'deadbeef')).toThrow(/no session matching/) + }) +}) + +describe('exitCodeForSessionJobError', () => { + it('maps codes', () => { + expect(exitCodeForSessionJobError(new SessionJobError('bad_args', 'x'))).toBe(2) + expect(exitCodeForSessionJobError(new SessionJobError('auth_failed', 'x'))).toBe(3) + expect(exitCodeForSessionJobError(new SessionJobError('not_found', 'x'))).toBe(4) + expect(exitCodeForSessionJobError(new SessionJobError('ambiguous', 'x'))).toBe(5) + expect(exitCodeForSessionJobError(new SessionJobError('request_failed', 'x'))).toBe(1) + }) +}) + +describe('formatJobLine terminal sanitization', () => { + it('strips ANSI/OSC and C0 controls from job text fields', () => { + const line = formatJobLine({ + key: 'beets\u0007', + label: '\u001b[31mimport\u001b[0m', + status: 'running', + unit: 'tracks\u001b]8;;http://evil\u0007', + detail: 'phase\u001b]52;c;QUFB\u0007done\u009devil\u009c', + runId: 'run-\u001b[1mid\u001b[0m', + remaining: 3, + heartbeatAt: Date.now() - 5_000, + startedAt: Date.now() - 60_000 + }, { includeTiming: true }) + expect(line).not.toMatch(/\u001b/) + expect(line).not.toMatch(/[\u0000-\u001f\u007f-\u009f]/) + expect(line).toContain('beets') + expect(line).toContain('import') + expect(line).toContain('3 tracks left') + expect(line).toContain('phase') + expect(line).toContain('done') + expect(line).toContain('runId run-id') + expect(line).not.toMatch(/http:\/\/evil/) + expect(line).not.toMatch(/QUFB/) + }) +}) diff --git a/cli/src/commands/job.ts b/cli/src/commands/job.ts new file mode 100644 index 00000000..7e209f25 --- /dev/null +++ b/cli/src/commands/job.ts @@ -0,0 +1,628 @@ +import chalk from 'chalk' +import { initializeToken } from '@/ui/tokenInit' +import type { AttachedJobPatch, AttachedJobUpsert } from '@hapi/protocol' +import { + SessionJobError, + SESSION_JOB_REMAINING_ZERO_HINT, + clearSessionJob, + exitCodeForSessionJobError, + formatSessionJobNotFoundHint, + listSessionJobs, + setSessionJob, + updateSessionJob +} from '@/modules/sessionJob/sessionJob' +import { formatJobLine } from '@/modules/sessionJob/formatJobLine' +import { runSessionJob } from '@/modules/sessionJob/runSessionJob' +import { + assertCreateProgressMode, + assertNumericSleepUsesUntil, + type JobProgressMode, + parseUntilTimestamp, + stampUntilProgress +} from '@/modules/sessionJob/jobProgressMode' +import type { CommandDefinition } from './types' + +export { formatJobLine, terminalText } from '@/modules/sessionJob/formatJobLine' + +export type ParsedJobArgs = { + help: boolean + action?: 'set' | 'update' | 'clear' | 'list' | 'run' + sessionIdPrefix?: string + jobKey?: string + label?: string + status?: 'running' | 'completed' | 'failed' + progress?: JobProgressMode + untilMs?: number + done?: number | null + total?: number | null + remaining?: number | null + unit?: string | null + detail?: string | null + startedAt?: number + heartbeatSec?: number + runId?: string + expectedRunId?: string + wakeOnTerminal?: boolean + wakePrompt?: string + command?: string[] +} + +function showHelp(): void { + console.log(` +${chalk.bold('hapi job')} - Attach long-running work to a HAPI session (tiann/hapi#1404) + +${chalk.bold('When to use:')} + Work that outlives the agent (batch / long scripts / external daemons) + while the session may be idle. Not thinking progress or in-agent background tools. + +${chalk.bold('Agent contract:')} + Prefer ${chalk.bold('hapi job run')} — it heartbeats for you and marks completed/failed on exit. + An idle agent cannot heartbeat; set-once jobs go amber after ~15m. + ${chalk.bold('run/set require --progress')} unknown|fraction|until (explicit affordance). + unknown → indeterminate stripes (no counts). fraction → remaining+total or done+total. + until → --until ; remaining/total derived (job run heartbeats re-stamp remaining). + Fraction without a continuous updater freezes under heartbeats — keep + ${chalk.bold('job update')}ing done/remaining (or use --progress unknown). + Numeric ${chalk.bold('sleep N')} requires ${chalk.bold('--progress until')}. + Never invent a fake percent. + Do not wrap hapi-restart-hub / stack-switch in job run (hub down → zombie running meter). + +${chalk.bold('Usage:')} + hapi job run --label --progress unknown|fraction|until […] -- … + hapi job set --label --progress unknown|fraction|until […] + hapi job update [--expected-run-id UUID] [--remaining N] [--done N] [--total N] [--status running|completed|failed] [--wake-on-terminal] [--wake-prompt ] [--detail ...] + [--clear-remaining|--clear-done|--clear-total|--clear-unit|--clear-detail] + hapi job clear [--expected-run-id UUID] + hapi job list + +${chalk.bold('Wake on terminal (tiann/hapi#1489, default off):')} + --wake-on-terminal When the job hits completed/failed, hub resumes the owning + session and posts a prompt so an idle agent can continue. + --wake-prompt TEXT Optional prescription appended to the wake message. + +${chalk.bold('Progress UI (--progress):')} + unknown → "running · 2h" + subtle indeterminate striped bar (no %) + fraction → remaining+total or done+total → fill bar + until → determinate countdown from --until (unit s) + elapsed always from startedAt (wall clock) — never an ETA field + --clear-remaining → drop leftover meter so done/total can take over (PATCH null) + +${chalk.bold('startedAt / elapsed:')} + Prefer ${chalk.bold('update')} for heartbeats/progress so the clock is never wiped. + PATCH rejects startedAt. PUT/set without --started-at keeps the existing clock. + Late attach or wrong clock: ${chalk.bold('set --started-at ')} (explicit PUT), + or clear then set with --started-at (works on older hubs that ignored PUT corrections). + Mid-window countdown re-attach: ${chalk.bold('run --progress until --until … --started-at ')} + so heartbeat total stays until−start (not "time left from this restart"). + Manual babysitter wrappers: mint one UUID per run (${chalk.bold('set --run-id ')}), + then pass the same value on every heartbeat (${chalk.bold('update --expected-run-id ')}) + and on clear (${chalk.bold('clear --expected-run-id ')}) so a key-reuse cannot + steal the older wrapper's PATCHes or DELETE the newer run. + +${chalk.bold('Notes:')} + Hub-persisted. Prefer "$HAPI_SESSION_ID" when it matches the operator chat row + (/sessions/ in the web URL). Remote Cursor runner may export a worker-row id — + pass that URL uuid explicitly (see docs/guide/session-jobs.md). + Needs a hub/CLI that includes the job subcommand (soup / feat build — not every npm release). + Job key: 1-128 chars, alnum / . _ - + Session lookup prefers exact id; prefix scan is the 500 most-recently-updated sessions. + Docs: docs/guide/session-jobs.md + +${chalk.bold('Env:')} + HAPI_API_URL / CLI_API_TOKEN (or ~/.hapi/settings.json via \`hapi auth login\`) +`) +} + +function parseOptionalNumber(flag: string, value: string | undefined): number { + if (value === undefined) { + throw new SessionJobError('bad_args', `${flag} requires a number`) + } + const n = Number(value) + if (!Number.isFinite(n)) { + throw new SessionJobError('bad_args', `${flag} must be a number`) + } + return n +} + +export function parseJobArgs(args: string[]): ParsedJobArgs { + const result: ParsedJobArgs = { help: false } + const dashDash = args.indexOf('--') + const flagArgs = dashDash >= 0 ? args.slice(0, dashDash) : args + if (dashDash >= 0) { + result.command = args.slice(dashDash + 1) + } + + for (let i = 0; i < flagArgs.length; i++) { + const arg = flagArgs[i]! + if (arg === '--help' || arg === '-h') { + result.help = true + continue + } + if (arg === '--label') { + result.label = flagArgs[++i] + if (!result.label) throw new SessionJobError('bad_args', '--label requires a value') + continue + } + if (arg.startsWith('--label=')) { + result.label = arg.slice('--label='.length) + continue + } + if (arg === '--status') { + const value = flagArgs[++i] + if (value !== 'running' && value !== 'completed' && value !== 'failed') { + throw new SessionJobError('bad_args', '--status must be running|completed|failed') + } + result.status = value + continue + } + if (arg.startsWith('--status=')) { + const value = arg.slice('--status='.length) + if (value !== 'running' && value !== 'completed' && value !== 'failed') { + throw new SessionJobError('bad_args', '--status must be running|completed|failed') + } + result.status = value + continue + } + if (arg === '--done') { + result.done = parseOptionalNumber('--done', flagArgs[++i]) + continue + } + if (arg.startsWith('--done=')) { + result.done = parseOptionalNumber('--done', arg.slice('--done='.length)) + continue + } + if (arg === '--total') { + result.total = parseOptionalNumber('--total', flagArgs[++i]) + continue + } + if (arg.startsWith('--total=')) { + result.total = parseOptionalNumber('--total', arg.slice('--total='.length)) + continue + } + if (arg === '--remaining') { + result.remaining = parseOptionalNumber('--remaining', flagArgs[++i]) + continue + } + if (arg.startsWith('--remaining=')) { + result.remaining = parseOptionalNumber('--remaining', arg.slice('--remaining='.length)) + continue + } + if (arg === '--unit') { + result.unit = flagArgs[++i] + if (!result.unit) throw new SessionJobError('bad_args', '--unit requires a value') + continue + } + if (arg.startsWith('--unit=')) { + result.unit = arg.slice('--unit='.length) + continue + } + if (arg === '--detail') { + result.detail = flagArgs[++i] + if (result.detail === undefined) throw new SessionJobError('bad_args', '--detail requires a value') + continue + } + if (arg.startsWith('--detail=')) { + result.detail = arg.slice('--detail='.length) + continue + } + if (arg === '--heartbeat-sec') { + result.heartbeatSec = parseOptionalNumber('--heartbeat-sec', flagArgs[++i]) + continue + } + if (arg.startsWith('--heartbeat-sec=')) { + result.heartbeatSec = parseOptionalNumber('--heartbeat-sec', arg.slice('--heartbeat-sec='.length)) + continue + } + if (arg === '--started-at') { + result.startedAt = parseOptionalNumber('--started-at', flagArgs[++i]) + continue + } + if (arg.startsWith('--started-at=')) { + result.startedAt = parseOptionalNumber('--started-at', arg.slice('--started-at='.length)) + continue + } + if (arg === '--clear-remaining') { + result.remaining = null + continue + } + if (arg === '--clear-done') { + result.done = null + continue + } + if (arg === '--clear-total') { + result.total = null + continue + } + if (arg === '--clear-unit') { + result.unit = null + continue + } + if (arg === '--clear-detail') { + result.detail = null + continue + } + if (arg === '--run-id') { + result.runId = flagArgs[++i] + if (!result.runId) throw new SessionJobError('bad_args', '--run-id requires a value') + continue + } + if (arg.startsWith('--run-id=')) { + result.runId = arg.slice('--run-id='.length) + if (!result.runId) throw new SessionJobError('bad_args', '--run-id requires a value') + continue + } + if (arg === '--expected-run-id') { + result.expectedRunId = flagArgs[++i] + if (!result.expectedRunId) { + throw new SessionJobError('bad_args', '--expected-run-id requires a value') + } + continue + } + if (arg.startsWith('--expected-run-id=')) { + result.expectedRunId = arg.slice('--expected-run-id='.length) + if (!result.expectedRunId) { + throw new SessionJobError('bad_args', '--expected-run-id requires a value') + } + continue + } + if (arg === '--wake-on-terminal') { + result.wakeOnTerminal = true + continue + } + if (arg === '--wake-prompt') { + result.wakePrompt = flagArgs[++i] + if (result.wakePrompt === undefined) { + throw new SessionJobError('bad_args', '--wake-prompt requires a value') + } + continue + } + if (arg.startsWith('--wake-prompt=')) { + result.wakePrompt = arg.slice('--wake-prompt='.length) + continue + } + if (arg === '--progress') { + const value = flagArgs[++i] + if (value !== 'unknown' && value !== 'fraction' && value !== 'until') { + throw new SessionJobError('bad_args', '--progress must be unknown|fraction|until') + } + result.progress = value + continue + } + if (arg.startsWith('--progress=')) { + const value = arg.slice('--progress='.length) + if (value !== 'unknown' && value !== 'fraction' && value !== 'until') { + throw new SessionJobError('bad_args', '--progress must be unknown|fraction|until') + } + result.progress = value + continue + } + if (arg === '--until') { + const value = flagArgs[++i] + if (value === undefined) { + throw new SessionJobError('bad_args', '--until requires a value') + } + result.untilMs = parseUntilTimestamp(value) + continue + } + if (arg.startsWith('--until=')) { + result.untilMs = parseUntilTimestamp(arg.slice('--until='.length)) + continue + } + if (arg.startsWith('-')) { + throw new SessionJobError('bad_args', `unexpected flag: ${arg}`) + } + if (!result.action) { + if ( + arg !== 'set' + && arg !== 'update' + && arg !== 'clear' + && arg !== 'list' + && arg !== 'run' + ) { + throw new SessionJobError('bad_args', `unknown action '${arg}' (set|update|clear|list|run)`) + } + result.action = arg + continue + } + if (!result.sessionIdPrefix) { + result.sessionIdPrefix = arg + continue + } + if (!result.jobKey && result.action !== 'list') { + result.jobKey = arg + continue + } + throw new SessionJobError('bad_args', `unexpected arg: ${arg}`) + } + + if (result.startedAt !== undefined && result.action !== undefined) { + if (result.action === 'set') { + // ok — correct historical clock / window start + } else if (result.action === 'run' && result.progress === 'until') { + // ok — mid-window countdown: heartbeats keep total = until - startedAt + } else if (result.action === 'run') { + throw new SessionJobError( + 'bad_args', + '--started-at on job run is only valid with --progress until ' + + '(pass the window start so total stays honest across re-attach)' + ) + } else { + throw new SessionJobError( + 'bad_args', + '--started-at is only valid with job set, or job run --progress until' + ) + } + } + + if ( + result.heartbeatSec !== undefined + && result.action !== undefined + && result.action !== 'run' + ) { + throw new SessionJobError('bad_args', '--heartbeat-sec is only valid with job run') + } + + const clearUsed = + result.done === null + || result.total === null + || result.remaining === null + || result.unit === null + || result.detail === null + if (clearUsed && result.action !== undefined && result.action !== 'update') { + throw new SessionJobError('bad_args', '--clear-* flags are only valid with job update') + } + if (result.runId !== undefined && result.action !== undefined && result.action !== 'set') { + throw new SessionJobError('bad_args', '--run-id is only valid with job set') + } + if ( + result.expectedRunId !== undefined + && result.action !== undefined + && result.action !== 'update' + && result.action !== 'clear' + ) { + throw new SessionJobError('bad_args', '--expected-run-id is only valid with job update or clear') + } + + const mutationFieldsUsed = [ + result.label, + result.status, + result.done, + result.total, + result.remaining, + result.unit, + result.detail + ].some((value) => value !== undefined) + + if (result.action === 'list' && mutationFieldsUsed) { + throw new SessionJobError('bad_args', 'job list does not accept mutation flags') + } + if (result.action === 'clear' && mutationFieldsUsed) { + throw new SessionJobError('bad_args', 'job clear only accepts --expected-run-id') + } + if (result.action === 'run' && result.status !== undefined) { + throw new SessionJobError('bad_args', '--status is not valid with job run') + } + + if ( + result.command !== undefined + && result.action !== undefined + && result.action !== 'run' + ) { + throw new SessionJobError('bad_args', '-- is only valid with job run') + } + + if ( + (result.progress !== undefined || result.untilMs !== undefined) + && result.action !== undefined + && result.action !== 'run' + && result.action !== 'set' + ) { + throw new SessionJobError('bad_args', '--progress/--until are only valid with job run or set') + } + + if (result.action === 'run' || result.action === 'set') { + assertCreateProgressMode(result.action, { + progress: result.progress, + untilMs: result.untilMs, + done: result.done, + total: result.total, + remaining: result.remaining + }) + if (result.progress === 'until' && result.untilMs !== undefined) { + const startedAt = result.startedAt ?? Date.now() + const stamped = stampUntilProgress(result.untilMs, Date.now(), startedAt) + result.remaining = stamped.remaining + result.total = stamped.total + result.unit = result.unit ?? stamped.unit + } + if (result.action === 'run' && result.command) { + assertNumericSleepUsesUntil(result.progress!, result.command) + } + } + + return result +} + +function formatCliJobLine(job: { + key: string + label: string + status: string + done?: number + total?: number + remaining?: number + unit?: string + detail?: string + runId?: string + heartbeatAt: number + startedAt: number +}): string { + return formatJobLine(job, { includeTiming: true }) +} + +export async function handleJobCommand(args: string[]): Promise { + const parsed = parseJobArgs(args) + if (parsed.help || !parsed.action) { + showHelp() + if (!parsed.action && !parsed.help) { + throw new SessionJobError('bad_args', 'missing action; usage: hapi job set|update|clear|list|run ...') + } + return + } + + await initializeToken() + + if (!parsed.sessionIdPrefix) { + showHelp() + throw new SessionJobError('bad_args', 'missing session id') + } + + if (parsed.action === 'list') { + const result = await listSessionJobs({ sessionIdPrefix: parsed.sessionIdPrefix }) + console.log(`session ${result.sessionId}`) + if (result.jobs.length === 0) { + console.log('(no jobs)') + return + } + for (const job of result.jobs) { + const mark = result.primary?.key === job.key ? '*' : ' ' + console.log(`${mark} ${formatCliJobLine(job)}`) + } + return + } + + if (!parsed.jobKey) { + throw new SessionJobError('bad_args', 'missing job key') + } + + if (parsed.action === 'clear') { + const result = await clearSessionJob({ + sessionIdPrefix: parsed.sessionIdPrefix, + jobKey: parsed.jobKey, + ...(parsed.expectedRunId !== undefined + ? { expectedRunId: parsed.expectedRunId } + : {}) + }) + console.log(`cleared ${parsed.jobKey} on ${result.sessionId}`) + return + } + + if (parsed.action === 'set') { + if (!parsed.label) { + throw new SessionJobError('bad_args', 'set requires --label') + } + if (parsed.startedAt !== undefined && !Number.isFinite(parsed.startedAt)) { + throw new SessionJobError('bad_args', '--started-at must be epoch milliseconds') + } + // --progress already asserted + until stamped in parseJobArgs + const body: AttachedJobUpsert = { + label: parsed.label, + status: parsed.status ?? 'running', + ...(typeof parsed.done === 'number' ? { done: parsed.done } : {}), + ...(typeof parsed.total === 'number' ? { total: parsed.total } : {}), + ...(typeof parsed.remaining === 'number' ? { remaining: parsed.remaining } : {}), + ...(typeof parsed.unit === 'string' ? { unit: parsed.unit } : {}), + ...(typeof parsed.detail === 'string' ? { detail: parsed.detail } : {}), + ...(parsed.startedAt !== undefined ? { startedAt: parsed.startedAt } : {}), + ...(parsed.runId !== undefined ? { runId: parsed.runId } : {}), + ...(parsed.wakeOnTerminal !== undefined ? { wakeOnTerminal: parsed.wakeOnTerminal } : {}), + ...(parsed.wakePrompt !== undefined ? { wakePrompt: parsed.wakePrompt } : {}) + } + const result = await setSessionJob({ + sessionIdPrefix: parsed.sessionIdPrefix, + jobKey: parsed.jobKey, + body + }) + console.log(`set ${formatCliJobLine(result.job)}`) + return + } + + if (parsed.action === 'run') { + if (!parsed.label) { + throw new SessionJobError('bad_args', 'run requires --label') + } + if (!parsed.command || parsed.command.length === 0) { + throw new SessionJobError('bad_args', 'run requires a command after --') + } + if (parsed.startedAt !== undefined && !Number.isFinite(parsed.startedAt)) { + throw new SessionJobError('bad_args', '--started-at must be epoch milliseconds') + } + const exitCode = await runSessionJob({ + sessionIdPrefix: parsed.sessionIdPrefix, + jobKey: parsed.jobKey, + label: parsed.label, + command: parsed.command, + ...(parsed.heartbeatSec !== undefined + ? { heartbeatMs: Math.max(5, parsed.heartbeatSec) * 1000 } + : {}), + ...(typeof parsed.done === 'number' ? { done: parsed.done } : {}), + ...(typeof parsed.total === 'number' ? { total: parsed.total } : {}), + ...(typeof parsed.remaining === 'number' ? { remaining: parsed.remaining } : {}), + ...(typeof parsed.unit === 'string' ? { unit: parsed.unit } : {}), + ...(typeof parsed.detail === 'string' ? { detail: parsed.detail } : {}), + ...(parsed.untilMs !== undefined ? { untilMs: parsed.untilMs } : {}), + ...(parsed.startedAt !== undefined ? { startedAtMs: parsed.startedAt } : {}), + ...(parsed.wakeOnTerminal !== undefined ? { wakeOnTerminal: parsed.wakeOnTerminal } : {}), + ...(parsed.wakePrompt !== undefined ? { wakePrompt: parsed.wakePrompt } : {}) + }) + if (exitCode !== 0) { + process.exitCode = exitCode + } + console.log(`run finished exit=${exitCode} job=${parsed.jobKey}`) + return + } + + // update + const body: AttachedJobPatch = { + ...(parsed.label !== undefined ? { label: parsed.label } : {}), + ...(parsed.status !== undefined ? { status: parsed.status } : {}), + ...(parsed.done !== undefined ? { done: parsed.done } : {}), + ...(parsed.total !== undefined ? { total: parsed.total } : {}), + ...(parsed.remaining !== undefined ? { remaining: parsed.remaining } : {}), + ...(parsed.unit !== undefined ? { unit: parsed.unit } : {}), + ...(parsed.detail !== undefined ? { detail: parsed.detail } : {}), + ...(parsed.expectedRunId !== undefined ? { expectedRunId: parsed.expectedRunId } : {}), + ...(parsed.wakeOnTerminal !== undefined ? { wakeOnTerminal: parsed.wakeOnTerminal } : {}), + ...(parsed.wakePrompt !== undefined ? { wakePrompt: parsed.wakePrompt } : {}) + } + // Empty body is a heartbeat-only update; hub stamps heartbeatAt. + let result + try { + result = await updateSessionJob({ + sessionIdPrefix: parsed.sessionIdPrefix, + jobKey: parsed.jobKey, + body + }) + } catch (error) { + if (error instanceof SessionJobError && error.code === 'not_found') { + throw new SessionJobError('not_found', formatSessionJobNotFoundHint('update')) + } + throw error + } + console.log(`updated ${formatCliJobLine(result.job)}`) + if (result.job.status === 'running' && result.job.remaining === 0) { + console.error(chalk.yellow('hapi job hint:'), SESSION_JOB_REMAINING_ZERO_HINT) + } +} + +export const jobCommand: CommandDefinition = { + name: 'job', + requiresRuntimeAssets: false, + run: async ({ commandArgs }) => { + try { + await handleJobCommand(commandArgs) + } catch (error) { + if (error instanceof SessionJobError) { + console.error(chalk.red('hapi job:'), error.message) + process.exit(exitCodeForSessionJobError(error)) + } + console.error( + chalk.red('hapi job:'), + error instanceof Error ? error.message : 'Unknown error' + ) + if (process.env.DEBUG) { + console.error(error) + } + process.exit(1) + } + } +} diff --git a/cli/src/commands/registry.ts b/cli/src/commands/registry.ts index 8fa70881..b396166c 100644 --- a/cli/src/commands/registry.ts +++ b/cli/src/commands/registry.ts @@ -24,6 +24,7 @@ import { inspectPeerCommand } from './inspectPeer' import { spawnPeerCommand } from './spawnPeer' import { usageCommand } from './usage' import { setModeCommand } from './setMode' +import { jobCommand } from './job' import type { CommandContext, CommandDefinition } from './types' // Gemini CLI was sunset (Google stopped serving the consumer Gemini CLI on @@ -68,6 +69,7 @@ const COMMANDS: CommandDefinition[] = [ inspectPeerCommand, spawnPeerCommand, setModeCommand, + jobCommand, usageCommand ] diff --git a/cli/src/cursor/cursorAcpRemoteLauncher.test.ts b/cli/src/cursor/cursorAcpRemoteLauncher.test.ts index 3911159a..29c632c6 100644 --- a/cli/src/cursor/cursorAcpRemoteLauncher.test.ts +++ b/cli/src/cursor/cursorAcpRemoteLauncher.test.ts @@ -44,7 +44,7 @@ const harness = vi.hoisted(() => ({ stderrErrorHandler: null as ((error: { type: string; message: string; raw?: string }) => void) | null, disconnectError: null as Error | null, overlayCleanup: null as ReturnType | null, - agentActivityListener: null as ((thinking: boolean) => void) | null, + agentActivityListener: null as ((thinking: boolean, source?: string) => void) | null, titleSyncControllers: [] as unknown[], titleSyncRegistered: [] as unknown[], onChangeTitle: null as ((title: string) => void) | null, @@ -235,7 +235,7 @@ vi.mock('./utils/cursorAcpBackend', () => ({ harness.stderrErrorHandler = handler ?? null; }), setUsageUpdateListener: vi.fn(), - setAgentActivityListener: vi.fn((listener: ((thinking: boolean) => void) | null) => { + setAgentActivityListener: vi.fn((listener: ((thinking: boolean, source?: string) => void) | null) => { harness.agentActivityListener = listener; }), setSessionInfoUpdateListener: vi.fn(), @@ -776,7 +776,7 @@ describe('cursorAcpRemoteLauncher', () => { expect(session.model).toBe('auto'); }); - it('applies harness thinking transitions once per edge (#1470)', async () => { + it('ignores ambient state_update_running without a prompt; still applies idle/permission (#1553)', async () => { const keepAlive = vi.fn(); const queue = new MessageQueue2(() => 'mode'); const client = { @@ -797,20 +797,74 @@ describe('cursorAcpRemoteLauncher', () => { permissionMode: 'default' }); session.onSessionFoundWithProtocol = vi.fn(); - // Keep the launcher in the main loop long enough to wire the listener. const runPromise = cursorAcpRemoteLauncher(session); await vi.waitFor(() => expect(harness.agentActivityListener).not.toBeNull()); expect(session.thinking).toBe(false); keepAlive.mockClear(); - harness.agentActivityListener!(true); - harness.agentActivityListener!(true); - harness.agentActivityListener!(false); - + // Ambient Cursor chatter while queue-idle must not float Working. + harness.agentActivityListener!(true, 'state_update_running'); expect(session.thinking).toBe(false); - expect(keepAlive.mock.calls.map((call) => call[0])).toEqual([true, false]); + expect(keepAlive).not.toHaveBeenCalled(); + harness.agentActivityListener!(true, 'permission'); + expect(session.thinking).toBe(true); + expect(keepAlive).toHaveBeenCalled(); + + keepAlive.mockClear(); + harness.agentActivityListener!(false, 'state_update_idle'); + expect(session.thinking).toBe(false); + expect(keepAlive).toHaveBeenCalled(); + + queue.close(); + await runPromise; + }); + + it('applies state_update_running while a prompt is in flight (#1470)', async () => { + const keepAlive = vi.fn(); + const queue = new MessageQueue2(() => 'mode'); + const client = { + ...makeClient(), + keepAlive + } as unknown as ApiSessionClient; + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn(); + + harness.deferPrompt = new Promise((resolve) => { + harness.releasePrompt = resolve; + }); + queue.push('do work', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.promptCalls).toBeGreaterThan(0)); + await vi.waitFor(() => expect(harness.agentActivityListener).not.toBeNull()); + + // Prompt start already set thinking; clear so we can assert the listener edge. + session.onThinkingChange(false); + keepAlive.mockClear(); + harness.agentActivityListener!(true, 'state_update_running'); + expect(session.thinking).toBe(true); + expect(keepAlive).toHaveBeenCalled(); + + harness.agentActivityListener!(true, 'state_update_requires_action'); + expect(session.thinking).toBe(true); + + harness.releasePrompt?.(); + harness.releasePrompt = null; + harness.deferPrompt = null; queue.close(); await runPromise; }); diff --git a/cli/src/cursor/cursorAcpRemoteLauncher.ts b/cli/src/cursor/cursorAcpRemoteLauncher.ts index 471b591e..855acba3 100644 --- a/cli/src/cursor/cursorAcpRemoteLauncher.ts +++ b/cli/src/cursor/cursorAcpRemoteLauncher.ts @@ -982,15 +982,21 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { } /** - * #1470 / #1502: ACP foreground state → hub thinking via keepalive. - * Background tool/content updates are ignored; running is debounced in the backend. + * #1470 / #1502 / #1553: ACP foreground state → hub thinking via keepalive. + * Ignore ambient Cursor `state_update_running` when no HAPI prompt is in + * flight — that chatter otherwise floats quiet sessions into Working and + * hides an attached job from the Jobs bucket. Prompt-owned running, + * permission, and requires_action still bump thinking. */ private softSteerOutstanding(): boolean { return this.softSteerWaiters.length > 0; } private wireAgentActivityThinking(backend: AcpSdkBackend, session: CursorSession): void { - backend.setAgentActivityListener((thinking) => { + backend.setAgentActivityListener((thinking, source) => { + if (source === 'state_update_running' && !this.promptInFlight) { + return; + } if (shouldSuppressPostCloseHarnessThinking(this.postCloseHarnessGate, { promptInFlight: this.promptInFlight, softSteerOutstanding: this.softSteerOutstanding(), diff --git a/cli/src/grok/utils/systemPrompt.ts b/cli/src/grok/utils/systemPrompt.ts index 695bc9ea..07af91a8 100644 --- a/cli/src/grok/utils/systemPrompt.ts +++ b/cli/src/grok/utils/systemPrompt.ts @@ -1,9 +1,10 @@ import { SKILL_LOOKUP_INSTRUCTION } from '@/modules/common/skillLookupInstruction' +import { withSessionJobInstruction } from '@/modules/common/sessionJobInstruction' import { withSessionSummaryInstruction } from '@/modules/common/sessionSummaryInstruction' export const GROK_TITLE_INSTRUCTION = `Use the tool "hapi_change_title" once after the initial request is clear to set a concise session title. Do not rename for routine progress or substeps.\n${SKILL_LOOKUP_INSTRUCTION}` export function getGrokTitleInstruction(env: NodeJS.ProcessEnv = process.env): string { - return withSessionSummaryInstruction(GROK_TITLE_INSTRUCTION, env) + return withSessionSummaryInstruction(withSessionJobInstruction(GROK_TITLE_INSTRUCTION), env) } diff --git a/cli/src/modules/common/permission/BasePermissionHandler.test.ts b/cli/src/modules/common/permission/BasePermissionHandler.test.ts index ae4350a6..aa2c2e7a 100644 --- a/cli/src/modules/common/permission/BasePermissionHandler.test.ts +++ b/cli/src/modules/common/permission/BasePermissionHandler.test.ts @@ -121,3 +121,15 @@ describe('resolveToolAutoApprovalDecision list_peers', () => { )).toBeNull() }) }) + +describe('resolveToolAutoApprovalDecision session_job', () => { + it.each([ + 'session_job', + 'hapi_session_job', + 'mcp__hapi__session_job', + 'Session-Attached Job' + ])('does not name-only auto-approve spoofable job tool %s', (toolName) => { + // Bridge / --allowedTools own the approve path; global title allowlist must not. + expect(resolveToolAutoApprovalDecision('default', toolName, 'call-1')).toBeNull() + }) +}) diff --git a/cli/src/modules/common/permission/BasePermissionHandler.ts b/cli/src/modules/common/permission/BasePermissionHandler.ts index 679efe75..ef8b268f 100644 --- a/cli/src/modules/common/permission/BasePermissionHandler.ts +++ b/cli/src/modules/common/permission/BasePermissionHandler.ts @@ -39,6 +39,9 @@ const AUTO_APPROVE_EXACT_TOOL_NAMES = new Set([ // ACP permission requests often surface MCP tool title, not the snake_case name. 'list peer sessions' ]); +// session_job is intentionally NOT in this name-only allowlist: ACP titles are +// spoofable (tool-name derivation prefers backend title). Auto-approve only via +// trusted HAPI bridge config (Codex tools map / Claude --allowedTools). // ping_peer / inspect_peer / spawn_peer intentionally omitted from always-approve: // they can resume+inject into another session, read peer histories, or create a // new session with an injected remit, so permission modes must still gate them. diff --git a/cli/src/modules/common/sessionJobInstruction.test.ts b/cli/src/modules/common/sessionJobInstruction.test.ts new file mode 100644 index 00000000..c1dd6c40 --- /dev/null +++ b/cli/src/modules/common/sessionJobInstruction.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { + SESSION_JOB_INSTRUCTION, + withSessionJobInstruction +} from './sessionJobInstruction' + +describe('sessionJobInstruction', () => { + it('requires job run and forbids MCP set / fake percent', () => { + expect(SESSION_JOB_INSTRUCTION).toContain('session_job') + expect(SESSION_JOB_INSTRUCTION).toContain('ping_peer') + expect(SESSION_JOB_INSTRUCTION).toContain('hapi job run') + expect(SESSION_JOB_INSTRUCTION).toContain('idle agents cannot') + expect(SESSION_JOB_INSTRUCTION).toMatch(/action=set \(refused\)/) + expect(SESSION_JOB_INSTRUCTION).toContain('Never invent a fake percent') + expect(SESSION_JOB_INSTRUCTION).toContain('HAPI_SESSION_ID') + expect(SESSION_JOB_INSTRUCTION).toMatch(/operator chat URL uuid|URL uuid explicitly/i) + expect(SESSION_JOB_INSTRUCTION).toMatch(/action=list on start\/resume/i) + expect(SESSION_JOB_INSTRUCTION).toMatch(/before done\/archive/i) + expect(SESSION_JOB_INSTRUCTION).toMatch(/never ask the operator/i) + expect(SESSION_JOB_INSTRUCTION).toContain('--progress until') + + expect(SESSION_JOB_INSTRUCTION).toMatch(/--progress unknown\|fraction\|until/) + expect(SESSION_JOB_INSTRUCTION).toMatch(/frozen 0\/N/) + expect(SESSION_JOB_INSTRUCTION).toMatch(/--progress until/) + expect(SESSION_JOB_INSTRUCTION).toMatch(/Exit≠semantic failure|Exit!=semantic failure/) + }) + + it('appends after an existing prompt block', () => { + expect(withSessionJobInstruction('Base.')).toBe(`Base.\n\n${SESSION_JOB_INSTRUCTION}`) + expect(withSessionJobInstruction('')).toBe(SESSION_JOB_INSTRUCTION) + }) +}) diff --git a/cli/src/modules/common/sessionJobInstruction.ts b/cli/src/modules/common/sessionJobInstruction.ts new file mode 100644 index 00000000..fdcaa4ee --- /dev/null +++ b/cli/src/modules/common/sessionJobInstruction.ts @@ -0,0 +1,49 @@ +/** + * Always-on steer for session-attached long-running jobs (tiann/hapi#1404). + * + * Injected into flavors that have a HAPI system / developer-instructions seam + * today: Claude, Codex, OpenCode, Grok. Cursor/Kimi/Copilot/Pi get the same + * MCP tool (`session_job`) via the HAPI MCP bridge — catalog discovery, not + * this prompt block. Estate skill remains a Cursor backup. + */ + +/** Canonical one-block contract. Keep short — every session's prompt budget. */ +export const SESSION_JOB_INSTRUCTION = [ + 'Session-attached jobs (outliving work):', + 'When you start work that will keep running after this agent goes idle', + '(batch imports, long scripts, external daemons), attach a session job so', + 'the session list shows progress while you are idle — same class of HAPI', + 'tooling as ping_peer / inspect_peer.', + 'REQUIRED for process-shaped work (idle agents cannot heartbeat):', + 'Shell → hapi job run --label ', + '--progress unknown|fraction|until … -- …', + '(--progress is required: unknown=indeterminate stripes; fraction=remaining+total', + 'or done+total; until=--until for known deadlines — heartbeats re-stamp remaining).', + 'Fraction without a continuous updater freezes — keep job update feeder from t=0.', + 'FORBIDDEN: --progress fraction --done 0 --total N with no count writer (frozen 0/N).', + 'Known wall-clock windows MUST use --progress until, not unknown.', + 'Numeric sleep N requires --progress until --until (CLI refuses otherwise).', + + 'Use "$HAPI_SESSION_ID" only when it matches the operator chat URL uuid;', + 'remote Cursor runner may export a worker-row id — pass /sessions/ explicitly.', + '(auto-heartbeats + completed/failed on exit code). Wrap the real cmd — never a sleep', + 'stub while work runs elsewhere (SSH/wget/nohup), except intentional --progress until countdowns.', + 'Exit≠semantic failure: nonzero exit stamps failed even if the batch mostly', + 'succeeded — prefer exit 0 when the run finished; put item errors in detail/logs.', + 'Non-JSONL children need an adapter or --progress unknown — do not invent a percent.', + 'HYGIENE: MCP session_job action=list on start/resume AND before done/archive.', + 'Clear or fail zombie running meters (dead process) yourself — never ask the operator.', + 'Leave live jobs with fresh heartbeats alone.', + 'Do NOT use MCP session_job action=set (refused) or bare set+nohup — that freezes the bar.', + 'MCP session_job is only update / clear / list after job run created the meter.', + 'remaining=0 does not finish the job — pass --status completed or job clear when done.', + 'Never invent a fake percent. Full contract: hapi job --help; docs/guide/session-jobs.md.' +].join(' ') + +/** Append instruction to an existing prompt block (blank line separator). */ +export function withSessionJobInstruction(base: string): string { + const trimmed = base.trimEnd() + return trimmed.length > 0 + ? `${trimmed}\n\n${SESSION_JOB_INSTRUCTION}` + : SESSION_JOB_INSTRUCTION +} diff --git a/cli/src/modules/sessionJob/formatJobLine.ts b/cli/src/modules/sessionJob/formatJobLine.ts new file mode 100644 index 00000000..4c6ac76c --- /dev/null +++ b/cli/src/modules/sessionJob/formatJobLine.ts @@ -0,0 +1,69 @@ +import { stripVTControlCharacters } from 'node:util' + +/** + * Job fields can carry agent- or repo-supplied text. Strip VT/ANSI and remaining + * C0 controls before printing so CLI stdout and MCP tool results cannot emit + * OSC clipboard / title escapes into agent or operator terminals. + */ +export function terminalText(value: string): string { + // stripVT removes ESC-based VT; also scrub C0 + DEL + C1 (incl. 8-bit OSC/ST). + return stripVTControlCharacters(value).replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ') +} + +export type FormatJobLineJob = { + key: string + label: string + status: string + done?: number + total?: number + remaining?: number + unit?: string + detail?: string + runId?: string + heartbeatAt?: number + startedAt?: number +} + +export type FormatJobLineOptions = { + /** CLI list/set/update include wall-clock elapsed + heartbeat age. */ + includeTiming?: boolean + nowMs?: number +} + +export function formatJobLine( + job: FormatJobLineJob, + options: FormatJobLineOptions = {} +): string { + const unit = job.unit ? ` ${terminalText(job.unit)}` : '' + const parts = [terminalText(job.key), terminalText(job.label), terminalText(job.status)] + if (job.remaining !== undefined) { + parts.push(`${job.remaining}${unit} left`) + } else if (job.done !== undefined && job.total !== undefined) { + parts.push(`${job.done}/${job.total}${unit}`) + } + if (options.includeTiming && job.startedAt !== undefined) { + const nowMs = options.nowMs ?? Date.now() + const elapsedSec = Math.max(0, Math.round((nowMs - job.startedAt) / 1000)) + if (elapsedSec < 60) { + parts.push(`elapsed ${elapsedSec}s`) + } else if (elapsedSec < 3600) { + parts.push(`elapsed ${Math.floor(elapsedSec / 60)}m`) + } else if (elapsedSec < 86400) { + const h = Math.floor(elapsedSec / 3600) + const m = Math.floor((elapsedSec % 3600) / 60) + parts.push(m > 0 ? `elapsed ${h}h ${m}m` : `elapsed ${h}h`) + } else { + const d = Math.floor(elapsedSec / 86400) + const h = Math.floor((elapsedSec % 86400) / 3600) + parts.push(h > 0 ? `elapsed ${d}d ${h}h` : `elapsed ${d}d`) + } + } + if (job.detail) parts.push(terminalText(job.detail)) + if (job.runId) parts.push(`runId ${terminalText(job.runId)}`) + if (options.includeTiming && job.heartbeatAt !== undefined) { + const nowMs = options.nowMs ?? Date.now() + const ageSec = Math.max(0, Math.round((nowMs - job.heartbeatAt) / 1000)) + parts.push(`heartbeat ${ageSec}s ago`) + } + return parts.join(' · ') +} diff --git a/cli/src/modules/sessionJob/jobProgressMode.test.ts b/cli/src/modules/sessionJob/jobProgressMode.test.ts new file mode 100644 index 00000000..ea536981 --- /dev/null +++ b/cli/src/modules/sessionJob/jobProgressMode.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest' +import { SessionJobError } from './sessionJob' +import { + assertCreateProgressMode, + assertNumericSleepUsesUntil, + commandLooksLikeNumericSleep, + parseUntilTimestamp, + stampUntilProgress +} from './jobProgressMode' + +describe('commandLooksLikeNumericSleep', () => { + it('detects sleep N and rejects infinity / bare sleep', () => { + expect(commandLooksLikeNumericSleep(['sleep', '150747'])).toBe(true) + expect(commandLooksLikeNumericSleep(['/bin/sleep', '60'])).toBe(true) + expect(commandLooksLikeNumericSleep(['sleep', '999999'])).toBe(true) + expect(commandLooksLikeNumericSleep(['sleep', 'infinity'])).toBe(false) + expect(commandLooksLikeNumericSleep(['sleep'])).toBe(false) + expect(commandLooksLikeNumericSleep(['./beets-import.sh'])).toBe(false) + }) +}) + +describe('assertNumericSleepUsesUntil', () => { + it('refuses numeric sleep under unknown (dogfootgun)', () => { + expect(() => assertNumericSleepUsesUntil('unknown', ['sleep', '150747'])) + .toThrow(/--progress until/) + expect(() => assertNumericSleepUsesUntil('fraction', ['sleep', '60'])) + .toThrow(/--progress until/) + expect(() => assertNumericSleepUsesUntil('until', ['sleep', '150747'])) + .not.toThrow() + expect(() => assertNumericSleepUsesUntil('unknown', ['sleep', 'infinity'])) + .not.toThrow() + }) +}) + + +describe('assertCreateProgressMode', () => { + it('requires --progress on create', () => { + expect(() => assertCreateProgressMode('run', {})).toThrow(/requires --progress/) + expect(() => assertCreateProgressMode('set', {})).toThrow(/requires --progress/) + }) + + it('unknown forbids count and until fields', () => { + expect(() => assertCreateProgressMode('run', { + progress: 'unknown', + remaining: 1 + })).toThrow(/forbids/) + expect(() => assertCreateProgressMode('run', { + progress: 'unknown', + untilMs: Date.now() + 60_000 + })).toThrow(/forbids/) + expect(() => assertCreateProgressMode('run', { progress: 'unknown' })).not.toThrow() + }) + + it('fraction requires a remaining+total or done+total pair', () => { + expect(() => assertCreateProgressMode('set', { + progress: 'fraction', + remaining: 10 + })).toThrow(/requires --remaining N --total M/) + expect(() => assertCreateProgressMode('set', { + progress: 'fraction', + remaining: 10, + total: 100 + })).not.toThrow() + expect(() => assertCreateProgressMode('set', { + progress: 'fraction', + done: 3, + total: 10 + })).not.toThrow() + }) + + it('until requires --until and forbids manual counts', () => { + expect(() => assertCreateProgressMode('run', { progress: 'until' })) + .toThrow(/requires --until/) + expect(() => assertCreateProgressMode('run', { + progress: 'until', + untilMs: Date.now() + 60_000, + remaining: 1 + })).toThrow(/derives remaining\/total/) + expect(() => assertCreateProgressMode('run', { + progress: 'until', + untilMs: Date.now() + 60_000 + })).not.toThrow() + }) +}) + +describe('parseUntilTimestamp', () => { + it('parses ISO and rejects past', () => { + const now = Date.parse('2026-11-08T03:00:00.000Z') + expect(parseUntilTimestamp('2026-11-09T21:20:14.000Z', now)) + .toBe(Date.parse('2026-11-09T21:20:14.000Z')) + expect(() => parseUntilTimestamp('2026-11-07T00:00:00.000Z', now)) + .toThrow(SessionJobError) + }) +}) + +describe('stampUntilProgress', () => { + it('stamps remaining/total in seconds from until and start', () => { + const start = Date.parse('2026-11-07T21:20:14.000Z') + const until = Date.parse('2026-11-09T21:20:14.000Z') + const mid = Date.parse('2026-11-08T21:20:14.000Z') + const stamped = stampUntilProgress(until, mid, start) + expect(stamped.unit).toBe('s') + expect(stamped.total).toBe(172_800) + expect(stamped.remaining).toBe(86_400) + }) + + it('clamps remaining to total when now is before window start', () => { + const start = Date.parse('2026-11-08T00:00:00.000Z') + const until = Date.parse('2026-11-09T00:00:00.000Z') + const before = Date.parse('2026-11-07T00:00:00.000Z') + const stamped = stampUntilProgress(until, before, start) + expect(stamped.total).toBe(86_400) + expect(stamped.remaining).toBe(86_400) + }) +}) diff --git a/cli/src/modules/sessionJob/jobProgressMode.ts b/cli/src/modules/sessionJob/jobProgressMode.ts new file mode 100644 index 00000000..0570d3c8 --- /dev/null +++ b/cli/src/modules/sessionJob/jobProgressMode.ts @@ -0,0 +1,161 @@ +/** + * Explicit progress mode for job create (run/set). + * Omission used to default to indeterminate stripes — that hid known-duration + * countdowns (2026-11-08 dogfood postmortem). Mode must be chosen on purpose. + */ + +import { basename } from 'node:path' +import { SessionJobError } from './sessionJob' + +export const JOB_PROGRESS_MODES = ['unknown', 'fraction', 'until'] as const +export type JobProgressMode = (typeof JOB_PROGRESS_MODES)[number] + +export type ProgressFields = { + progress?: JobProgressMode + untilMs?: number + done?: number | null + total?: number | null + remaining?: number | null + unit?: string | null +} + +export function parseUntilTimestamp(raw: string, nowMs: number = Date.now()): number { + const trimmed = raw.trim() + if (!trimmed) { + throw new SessionJobError('bad_args', '--until requires an ISO-8601 timestamp or epoch ms') + } + if (/^\d+$/.test(trimmed)) { + const n = Number(trimmed) + // 10-digit epoch seconds vs 13-digit ms + const ms = trimmed.length <= 10 ? n * 1000 : n + if (!Number.isFinite(ms)) { + throw new SessionJobError('bad_args', '--until must be a finite epoch') + } + return ms + } + const parsed = Date.parse(trimmed) + if (!Number.isFinite(parsed)) { + throw new SessionJobError( + 'bad_args', + `--until must be ISO-8601 or epoch ms (got ${JSON.stringify(trimmed)})` + ) + } + if (parsed <= nowMs) { + throw new SessionJobError('bad_args', '--until must be in the future') + } + return parsed +} + +export function assertCreateProgressMode( + action: 'run' | 'set', + fields: ProgressFields +): asserts fields is ProgressFields & { progress: JobProgressMode } { + if (fields.progress === undefined) { + throw new SessionJobError( + 'bad_args', + `${action} requires --progress unknown|fraction|until ` + + '(explicit affordance — do not omit; unknown = indeterminate stripes, ' + + 'fraction = remaining+total or done+total, until = --until )' + ) + } + if (!(JOB_PROGRESS_MODES as readonly string[]).includes(fields.progress)) { + throw new SessionJobError( + 'bad_args', + `--progress must be unknown|fraction|until (got ${JSON.stringify(fields.progress)})` + ) + } + + const hasCount = (v: number | null | undefined): v is number => typeof v === 'number' + const hasDone = hasCount(fields.done) + const hasTotal = hasCount(fields.total) + const hasRemaining = hasCount(fields.remaining) + + if (fields.progress === 'unknown') { + if (hasDone || hasTotal || hasRemaining || fields.untilMs !== undefined) { + throw new SessionJobError( + 'bad_args', + '--progress unknown forbids --done/--total/--remaining/--until ' + + '(claim unknown size explicitly; use fraction or until when you know bounds)' + ) + } + return + } + + if (fields.progress === 'fraction') { + if (fields.untilMs !== undefined) { + throw new SessionJobError('bad_args', '--until is only valid with --progress until') + } + const remainingPair = hasRemaining && hasTotal + const donePair = hasDone && hasTotal + if (!remainingPair && !donePair) { + throw new SessionJobError( + 'bad_args', + '--progress fraction requires --remaining N --total M, or --done N --total M' + ) + } + return + } + + // until + if (fields.untilMs === undefined) { + throw new SessionJobError( + 'bad_args', + '--progress until requires --until ' + ) + } + if (hasDone || hasRemaining || hasTotal) { + throw new SessionJobError( + 'bad_args', + '--progress until derives remaining/total from --until; omit --done/--remaining/--total' + ) + } +} + +/** Stamp remaining+total(+unit) for until mode at `nowMs` / optional startedAt. */ +export function stampUntilProgress( + untilMs: number, + nowMs: number = Date.now(), + startedAtMs: number = nowMs +): { remaining: number; total: number; unit: string } { + const totalSec = Math.max(1, Math.ceil((untilMs - startedAtMs) / 1000)) + // Clamp to the window: remaining cannot exceed total (mid-window attach / + // clock skew) and cannot go negative after the deadline. + const remainingSec = Math.max( + 0, + Math.min(totalSec, Math.ceil((untilMs - nowMs) / 1000)) + ) + return { + remaining: remainingSec, + total: totalSec, + unit: 's' + } +} + +/** + * `sleep ` encodes a known wall duration. Bare/alive-only attach + * was the 2026-11-08 dogfood footgun (stripes / frozen one-shot remaining). + * `sleep infinity` stays allowed under `--progress unknown`. + */ +export function commandLooksLikeNumericSleep(command: string[]): boolean { + if (command.length < 2) return false + const bin = basename(command[0]!) + if (bin !== 'sleep') return false + const arg = command[1]!.trim() + if (!/^\d+$/.test(arg)) return false + return Number(arg) > 0 +} + +export function assertNumericSleepUsesUntil( + progress: JobProgressMode, + command: string[] +): void { + if (!commandLooksLikeNumericSleep(command)) return + if (progress === 'until') return + throw new SessionJobError( + 'bad_args', + 'numeric `sleep N` is a known-duration countdown — use ' + + '`--progress until --until ` (heartbeats keep the bar honest). ' + + '`sleep infinity` is OK with `--progress unknown`; do not encode a deadline ' + + 'as sleep-seconds under unknown/fraction (dogfood postmortem 2026-11-08).' + ) +} diff --git a/cli/src/modules/sessionJob/runSessionJob.test.ts b/cli/src/modules/sessionJob/runSessionJob.test.ts new file mode 100644 index 00000000..966327cb --- /dev/null +++ b/cli/src/modules/sessionJob/runSessionJob.test.ts @@ -0,0 +1,1000 @@ +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi } from 'vitest' +import { SESSION_JOB_JWT_REFRESH_AFTER_MS, resolveSessionJobClient, updateSessionJob } from './sessionJob' +import { runSessionJob } from './runSessionJob' + +function fakeChild(exitCode: number, deferExit = false) { + const child = new EventEmitter() as EventEmitter & { + pid: number + killed: boolean + exit: () => void + } + child.pid = 4242 + child.killed = false + child.exit = () => child.emit('exit', exitCode, null) + if (!deferExit) { + queueMicrotask(() => child.exit()) + } + return child +} + +describe('runSessionJob', () => { + it('until heartbeats re-stamp remaining against explicit window startedAt', async () => { + const windowStart = Date.parse('2098-12-01T00:00:00.000Z') + const until = Date.parse('2099-01-01T00:00:00.000Z') + const nowMs = Date.parse('2098-12-15T00:00:00.000Z') + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async (_url: string, body: { startedAt?: number }) => ({ + status: 200, + data: { + job: { + key: 'dogfood', + label: 'dogfood', + status: 'running', + heartbeatAt: 1, + startedAt: body.startedAt ?? 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, _body: { + remaining?: number + total?: number + unit?: string + expectedRunId?: string + }) => ({ + status: 200, + data: { + job: { + key: 'dogfood', + label: 'dogfood', + status: 'running', + heartbeatAt: 2, + startedAt: windowStart, + updatedAt: 2 + } + } + })) + } + + const timers: Array<() => void> = [] + const child = fakeChild(0, true) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'dogfood', + label: 'dogfood', + command: ['sleep', '999999'], + untilMs: until, + startedAtMs: windowStart, + remaining: Math.ceil((until - nowMs) / 1000), + total: Math.ceil((until - windowStart) / 1000), + unit: 's', + heartbeatMs: 10, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + nowImpl: () => nowMs, + spawnImpl: (() => child) as never, + setIntervalImpl: ((fn: () => void) => { + timers.push(fn) + return 1 as unknown as NodeJS.Timeout + }) as never, + clearIntervalImpl: (() => undefined) as never + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + expect(http.put.mock.calls[0]?.[1]).toEqual(expect.objectContaining({ + startedAt: windowStart, + remaining: Math.ceil((until - nowMs) / 1000), + total: Math.ceil((until - windowStart) / 1000) + })) + + timers[0]!() + await vi.waitFor(() => expect(http.patch).toHaveBeenCalled()) + expect(http.patch.mock.calls[0]?.[1]).toEqual(expect.objectContaining({ + remaining: Math.ceil((until - nowMs) / 1000), + total: Math.ceil((until - windowStart) / 1000), + unit: 's' + })) + + child.exit() + await expect(running).resolves.toBe(0) + }) + + it('sets running, heartbeats, then marks completed on exit 0', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async (_url: string, body: { status?: string; startedAt?: number }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 1, + startedAt: body.startedAt ?? 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + })) + } + + const timers: Array<() => void> = [] + const child = fakeChild(0, true) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + heartbeatMs: 10, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: ((fn: () => void) => { + timers.push(fn) + return 1 as unknown as NodeJS.Timeout + }) as never, + clearIntervalImpl: (() => undefined) as never + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + expect(http.put.mock.calls[0]?.[1]).toEqual(expect.objectContaining({ + status: 'running', + runId: expect.any(String) + })) + expect((http.put.mock.calls[0]?.[1] as { startedAt?: number }).startedAt).toBeUndefined() + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + + // Heartbeat ticks reuse resolved client (no extra auth) and must not + // send status:running (late heartbeat must not resurrect after exit). + expect(timers.length).toBe(1) + timers[0]!() + await vi.waitFor(() => expect(http.patch).toHaveBeenCalled()) + const putRunId = (http.put.mock.calls[0]?.[1] as { runId: string }).runId + expect(putRunId).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + ) + const heartbeatBody = http.patch.mock.calls[0]?.[1] as { + status?: string + expectedRunId?: string + } + expect(heartbeatBody.status).toBeUndefined() + expect(heartbeatBody.expectedRunId).toBe(putRunId) + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + + child.exit() + const exitCode = await running + expect(exitCode).toBe(0) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { + status?: string + expectedRunId?: string + } + expect(lastPatch.status).toBe('completed') + expect(lastPatch.expectedRunId).toBe(putRunId) + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + }) + + it('does not mark terminal when hub reports run mismatch (key reused)', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async (_url: string, body: { startedAt?: number }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: body.startedAt ?? 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async () => ({ + status: 409, + data: { error: 'Job run mismatch' } + })) + } + + const child = fakeChild(0, true) + const err = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: ((() => 1) as unknown as typeof setInterval), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async () => undefined + }) + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + child.exit() + const exitCode = await running + expect(exitCode).toBe(0) + expect(http.patch).toHaveBeenCalledTimes(1) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/run mismatch|Job run mismatch/i)) + err.mockRestore() + }) + + it('retries terminal status write after transient failures', async () => { + let patchCalls = 0 + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => { + patchCalls += 1 + if (body.status === 'completed' && patchCalls < 3) { + throw new Error('transient hub 503') + } + return { + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + const sleeps: number[] = [] + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async (ms) => { sleeps.push(ms) } + }) + + expect(exitCode).toBe(0) + expect(patchCalls).toBe(3) + expect(sleeps).toEqual([1_000, 2_000]) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('completed') + }) + + it('exits 0 when child succeeds but meter was cleared before terminal write', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => { + if (body.status === 'completed') { + return { status: 404, data: { error: 'job not found' } } + } + return { + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async () => undefined + }) + + expect(exitCode).toBe(0) + expect(http.patch).toHaveBeenCalled() + }) + + it('exits 1 when child succeeds but terminal status never persists', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async () => { + // Non-connection failure: short retry budget only (3 attempts). + throw new Error('permanent write rejected') + }) + } + + const err = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async () => undefined + }) + + expect(exitCode).toBe(1) + expect(http.patch).toHaveBeenCalledTimes(3) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/failed to mark job completed/i)) + err.mockRestore() + }) + + it('exits 1 when hub stays unreachable past the terminal hub-down deadline', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async () => { + throw Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:3006'), { + code: 'ECONNREFUSED' + }) + }) + } + + const err = vi.spyOn(console, 'error').mockImplementation(() => undefined) + let nowMs = 0 + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async (ms) => { nowMs += ms }, + nowImpl: () => nowMs, + terminalHubDownDeadlineMs: 8_000 + }) + + expect(exitCode).toBe(1) + expect(http.patch.mock.calls.length).toBeGreaterThan(3) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/hub unreachable after child exit/i)) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/failed to mark job completed/i)) + err.mockRestore() + }) + + it('marks failed on non-zero exit', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + })) + } + + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['false'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(7)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never + }) + + expect(exitCode).toBe(7) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('failed') + }) + + it('re-exchanges JWT on heartbeat 401 and still marks completed (hub 4h expiry)', async () => { + let jwtIssue = 0 + let patchCalls = 0 + const http = { + post: vi.fn(async () => { + jwtIssue += 1 + return { status: 200, data: { token: `jwt-${jwtIssue}` } } + }), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }, cfg?: { headers?: Record }) => { + patchCalls += 1 + const auth = cfg?.headers?.Authorization ?? '' + // First heartbeat still carries jwt-1 after hub expiry → 401. + if (patchCalls === 1 && auth.includes('jwt-1')) { + return { status: 401, data: { error: 'expired' } } + } + return { + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + const timers: Array<() => void> = [] + const child = fakeChild(0, true) + const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + heartbeatMs: 10, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: ((fn: () => void) => { + timers.push(fn) + return 1 as unknown as NodeJS.Timeout + }) as never, + clearIntervalImpl: (() => undefined) as never + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + + timers[0]!() + await vi.waitFor(() => expect(http.post).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(http.patch.mock.calls.length).toBeGreaterThanOrEqual(2)) + // Session list not re-fetched — only JWT refresh. + expect(http.get).toHaveBeenCalledTimes(1) + + child.exit() + const exitCode = await running + expect(exitCode).toBe(0) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('completed') + errSpy.mockRestore() + }) + + it('proactively re-exchanges JWT after 3h without re-listing sessions', async () => { + let jwtIssue = 0 + const http = { + post: vi.fn(async () => { + jwtIssue += 1 + return { status: 200, data: { token: `jwt-${jwtIssue}` } } + }), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + patch: vi.fn(async (_url: string, _body: unknown, cfg?: { headers?: Record }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + }, + _auth: cfg?.headers?.Authorization + } + })) + } + + const resolved = await resolveSessionJobClient({ + sessionIdPrefix: 'aaaa', + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + }) + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + + // Inside the window: no second exchange. + await updateSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + body: { remaining: 9 }, + resolved, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + }) + expect(http.post).toHaveBeenCalledTimes(1) + + // Past proactive refresh threshold: exchange once, keep session id. + resolved.jwtIssuedAtMs = Date.now() - SESSION_JOB_JWT_REFRESH_AFTER_MS - 1 + await updateSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + body: { remaining: 8 }, + resolved, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + }) + expect(http.post).toHaveBeenCalledTimes(2) + expect(http.get).toHaveBeenCalledTimes(1) + expect(resolved.jwt).toBe('jwt-2') + const auth = (http.patch.mock.calls.at(-1)?.[2] as { headers?: Record } | undefined) + ?.headers?.Authorization + expect(auth).toContain('jwt-2') + + // Next tick inside the new window: no exchange storm. + await updateSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + body: { remaining: 7 }, + resolved, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + }) + expect(http.post).toHaveBeenCalledTimes(2) + expect(http.get).toHaveBeenCalledTimes(1) + }) + + it('forwards SIGINT/SIGTERM via tree-kill so grandchildren cannot outlive the job', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + runId: 'run-1', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'completed', + runId: 'run-1', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + })) + } + + const child = fakeChild(0, true) + const killChild = vi.fn(async () => true) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['sleep', '30'], + heartbeatMs: 60_000, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: (() => 1 as unknown as NodeJS.Timeout) as never, + clearIntervalImpl: (() => undefined) as never, + killChildImpl: killChild + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + process.emit('SIGINT') + expect(killChild).toHaveBeenCalledWith(child, 'SIGINT') + child.exit() + await running + }) + + it('awaits verified tree-kill before writing terminal job state', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + runId: 'run-1', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async ( + _url: string, + body: { status?: string; detail?: string } + ) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'failed', + runId: 'run-1', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2, + ...(body.detail !== undefined ? { detail: body.detail } : {}), + } + } + })) + } + + let resolveKill: ((ok: boolean) => void) | undefined + const killChild = vi.fn(() => new Promise((resolve) => { + resolveKill = resolve + })) + const child = fakeChild(0, true) + const err = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['sleep', '30'], + heartbeatMs: 60_000, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: (() => 1 as unknown as NodeJS.Timeout) as never, + clearIntervalImpl: (() => undefined) as never, + killChildImpl: killChild + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + process.emit('SIGTERM') + expect(killChild).toHaveBeenCalledWith(child, 'SIGTERM') + child.exit() + + // Child exited, but tree-kill still pending → no terminal write yet. + await Promise.resolve() + expect(http.patch).not.toHaveBeenCalled() + + resolveKill?.(false) + const exitCode = await running + expect(exitCode).toBe(1) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] + expect(lastPatch?.status).toBe('failed') + expect(lastPatch?.detail).toMatch(/complete child process tree/i) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/complete child process tree/i)) + err.mockRestore() + }) + + it('keeps retrying terminal completed after ECONNREFUSED until hub returns (hub restart)', async () => { + let patchCalls = 0 + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'restart-hub', + label: 'restart', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => { + patchCalls += 1 + if (body.status === 'completed' && patchCalls < 6) { + throw Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:3006'), { + code: 'ECONNREFUSED' + }) + } + return { + status: 200, + data: { + job: { + key: 'restart-hub', + label: 'restart', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + const sleeps: number[] = [] + let nowMs = 0 + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'restart-hub', + label: 'restart', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async (ms) => { + sleeps.push(ms) + nowMs += ms + }, + nowImpl: () => nowMs, + terminalHubDownDeadlineMs: 60_000 + }) + + expect(exitCode).toBe(0) + expect(patchCalls).toBe(6) + expect(sleeps.length).toBeGreaterThanOrEqual(5) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('completed') + }) + + it('treats structured HTTP 503 as hub-down for the long terminal retry window', async () => { + let patchCalls = 0 + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => { + patchCalls += 1 + if (body.status === 'completed' && patchCalls < 5) { + // Hub returns JSON error text without "HTTP 503" in the message — + // classification must use the numeric status, not the detail string. + return { status: 503, data: { error: 'Not connected' } } + } + return { + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + let nowMs = 0 + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async (ms) => { nowMs += ms }, + nowImpl: () => nowMs, + terminalHubDownDeadlineMs: 60_000 + }) + + expect(exitCode).toBe(0) + expect(patchCalls).toBe(5) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('completed') + }) + + it('refuses wrapping hapi-restart-hub in job run before creating a meter', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(), + patch: vi.fn() + } + + await expect(runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'restart-hub', + label: 'Patient hub restart', + command: ['env', 'HAPI_AGENT_LABEL=x', 'hapi-restart-hub'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + })).rejects.toMatchObject({ + code: 'bad_args', + message: expect.stringMatching(/hapi-restart-hub|outside the job|hub restart/i) + }) + expect(http.put).not.toHaveBeenCalled() + expect(http.patch).not.toHaveBeenCalled() + }) +}) diff --git a/cli/src/modules/sessionJob/runSessionJob.ts b/cli/src/modules/sessionJob/runSessionJob.ts new file mode 100644 index 00000000..d36b9042 --- /dev/null +++ b/cli/src/modules/sessionJob/runSessionJob.ts @@ -0,0 +1,380 @@ +/** + * Supervise a child command while heartbeating a session-attached job. + * Fixes the idle-agent heartbeat gap (cold review #1404). + */ + +import { randomUUID } from 'node:crypto' +import { basename } from 'node:path' +import { spawn, type ChildProcess } from 'node:child_process' +import { constants as osConstants } from 'node:os' +import type { AttachedJobUpsert } from '@hapi/protocol' +import { killProcessByChildProcess } from '@/utils/process' +import { + SessionJobError, + resolveSessionJobClient, + setSessionJob, + updateSessionJob, + type SessionJobClientOptions, + type SessionJobResolvedClient +} from './sessionJob' +import { stampUntilProgress } from './jobProgressMode' + +export type RunSessionJobOptions = SessionJobClientOptions & { + jobKey: string + label: string + command: string[] + heartbeatMs?: number + remaining?: number + done?: number + total?: number + unit?: string + detail?: string + /** When set, heartbeats re-stamp remaining from wall clock (progress until). */ + untilMs?: number + /** + * Window start for until-mode total (until − startedAt). Defaults to supervisor + * launch time. Pass the original window start on mid-window re-attach so the + * bar does not reset to "time left from this restart." + */ + startedAtMs?: number + wakeOnTerminal?: boolean + wakePrompt?: string + /** Injected for tests. */ + spawnImpl?: typeof spawn + setIntervalImpl?: typeof setInterval + clearIntervalImpl?: typeof clearInterval + /** Injected for tests (terminal-status retry backoff). */ + sleepImpl?: (ms: number) => Promise + /** Injected for tests — wall clock for hub-down terminal retry deadline. */ + nowImpl?: () => number + /** + * How long to keep retrying terminal PATCH while the hub is unreachable + * (ECONNREFUSED after `hapi-restart-hub`, brief remat, etc.). Default 10m. + */ + terminalHubDownDeadlineMs?: number + /** Injected for tests — defaults to tree-kill via killProcessByChildProcess. */ + killChildImpl?: (child: ChildProcess, signal: NodeJS.Signals) => void | Promise +} + +const DEFAULT_HEARTBEAT_MS = 5 * 60 * 1000 +const TERMINAL_STATUS_ATTEMPTS = 3 +const DEFAULT_TERMINAL_HUB_DOWN_DEADLINE_MS = 10 * 60 * 1000 +const TERMINAL_HUB_DOWN_BACKOFF_CAP_MS = 30_000 + +/** Argv tokens that take this hub (or active stack) down mid-supervision. */ +const HUB_STACK_CONTROL_BASENAMES = new Set([ + 'hapi-restart-hub', + 'hapi-use-worktree', + 'hapi-use-driver', + 'hapi-watch-activate-driver', +]) + +/** + * True when the supervised argv would restart/swap this hub while `job run` + * still needs a terminal PATCH — wrapping these creates zombie `running` meters + * unless the hub is reachable again within the hub-down retry window. + */ +export function commandLooksLikeHubStackControl(command: string[]): boolean { + for (const arg of command) { + for (const token of arg.split(/[\s]+/).filter(Boolean)) { + const base = basename(token) + if (HUB_STACK_CONTROL_BASENAMES.has(base)) return true + } + } + return false +} + +/** Connection / gateway failures where retrying after hub restart can succeed. */ +export function isHubUnreachableError(error: unknown): boolean { + if (error instanceof SessionJobError) { + if (error.code === 'run_mismatch' || error.code === 'not_found') return false + // Prefer numeric status: httpStatusError may replace "HTTP 503" with hub JSON text + // like "Not connected", which must still use the hub-down retry window. + if (error.httpStatus !== undefined && error.httpStatus >= 502 && error.httpStatus <= 504) { + return true + } + if (/HTTP 502|HTTP 503|HTTP 504|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|socket hang up|hub unreachable|Network Error/i.test(error.message)) { + return true + } + } + if (error && typeof error === 'object') { + const e = error as { code?: string; message?: string; cause?: unknown } + if (typeof e.code === 'string' + && /^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|EPIPE|EHOSTUNREACH)$/.test(e.code)) { + return true + } + if (typeof e.message === 'string' + && /ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|socket hang up|Network Error|hub unreachable/i.test(e.message)) { + return true + } + if (e.cause !== undefined) return isHubUnreachableError(e.cause) + } + if (error instanceof Error) { + return /ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|socket hang up|Network Error|hub unreachable/i.test(error.message) + } + return false +} + +function terminalBackoffMs(attempt: number, hubDown: boolean): number { + if (!hubDown) return 1_000 * 2 ** attempt + return Math.min(2_000 * 2 ** attempt, TERMINAL_HUB_DOWN_BACKOFF_CAP_MS) +} + +async function markTerminalWithRetry(options: { + clientOpts: SessionJobClientOptions & { resolved: SessionJobResolvedClient } + jobKey: string + status: 'completed' | 'failed' + detail?: string + expectedRunId: string + sleep: (ms: number) => Promise + now: () => number + hubDownDeadlineMs: number +}): Promise { + let lastError: unknown + let attempt = 0 + const startedAt = options.now() + let loggedHubDownWait = false + for (;;) { + try { + await updateSessionJob({ + ...options.clientOpts, + jobKey: options.jobKey, + body: { + status: options.status, + expectedRunId: options.expectedRunId, + ...(options.detail !== undefined ? { detail: options.detail } : {}), + }, + }) + return + } catch (error) { + lastError = error + // Another run owns the key — retrying cannot help and may confuse logs. + if (error instanceof SessionJobError && error.code === 'run_mismatch') { + break + } + + const hubDown = isHubUnreachableError(error) + const elapsed = options.now() - startedAt + const withinHubDownBudget = hubDown && elapsed < options.hubDownDeadlineMs + const withinShortBudget = !hubDown && attempt < TERMINAL_STATUS_ATTEMPTS - 1 + + // Operator cleared the meter while the child still ran — detached, not a + // supervision failure. Retry transient 404s; accept absence when budget ends. + if (error instanceof SessionJobError && error.code === 'not_found') { + if (!withinShortBudget && !withinHubDownBudget) { + return + } + } else if (!withinShortBudget && !withinHubDownBudget) { + break + } + + if (hubDown && !loggedHubDownWait) { + loggedHubDownWait = true + const message = error instanceof Error ? error.message : String(error) + console.error( + `[hapi job run] hub unreachable after child exit (${message}); ` + + `retrying terminal ${options.status} for up to ` + + `${Math.round(options.hubDownDeadlineMs / 1000)}s` + ) + } + + await options.sleep(terminalBackoffMs(attempt, hubDown)) + attempt += 1 + } + } + throw lastError instanceof Error ? lastError : new Error(String(lastError)) +} + +export async function runSessionJob(options: RunSessionJobOptions): Promise { + if (options.command.length === 0) { + throw new SessionJobError('bad_args', 'run requires a command after --') + } + + if (commandLooksLikeHubStackControl(options.command)) { + throw new SessionJobError( + 'bad_args', + 'do not wrap hapi-restart-hub / hapi-use-worktree / hapi-use-driver / ' + + 'hapi-watch-activate-driver in `hapi job run` — the hub is down exactly when ' + + 'the terminal status PATCH must land, leaving a zombie running meter. ' + + 'Run the hub restart outside the job (job = remat/work only; restart after exit).' + ) + } + + // Hub stamps startedAt when runId starts a new generation (runner/hub + // clocks may skew) unless the caller passes an explicit window start. + // runId is the unique generation fence. + const runId = randomUUID() + const body: AttachedJobUpsert = { + label: options.label, + status: 'running', + runId, + ...(options.done !== undefined ? { done: options.done } : {}), + ...(options.total !== undefined ? { total: options.total } : {}), + ...(options.remaining !== undefined ? { remaining: options.remaining } : {}), + ...(options.unit !== undefined ? { unit: options.unit } : {}), + ...(options.detail !== undefined ? { detail: options.detail } : {}), + ...(options.startedAtMs !== undefined ? { startedAt: options.startedAtMs } : {}), + ...(options.wakeOnTerminal !== undefined ? { wakeOnTerminal: options.wakeOnTerminal } : {}), + ...(options.wakePrompt !== undefined ? { wakePrompt: options.wakePrompt } : {}) + } + + // Cache sessionId for the run. JWT is refreshed in-place before hub's 4h + // expiry and on 401 (see sessionJob.withAuthedRequest) — do not skip refresh. + const resolved: SessionJobResolvedClient = await resolveSessionJobClient(options) + const clientOpts = { + sessionIdPrefix: options.sessionIdPrefix, + resolved, + accessToken: options.accessToken, + apiUrl: options.apiUrl, + http: options.http + } + + await setSessionJob({ + ...clientOpts, + jobKey: options.jobKey, + body + }) + + const spawnFn = options.spawnImpl ?? spawn + const setIntervalFn = options.setIntervalImpl ?? setInterval + const clearIntervalFn = options.clearIntervalImpl ?? clearInterval + const sleep = options.sleepImpl + ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))) + const now = options.nowImpl ?? Date.now + const hubDownDeadlineMs = options.terminalHubDownDeadlineMs ?? DEFAULT_TERMINAL_HUB_DOWN_DEADLINE_MS + const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS + + const child: ChildProcess = spawnFn(options.command[0]!, options.command.slice(1), { + stdio: 'inherit', + env: process.env + }) + + let loggedHeartbeatFailure = false + let inflightHeartbeat: Promise = Promise.resolve() + // Until-mode total = until − windowStart. Prefer explicit startedAtMs so a + // mid-window move keeps the original 48h (etc.) denominator. + const untilWindowStartMs = options.startedAtMs ?? now() + const heartbeat = setIntervalFn(() => { + // Never PATCH status:running on the heartbeat — a late in-flight + // request must not resurrect running after the terminal write. + // Fence with runId so a superseded run cannot touch a key reuse. + // Do not re-send --detail: MCP/CLI progress updates would otherwise be + // clobbered by the next timer tick with the launch-time string. + const untilBody = options.untilMs !== undefined + ? (() => { + const stamped = stampUntilProgress(options.untilMs!, now(), untilWindowStartMs) + return { + remaining: stamped.remaining, + total: stamped.total, + unit: options.unit ?? stamped.unit + } + })() + : {} + inflightHeartbeat = updateSessionJob({ + ...clientOpts, + jobKey: options.jobKey, + body: { expectedRunId: runId, ...untilBody } + }).catch((error: unknown) => { + // Best-effort — exit path still marks terminal status. Log once so + // a broken supervisor is visible (stuck chip with dead PID is worse). + if (!loggedHeartbeatFailure) { + loggedHeartbeatFailure = true + const message = error instanceof Error ? error.message : String(error) + console.error(`[hapi job run] heartbeat failed (will keep trying): ${message}`) + } + }) + }, heartbeatMs) + // Don't keep the event loop alive solely for heartbeats if child already exited. + heartbeat.unref?.() + + // Forward the received signal through tree-kill (not always SIGTERM) and + // await verified teardown before writing terminal job state. + let terminationPromise: Promise | null = null + const forward = (signal: NodeJS.Signals) => { + if (child.pid && !child.killed) { + // Tree-kill: a supervised shell can exit while a grandchild keeps + // running; bare process.kill(child.pid) would leave orphans and let + // the wrapper mark the job terminal while work continues. + const killChild = options.killChildImpl + ?? ((target: ChildProcess, sig: NodeJS.Signals) => + killProcessByChildProcess(target, false, sig)) + terminationPromise ??= Promise.resolve(killChild(child, signal)).then( + (result) => result !== false + ) + } + } + const onSigInt = () => forward('SIGINT') + const onSigTerm = () => forward('SIGTERM') + process.on('SIGINT', onSigInt) + process.on('SIGTERM', onSigTerm) + + let spawnErrorDetail: string | undefined + const exitCode = await new Promise((resolve) => { + child.on('error', async (error) => { + clearIntervalFn(heartbeat) + spawnErrorDetail = error.message + resolve(127) + }) + child.on('exit', (code, signal) => { + clearIntervalFn(heartbeat) + if (signal) { + const signalNumber = osConstants.signals[signal] ?? 1 + resolve(128 + signalNumber) + return + } + resolve(code ?? 1) + }) + }) + + process.off('SIGINT', onSigInt) + process.off('SIGTERM', onSigTerm) + + // Drain any in-flight heartbeat so a late status:running cannot clobber + // the terminal completed/failed write. + await inflightHeartbeat.catch(() => undefined) + + let treeKillFailed = false + if (terminationPromise) { + const stopped = await terminationPromise + if (!stopped) { + treeKillFailed = true + console.error('[hapi job run] failed to terminate the complete child process tree') + } + } + + const terminalStatus = exitCode === 0 && !treeKillFailed ? 'completed' : 'failed' + let terminalWriteFailed = false + try { + await markTerminalWithRetry({ + clientOpts, + jobKey: options.jobKey, + status: terminalStatus, + expectedRunId: runId, + ...(spawnErrorDetail !== undefined + ? { detail: spawnErrorDetail } + : treeKillFailed + ? { detail: 'failed to terminate the complete child process tree' } + : {}), + sleep, + now, + hubDownDeadlineMs, + }) + } catch (error) { + // run_mismatch means another generation owns the key — not our meter to fix. + // not_found means the meter was cleared externally (e.g. session_job clear). + terminalWriteFailed = !( + error instanceof SessionJobError + && (error.code === 'run_mismatch' || error.code === 'not_found') + ) + const message = error instanceof Error ? error.message : String(error) + console.error(`[hapi job run] failed to mark job ${terminalStatus}: ${message}`) + } + + // Child success with a frozen "running" meter (or uncleared descendants) is + // worse than a nonzero exit — surface the supervision failure so wrappers/CI + // cannot claim green. + if (treeKillFailed) { + return exitCode === 0 ? 1 : exitCode + } + return exitCode === 0 && terminalWriteFailed ? 1 : exitCode +} diff --git a/cli/src/modules/sessionJob/sessionJob.ts b/cli/src/modules/sessionJob/sessionJob.ts new file mode 100644 index 00000000..4c5dfa8b --- /dev/null +++ b/cli/src/modules/sessionJob/sessionJob.ts @@ -0,0 +1,458 @@ +/** + * Register / update / clear session-attached jobs (tiann/hapi#1404). + * Same hub JWT flow as ping-peer — works while the agent session is idle. + */ + +import axios, { type AxiosInstance } from 'axios' +import type { AttachedJob, AttachedJobPatch, AttachedJobUpsert } from '@hapi/protocol' +import { configuration } from '@/configuration' +import { getAuthToken } from '@/api/auth' +import { buildHubRequestHeaders } from '@/api/hubExtraHeaders' + +export type SessionJobErrorCode = + | 'bad_args' + | 'auth_failed' + | 'not_found' + | 'ambiguous' + | 'run_mismatch' + | 'request_failed' + +export class SessionJobError extends Error { + readonly code: SessionJobErrorCode + /** Present when the failure came from an HTTP response (for outage classification). */ + readonly httpStatus?: number + + constructor(code: SessionJobErrorCode, message: string, httpStatus?: number) { + super(message) + this.name = 'SessionJobError' + this.code = code + if (httpStatus !== undefined) this.httpStatus = httpStatus + } +} + +/** Exact Shell recipe agents should run instead of MCP set or update-before-create. */ +export const SESSION_JOB_RUN_RECIPE = + 'hapi job run --label "