mirror of
https://github.com/wu736139669/hapi.git
synced 2026-12-06 07:17:02 +00:00
feat: show progress bar on session for hours-long jobs (#1424)
* 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * test(jobs): cover proactive JWT refresh; map 401 to auth_failed Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(jobs): typecheck-safe assertion for run startedAt Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): type put mock args so startedAt assertion typechecks Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(jobs): type from-session metadata when inheriting job redirects Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(jobs): stub allocateAttachedJobVersion in sessions route mocks Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(jobs): expect empty MCP update as heartbeat Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * test(jobs): stub transferAttachedJobs in Codex duplicate-merge mock Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * docs(jobs): note schema tip V25 after A2A V23 collision Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(cli): preserve -- for hapi job run under normalizeCliArgs Runtime-wrapper handoff was dropping everything before `--` (or stripping `--` itself), so `job run … -- <cmd>` fell through to Claude. Keep `--` when a HAPI command already precedes it; only treat bare `bun entry -- <cli>` as a wrapper handoff. Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(cli): reject stray MCP fields and non-run command suffix MCP list/clear reject incompatible fields; CLI rejects -- <cmd> unless action is run so clear/set cannot silently drop a trailing command. Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(cursor): drop leftover rebase conflict markers in ACP launcher Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(cli): scrub C1 controls in shared job-output sanitizer Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): fix C1 sanitizer assertion (content may remain) Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(hub): also remap redirected job set without runId on collision Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * test(cli): type the tree-kill teardown patch mock for typecheck Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * test(cli): keep ACP MCP tool list without video/media after rebase Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * test(hub): expect schema tip v29 in migration-v26 after jobs remap Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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.<B> mapping. Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * chore: nudge GitHub PR head sync for #1424 Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): drop Fixed session order assertion from display settings Matches removal of the obsolete switch under SessionListView (#2263). Co-authored-by: Cursor <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * fix(jobs): provisional pending wake claims + run fence Persist wake delivery as pending:<runId> 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> * 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 <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -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()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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 <session-id> <job-key> --label <text>',
|
||||
'--progress unknown|fraction|until … -- <cmd>…',
|
||||
'(--progress is required: unknown=indeterminate stripes; fraction=remaining+total',
|
||||
'or done+total; until=--until <ISO|epoch> 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 <ISO> (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/<id> 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
|
||||
}
|
||||
@@ -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(' · ')
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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 <iso|epoch>)'
|
||||
)
|
||||
}
|
||||
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 <ISO-8601 or epoch ms>'
|
||||
)
|
||||
}
|
||||
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 <positive-int>` 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 <ISO|epoch>` (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).'
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<void>
|
||||
/** 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<boolean>
|
||||
}
|
||||
|
||||
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<void>
|
||||
now: () => number
|
||||
hubDownDeadlineMs: number
|
||||
}): Promise<void> {
|
||||
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<number> {
|
||||
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<void>((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<unknown> = 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<boolean> | 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<number>((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
|
||||
}
|
||||
@@ -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 <session-id> <job-key> --label "<label>" --progress unknown|fraction|until … -- <cmd>…'
|
||||
+ ' (required --progress: unknown=stripes; fraction=remaining+total|done+total;'
|
||||
+ ' until=--until <iso> with auto remaining on heartbeats).'
|
||||
+ ' Fraction without a continuous updater freezes — keep updating done/remaining.'
|
||||
+ ' (use "$HAPI_SESSION_ID" only when it matches the operator /sessions/<id> chat row;'
|
||||
+ ' remote Cursor: pass the URL uuid explicitly)'
|
||||
|
||||
export function formatSessionJobNotFoundHint(action: 'update' | 'clear'): string {
|
||||
return [
|
||||
`job not found on this session (${action} requires an existing meter).`,
|
||||
'Create one with Shell (MCP action=set is refused):',
|
||||
SESSION_JOB_RUN_RECIPE,
|
||||
'Wrap the real long-running command — not a sleep stub while work runs elsewhere.',
|
||||
].join(' ')
|
||||
}
|
||||
|
||||
/** True when hub/CLI reports a missing session job (incl. duplicate-class instanceof misses). */
|
||||
export function isSessionJobNotFoundError(error: unknown): boolean {
|
||||
if (error instanceof SessionJobError && error.code === 'not_found') {
|
||||
return true
|
||||
}
|
||||
if (typeof error === 'object' && error !== null) {
|
||||
const candidate = error as { name?: string; code?: string }
|
||||
if (candidate.code === 'not_found' && candidate.name === 'SessionJobError') {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// MCP server bundles can load two SessionJobError identities; message still matches.
|
||||
if (error instanceof Error && /\bjob not found\b/i.test(error.message)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Shown after update when progress reads done but status is still running. */
|
||||
export const SESSION_JOB_REMAINING_ZERO_HINT =
|
||||
'remaining is 0 but status is still running — pass --status completed when work is finished, or hapi job clear to drop the meter.'
|
||||
|
||||
const AUTH_RECOVERY_HINT =
|
||||
'On a remote runner, set HAPI_API_URL to the runner hub, and set CLI_API_TOKEN ' +
|
||||
'or run `hapi auth login`. Prefer `hapi job` over raw JWT+curl.'
|
||||
|
||||
function resolveApiUrl(apiUrl?: string): string {
|
||||
const raw = (apiUrl ?? configuration.apiUrl).trim().replace(/\/+$/, '')
|
||||
if (!raw) {
|
||||
throw new SessionJobError('bad_args', `HAPI API URL is empty. ${AUTH_RECOVERY_HINT}`)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
function resolveAccessToken(accessToken?: string): string {
|
||||
let token = ''
|
||||
try {
|
||||
token = (accessToken ?? getAuthToken()).trim()
|
||||
} catch {
|
||||
token = (accessToken ?? '').trim()
|
||||
}
|
||||
if (!token) {
|
||||
throw new SessionJobError(
|
||||
'bad_args',
|
||||
`CLI_API_TOKEN is required (run \`hapi auth login\`). ${AUTH_RECOVERY_HINT}`
|
||||
)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
async function exchangeJwt(
|
||||
apiUrl: string,
|
||||
accessToken: string,
|
||||
http: AxiosInstance
|
||||
): Promise<string> {
|
||||
try {
|
||||
const response = await http.post(
|
||||
`${apiUrl}/api/auth`,
|
||||
{ accessToken },
|
||||
{
|
||||
headers: buildHubRequestHeaders({ 'Content-Type': 'application/json' }),
|
||||
timeout: 10_000,
|
||||
validateStatus: () => true
|
||||
}
|
||||
)
|
||||
const token = typeof response.data?.token === 'string' ? response.data.token : ''
|
||||
if (response.status < 200 || response.status >= 300 || !token) {
|
||||
const detail = typeof response.data?.error === 'string'
|
||||
? response.data.error
|
||||
: `HTTP ${response.status}`
|
||||
throw new SessionJobError(
|
||||
'auth_failed',
|
||||
`failed to exchange access token for JWT (${detail}). Hub URL: ${apiUrl}. ${AUTH_RECOVERY_HINT}`
|
||||
)
|
||||
}
|
||||
return token
|
||||
} catch (error) {
|
||||
if (error instanceof SessionJobError) throw error
|
||||
throw new SessionJobError(
|
||||
'auth_failed',
|
||||
`failed to exchange access token for JWT (${error instanceof Error ? error.message : String(error)}). Hub URL: ${apiUrl}. ${AUTH_RECOVERY_HINT}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function authHeaders(jwt: string): Record<string, string> {
|
||||
return buildHubRequestHeaders({
|
||||
Authorization: `Bearer ${jwt}`,
|
||||
'Content-Type': 'application/json'
|
||||
})
|
||||
}
|
||||
|
||||
type SessionListItem = { id: string }
|
||||
|
||||
export function resolveSessionByPrefix(sessions: SessionListItem[], prefix: string): SessionListItem {
|
||||
const trimmed = prefix.trim()
|
||||
if (!trimmed) {
|
||||
throw new SessionJobError('bad_args', 'session id prefix is required')
|
||||
}
|
||||
const exact = sessions.filter((session) => session.id === trimmed)
|
||||
if (exact.length === 1) return exact[0]!
|
||||
const matches = sessions.filter((session) => session.id.startsWith(trimmed))
|
||||
if (matches.length === 0) {
|
||||
throw new SessionJobError('not_found', `no session matching prefix '${trimmed}'`)
|
||||
}
|
||||
if (matches.length > 1) {
|
||||
const sample = matches.slice(0, 5).map((session) => session.id.slice(0, 8)).join(', ')
|
||||
throw new SessionJobError(
|
||||
'ambiguous',
|
||||
`prefix '${trimmed}' matches ${matches.length} sessions (${sample}${matches.length > 5 ? ', ...' : ''}); use a longer prefix`
|
||||
)
|
||||
}
|
||||
return matches[0]!
|
||||
}
|
||||
|
||||
const FULL_SESSION_UUID =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
|
||||
/**
|
||||
* Resolve a session id for job CLI calls. Prefer list match; if the prefix is
|
||||
* a full UUID missing from the list (deleted merge source), pass it through so
|
||||
* hub job routes can follow jobsAcceptedFromSessionIds.
|
||||
*/
|
||||
export function resolveSessionIdForJobCli(
|
||||
sessions: SessionListItem[],
|
||||
sessionIdPrefix: string
|
||||
): string {
|
||||
try {
|
||||
return resolveSessionByPrefix(sessions, sessionIdPrefix).id
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof SessionJobError
|
||||
&& error.code === 'not_found'
|
||||
&& FULL_SESSION_UUID.test(sessionIdPrefix.trim())
|
||||
) {
|
||||
return sessionIdPrefix.trim()
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveSessionId(
|
||||
apiUrl: string,
|
||||
jwt: string,
|
||||
http: AxiosInstance,
|
||||
sessionIdPrefix: string
|
||||
): Promise<string> {
|
||||
const response = await http.get(`${apiUrl}/api/sessions`, {
|
||||
headers: authHeaders(jwt),
|
||||
params: { limit: 500, order: 'updatedAt' },
|
||||
timeout: 15_000,
|
||||
validateStatus: () => true
|
||||
})
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
throw new SessionJobError('request_failed', `list sessions failed: HTTP ${response.status}`)
|
||||
}
|
||||
const sessions = Array.isArray(response.data?.sessions)
|
||||
? (response.data.sessions as SessionListItem[])
|
||||
: []
|
||||
return resolveSessionIdForJobCli(sessions, sessionIdPrefix)
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutable client handle for supervised runs.
|
||||
* Cache `sessionId` for the life of the process (list is expensive); refresh
|
||||
* `jwt` proactively before hub's 4h expiry and on 401.
|
||||
*/
|
||||
export type SessionJobResolvedClient = {
|
||||
apiUrl: string
|
||||
jwt: string
|
||||
sessionId: string
|
||||
jwtIssuedAtMs: number
|
||||
}
|
||||
|
||||
export type SessionJobClientOptions = {
|
||||
sessionIdPrefix: string
|
||||
apiUrl?: string
|
||||
accessToken?: string
|
||||
http?: AxiosInstance
|
||||
/**
|
||||
* When set (e.g. after {@link resolveSessionJobClient}), skip session-list
|
||||
* resolve. JWT is still refreshed in-place for days-long `job run`.
|
||||
*/
|
||||
resolved?: SessionJobResolvedClient
|
||||
}
|
||||
|
||||
/** Hub JWT expires at 4h — refresh a bit early so heartbeats never 401. */
|
||||
export const SESSION_JOB_JWT_REFRESH_AFTER_MS = 3 * 60 * 60 * 1000
|
||||
|
||||
/** Resolve session id once; JWT may be refreshed later via the same object. */
|
||||
export async function resolveSessionJobClient(
|
||||
options: SessionJobClientOptions
|
||||
): Promise<SessionJobResolvedClient> {
|
||||
if (options.resolved) {
|
||||
return options.resolved
|
||||
}
|
||||
const http = options.http ?? axios
|
||||
const apiUrl = resolveApiUrl(options.apiUrl)
|
||||
const accessToken = resolveAccessToken(options.accessToken)
|
||||
const jwt = await exchangeJwt(apiUrl, accessToken, http)
|
||||
const sessionId = await resolveSessionId(apiUrl, jwt, http, options.sessionIdPrefix)
|
||||
return { apiUrl, jwt, sessionId, jwtIssuedAtMs: Date.now() }
|
||||
}
|
||||
|
||||
async function refreshSessionJobJwt(
|
||||
resolved: SessionJobResolvedClient,
|
||||
options: SessionJobClientOptions
|
||||
): Promise<void> {
|
||||
const http = options.http ?? axios
|
||||
const accessToken = resolveAccessToken(options.accessToken)
|
||||
resolved.jwt = await exchangeJwt(resolved.apiUrl, accessToken, http)
|
||||
resolved.jwtIssuedAtMs = Date.now()
|
||||
}
|
||||
|
||||
async function ensureFreshJwt(
|
||||
resolved: SessionJobResolvedClient,
|
||||
options: SessionJobClientOptions,
|
||||
force = false
|
||||
): Promise<void> {
|
||||
const age = Date.now() - resolved.jwtIssuedAtMs
|
||||
if (force || age >= SESSION_JOB_JWT_REFRESH_AFTER_MS) {
|
||||
await refreshSessionJobJwt(resolved, options)
|
||||
}
|
||||
}
|
||||
|
||||
type AuthedResponse = { status: number; data?: unknown }
|
||||
|
||||
function httpStatusError(
|
||||
action: string,
|
||||
response: AuthedResponse,
|
||||
errorDetail?: string
|
||||
): SessionJobError {
|
||||
const detail = typeof errorDetail === 'string' && errorDetail.length > 0
|
||||
? errorDetail
|
||||
: `HTTP ${response.status}`
|
||||
if (response.status === 401) {
|
||||
return new SessionJobError('auth_failed', `${action} failed: ${detail}`, response.status)
|
||||
}
|
||||
return new SessionJobError('request_failed', `${action} failed: ${detail}`, response.status)
|
||||
}
|
||||
|
||||
/**
|
||||
* Run an authed request; on 401 re-exchange JWT (keep cached sessionId) and retry once.
|
||||
*/
|
||||
async function withAuthedRequest<T>(
|
||||
options: SessionJobClientOptions,
|
||||
request: (ctx: { apiUrl: string; jwt: string; sessionId: string; http: AxiosInstance }) => Promise<AuthedResponse>,
|
||||
handle: (response: AuthedResponse, sessionId: string) => T
|
||||
): Promise<T> {
|
||||
const http = options.http ?? axios
|
||||
const resolved = await resolveSessionJobClient(options)
|
||||
await ensureFreshJwt(resolved, options)
|
||||
|
||||
const run = async () => request({
|
||||
apiUrl: resolved.apiUrl,
|
||||
jwt: resolved.jwt,
|
||||
sessionId: resolved.sessionId,
|
||||
http
|
||||
})
|
||||
|
||||
let response = await run()
|
||||
if (response.status === 401) {
|
||||
await ensureFreshJwt(resolved, options, true)
|
||||
response = await run()
|
||||
}
|
||||
return handle(response, resolved.sessionId)
|
||||
}
|
||||
|
||||
export async function listSessionJobs(
|
||||
options: SessionJobClientOptions
|
||||
): Promise<{ sessionId: string; jobs: AttachedJob[]; primary: AttachedJob | null }> {
|
||||
return withAuthedRequest(
|
||||
options,
|
||||
({ apiUrl, jwt, sessionId, http }) => http.get(`${apiUrl}/api/sessions/${sessionId}/jobs`, {
|
||||
headers: authHeaders(jwt),
|
||||
timeout: 15_000,
|
||||
validateStatus: () => true
|
||||
}),
|
||||
(response, sessionId) => {
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
throw httpStatusError('list jobs', response)
|
||||
}
|
||||
const data = response.data as { jobs?: AttachedJob[]; primary?: AttachedJob | null } | undefined
|
||||
return {
|
||||
sessionId,
|
||||
jobs: Array.isArray(data?.jobs) ? data.jobs : [],
|
||||
primary: data?.primary ?? null
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export async function setSessionJob(
|
||||
options: SessionJobClientOptions & { jobKey: string; body: AttachedJobUpsert }
|
||||
): Promise<{ sessionId: string; job: AttachedJob }> {
|
||||
return withAuthedRequest(
|
||||
options,
|
||||
({ apiUrl, jwt, sessionId, http }) => http.put(
|
||||
`${apiUrl}/api/sessions/${sessionId}/jobs/${encodeURIComponent(options.jobKey)}`,
|
||||
options.body,
|
||||
{
|
||||
headers: authHeaders(jwt),
|
||||
timeout: 15_000,
|
||||
validateStatus: () => true
|
||||
}
|
||||
),
|
||||
(response, sessionId) => {
|
||||
if (response.status === 404) {
|
||||
throw new SessionJobError('not_found', 'session or job not found')
|
||||
}
|
||||
const data = response.data as { job?: AttachedJob; error?: string } | undefined
|
||||
if (response.status < 200 || response.status >= 300 || !data?.job) {
|
||||
throw httpStatusError('set job', response, data?.error)
|
||||
}
|
||||
return { sessionId, job: data.job }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export async function updateSessionJob(
|
||||
options: SessionJobClientOptions & { jobKey: string; body: AttachedJobPatch }
|
||||
): Promise<{ sessionId: string; job: AttachedJob }> {
|
||||
return withAuthedRequest(
|
||||
options,
|
||||
({ apiUrl, jwt, sessionId, http }) => http.patch(
|
||||
`${apiUrl}/api/sessions/${sessionId}/jobs/${encodeURIComponent(options.jobKey)}`,
|
||||
options.body,
|
||||
{
|
||||
headers: authHeaders(jwt),
|
||||
timeout: 15_000,
|
||||
validateStatus: () => true
|
||||
}
|
||||
),
|
||||
(response, sessionId) => {
|
||||
if (response.status === 404) {
|
||||
throw new SessionJobError('not_found', 'job not found')
|
||||
}
|
||||
if (response.status === 409) {
|
||||
const data = response.data as { error?: string } | undefined
|
||||
throw new SessionJobError(
|
||||
'run_mismatch',
|
||||
data?.error
|
||||
?? 'job run mismatch (expectedRunId); another run reused this key'
|
||||
)
|
||||
}
|
||||
const data = response.data as { job?: AttachedJob; error?: string } | undefined
|
||||
if (response.status < 200 || response.status >= 300 || !data?.job) {
|
||||
throw httpStatusError('update job', response, data?.error)
|
||||
}
|
||||
return { sessionId, job: data.job }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export async function clearSessionJob(
|
||||
options: SessionJobClientOptions & { jobKey: string; expectedRunId?: string }
|
||||
): Promise<{ sessionId: string }> {
|
||||
return withAuthedRequest(
|
||||
options,
|
||||
({ apiUrl, jwt, sessionId, http }) => {
|
||||
const qs = options.expectedRunId
|
||||
? `?expectedRunId=${encodeURIComponent(options.expectedRunId)}`
|
||||
: ''
|
||||
return http.delete(
|
||||
`${apiUrl}/api/sessions/${sessionId}/jobs/${encodeURIComponent(options.jobKey)}${qs}`,
|
||||
{
|
||||
headers: authHeaders(jwt),
|
||||
timeout: 15_000,
|
||||
validateStatus: () => true
|
||||
}
|
||||
)
|
||||
},
|
||||
(response, sessionId) => {
|
||||
if (response.status === 404) {
|
||||
throw new SessionJobError('not_found', 'job not found')
|
||||
}
|
||||
if (response.status === 409) {
|
||||
const detail = (response.data as { error?: string } | undefined)?.error
|
||||
throw new SessionJobError(
|
||||
'run_mismatch',
|
||||
detail
|
||||
?? 'job run mismatch (expectedRunId); another run reused this key'
|
||||
)
|
||||
}
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
throw httpStatusError('clear job', response)
|
||||
}
|
||||
return { sessionId }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export function exitCodeForSessionJobError(error: SessionJobError): number {
|
||||
switch (error.code) {
|
||||
case 'bad_args':
|
||||
return 2
|
||||
case 'auth_failed':
|
||||
return 3
|
||||
case 'not_found':
|
||||
return 4
|
||||
case 'ambiguous':
|
||||
return 5
|
||||
case 'run_mismatch':
|
||||
return 6
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
handleSessionJobTool,
|
||||
SESSION_JOB_RUN_RECIPE,
|
||||
SESSION_JOB_SET_REFUSED_TEXT,
|
||||
SESSION_JOB_TOOL_DESCRIPTION
|
||||
} from './sessionJobMcp'
|
||||
|
||||
vi.mock('./sessionJob', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('./sessionJob')>()
|
||||
return {
|
||||
...actual,
|
||||
setSessionJob: vi.fn(async () => {
|
||||
throw new Error('setSessionJob must not be called from MCP')
|
||||
}),
|
||||
updateSessionJob: vi.fn(async () => ({
|
||||
sessionId: 'sid-1',
|
||||
job: {
|
||||
key: 'beets',
|
||||
label: 'beets import',
|
||||
status: 'running',
|
||||
remaining: 11,
|
||||
heartbeatAt: 2,
|
||||
startedAt: 1,
|
||||
updatedAt: 2
|
||||
}
|
||||
})),
|
||||
clearSessionJob: vi.fn(async () => ({ sessionId: 'sid-1' })),
|
||||
listSessionJobs: vi.fn(async () => ({ sessionId: 'sid-1', jobs: [], primary: null }))
|
||||
}
|
||||
})
|
||||
|
||||
describe('sessionJobMcp', () => {
|
||||
it('description steers to job run and forbids MCP set', () => {
|
||||
expect(SESSION_JOB_TOOL_DESCRIPTION).toMatch(/OUTLIVES/i)
|
||||
expect(SESSION_JOB_TOOL_DESCRIPTION).toMatch(/do NOT use action=set/i)
|
||||
expect(SESSION_JOB_TOOL_DESCRIPTION).toContain('hapi job run')
|
||||
expect(SESSION_JOB_TOOL_DESCRIPTION).toMatch(/Own-session only/i)
|
||||
expect(SESSION_JOB_TOOL_DESCRIPTION).toMatch(/action=list on session start\/resume/i)
|
||||
expect(SESSION_JOB_TOOL_DESCRIPTION).toMatch(/before claiming done or inviting archive/i)
|
||||
expect(SESSION_JOB_TOOL_DESCRIPTION).toMatch(/do not ask the operator to clean meters/i)
|
||||
})
|
||||
|
||||
it('hard-refuses action=set and never calls setSessionJob', async () => {
|
||||
const { setSessionJob } = await import('./sessionJob')
|
||||
const result = await handleSessionJobTool(
|
||||
{ action: 'set', jobKey: 'beets', label: 'beets import', remaining: 12 },
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(true)
|
||||
expect(result.text).toBe(SESSION_JOB_SET_REFUSED_TEXT)
|
||||
expect(result.text).toContain(SESSION_JOB_RUN_RECIPE)
|
||||
expect(setSessionJob).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('treats empty update as a heartbeat-only patch', async () => {
|
||||
const { updateSessionJob } = await import('./sessionJob')
|
||||
const result = await handleSessionJobTool(
|
||||
{ action: 'update', jobKey: 'beets' },
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(false)
|
||||
expect(result.text).toContain('updated')
|
||||
expect(updateSessionJob).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
sessionIdPrefix: 'sid-1',
|
||||
jobKey: 'beets',
|
||||
body: {}
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects startedAt on update', async () => {
|
||||
const result = await handleSessionJobTool(
|
||||
{ action: 'update', jobKey: 'beets', startedAt: 1_785_304_595_000 },
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(true)
|
||||
expect(result.text).toMatch(/startedAt is not valid over MCP/)
|
||||
})
|
||||
|
||||
it('steers update-before-create to job run recipe', async () => {
|
||||
const { SessionJobError, updateSessionJob } = await import('./sessionJob')
|
||||
vi.mocked(updateSessionJob).mockRejectedValueOnce(
|
||||
new SessionJobError('not_found', 'job not found')
|
||||
)
|
||||
const result = await handleSessionJobTool(
|
||||
{ action: 'update', jobKey: 'beets', remaining: 2 },
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(true)
|
||||
expect(result.text).toMatch(/session_job failed:/)
|
||||
expect(result.text).toMatch(/hapi job run/)
|
||||
expect(result.text).toMatch(/sleep stub/)
|
||||
})
|
||||
|
||||
it('rejects list with extra job fields', async () => {
|
||||
const result = await handleSessionJobTool(
|
||||
{ action: 'list', jobKey: 'beets' },
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(true)
|
||||
expect(result.text).toMatch(/does not accept job fields/)
|
||||
})
|
||||
|
||||
it('rejects clear with mutation fields', async () => {
|
||||
const result = await handleSessionJobTool(
|
||||
{ action: 'clear', jobKey: 'beets', status: 'completed' },
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(true)
|
||||
expect(result.text).toMatch(/only accepts jobKey and expectedRunId/)
|
||||
})
|
||||
|
||||
it('treats clear on missing job as idempotent (no job run recipe)', async () => {
|
||||
const { clearSessionJob } = await import('./sessionJob')
|
||||
const { SessionJobError } = await import('./sessionJob')
|
||||
vi.mocked(clearSessionJob).mockRejectedValueOnce(
|
||||
new SessionJobError('not_found', 'job not found')
|
||||
)
|
||||
const result = await handleSessionJobTool(
|
||||
{ action: 'clear', jobKey: 'beets' },
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(false)
|
||||
expect(result.text).toMatch(/already absent/)
|
||||
expect(result.text).not.toMatch(/hapi job run/)
|
||||
})
|
||||
|
||||
it('steers when not_found loses instanceof across MCP bundle boundaries', async () => {
|
||||
const { updateSessionJob } = await import('./sessionJob')
|
||||
vi.mocked(updateSessionJob).mockRejectedValueOnce(
|
||||
Object.assign(new Error('job not found'), {
|
||||
name: 'SessionJobError',
|
||||
code: 'not_found'
|
||||
})
|
||||
)
|
||||
const result = await handleSessionJobTool(
|
||||
{ action: 'update', jobKey: 'beets', remaining: 2 },
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(true)
|
||||
expect(result.text).toMatch(/hapi job run/)
|
||||
})
|
||||
|
||||
it('forwards null remaining so done/total can take over after a leftover meter', async () => {
|
||||
const { updateSessionJob } = await import('./sessionJob')
|
||||
vi.mocked(updateSessionJob).mockClear()
|
||||
const result = await handleSessionJobTool(
|
||||
{
|
||||
action: 'update',
|
||||
jobKey: 'beets',
|
||||
remaining: null,
|
||||
done: 3,
|
||||
total: 10
|
||||
},
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(false)
|
||||
expect(updateSessionJob).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
remaining: null,
|
||||
done: 3,
|
||||
total: 10
|
||||
})
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('sanitizes ANSI/OSC from MCP update text', async () => {
|
||||
const { updateSessionJob } = await import('./sessionJob')
|
||||
vi.mocked(updateSessionJob).mockResolvedValueOnce({
|
||||
sessionId: 'sid-1',
|
||||
job: {
|
||||
key: 'beets',
|
||||
label: '\u001b[31mimport\u001b[0m',
|
||||
status: 'running',
|
||||
detail: 'phase\u001b]52;c;QUFB\u0007done',
|
||||
remaining: 11,
|
||||
heartbeatAt: 2,
|
||||
startedAt: 1,
|
||||
updatedAt: 2
|
||||
}
|
||||
})
|
||||
const result = await handleSessionJobTool(
|
||||
{ action: 'update', jobKey: 'beets', remaining: 11 },
|
||||
'sid-1'
|
||||
)
|
||||
expect(result.isError).toBe(false)
|
||||
expect(result.text).not.toMatch(/\u001b/)
|
||||
expect(result.text).not.toMatch(/[\u0000-\u001f\u007f]/)
|
||||
expect(result.text).toContain('import')
|
||||
expect(result.text).toContain('phase')
|
||||
expect(result.text).not.toMatch(/QUFB/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* MCP surface for session-attached jobs (tiann/hapi#1404).
|
||||
* Same discovery class as ping_peer / inspect_peer — tool catalog, not docs-only.
|
||||
*
|
||||
* Hard contract: MCP cannot create a long-lived bar (action=set is refused).
|
||||
* Create meters with Shell + `hapi job run` (babysitter). MCP is for
|
||||
* update / clear / list after a supervisor or CLI wrapper owns heartbeats.
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import type { AttachedJobPatch } from '@hapi/protocol'
|
||||
import {
|
||||
SessionJobError,
|
||||
SESSION_JOB_RUN_RECIPE,
|
||||
formatSessionJobNotFoundHint,
|
||||
isSessionJobNotFoundError,
|
||||
clearSessionJob,
|
||||
listSessionJobs,
|
||||
updateSessionJob
|
||||
} from './sessionJob'
|
||||
import { formatJobLine } from './formatJobLine'
|
||||
|
||||
export const SESSION_JOB_TOOL_NAME = 'session_job'
|
||||
|
||||
/** Re-export for tests and steer copy. */
|
||||
export { SESSION_JOB_RUN_RECIPE }
|
||||
|
||||
export const SESSION_JOB_SET_REFUSED_TEXT = [
|
||||
'action=set is refused over MCP.',
|
||||
'Creating a progress meter for work that outlives this turn requires a babysitter',
|
||||
'that heartbeats while the agent is idle — use the Shell tool:',
|
||||
SESSION_JOB_RUN_RECIPE,
|
||||
'MCP session_job is only for action=update (progress/heartbeat/terminal status),',
|
||||
'action=clear, or action=list on a job that job run (or CLI set + self-heartbeat wrapper) already created.',
|
||||
'Bare set + nohup freezes the bar when the agent goes idle (wardrobe dogfood).',
|
||||
'Bare job run --done 0 --total N with no continuous update freezes 0/N under live heartbeats.',
|
||||
].join(' ')
|
||||
|
||||
/**
|
||||
* Self-contained tool description — agents select by matching intent to this text.
|
||||
* Write for selection, not for humans browsing a README.
|
||||
*/
|
||||
export const SESSION_JOB_TOOL_DESCRIPTION = [
|
||||
'Progress meter on THIS HAPI session for work that OUTLIVES the agent turn.',
|
||||
'Own-session only. CRITICAL: do NOT use action=set — it is refused.',
|
||||
'HYGIENE: call action=list on session start/resume AND before claiming done or inviting archive.',
|
||||
'If list shows status=running but the process is dead / you cannot prove it is alive, action=clear or update status=failed — do not ask the operator to clean meters.',
|
||||
'Leave live jobs with fresh heartbeats alone.',
|
||||
'To START a long job, use the Shell tool with:',
|
||||
SESSION_JOB_RUN_RECIPE,
|
||||
'(auto-heartbeats + completed/failed on exit). Idle agents cannot heartbeat.',
|
||||
'This MCP tool: action=update (progress/status), action=clear, action=list only.',
|
||||
'Fraction counts need continuous update/feeder; omit counts when unknown (use --progress unknown).',
|
||||
|
||||
'Never invent a percent or ETA. Not for todos, thinking, or short tool calls.',
|
||||
].join(' ')
|
||||
|
||||
export const sessionJobInputSchema: z.ZodTypeAny = z.object({
|
||||
action: z.enum(['set', 'update', 'clear', 'list']).describe(
|
||||
'set=REFUSED (use Shell hapi job run). update=heartbeat/progress/status; clear=remove; list=show jobs'
|
||||
),
|
||||
jobKey: z.string().trim().min(1).max(128).optional().describe(
|
||||
'Stable job key (alnum . _ -). Required for update/clear.'
|
||||
),
|
||||
label: z.string().trim().min(1).max(200).optional().describe(
|
||||
'Ignored for MCP set (refused). Optional on update.'
|
||||
),
|
||||
status: z.enum(['running', 'completed', 'failed']).optional().describe(
|
||||
'Job status on update (completed|failed to finish).'
|
||||
),
|
||||
done: z.number().nonnegative().nullable().optional().describe(
|
||||
'Units completed (pair with total). Pass null to clear a stale done count.'
|
||||
),
|
||||
total: z.number().positive().nullable().optional().describe(
|
||||
'Total units when both ends of a fraction exist. Pass null to clear.'
|
||||
),
|
||||
remaining: z.number().nonnegative().nullable().optional().describe(
|
||||
'Units left. Pass null to clear so done/total can take over (web prefers remaining).'
|
||||
),
|
||||
unit: z.string().trim().min(1).max(64).nullable().optional().describe(
|
||||
'Unit label (tracks, folders, files, …). Pass null to clear.'
|
||||
),
|
||||
detail: z.string().max(500).nullable().optional().describe(
|
||||
'Stage / current item text (not an ETA). Pass null to clear.'
|
||||
),
|
||||
expectedRunId: z.string().min(1).max(64).optional().describe(
|
||||
'Run generation fence for update/clear. Required when a manual wrapper stamped runId on set.'
|
||||
),
|
||||
startedAt: z.number().optional().describe(
|
||||
'Not used over MCP (set is refused). Correct clocks via CLI job set --started-at.'
|
||||
)
|
||||
})
|
||||
|
||||
export type SessionJobToolArgs = {
|
||||
action: 'set' | 'update' | 'clear' | 'list'
|
||||
jobKey?: string
|
||||
label?: string
|
||||
status?: 'running' | 'completed' | 'failed'
|
||||
done?: number | null
|
||||
total?: number | null
|
||||
remaining?: number | null
|
||||
unit?: string | null
|
||||
detail?: string | null
|
||||
expectedRunId?: string
|
||||
startedAt?: number
|
||||
}
|
||||
|
||||
function sessionJobMcpMutationFieldsUsed(args: SessionJobToolArgs): boolean {
|
||||
return [
|
||||
args.label,
|
||||
args.status,
|
||||
args.done,
|
||||
args.total,
|
||||
args.remaining,
|
||||
args.unit,
|
||||
args.detail
|
||||
].some((value) => value !== undefined)
|
||||
}
|
||||
|
||||
function sessionJobMcpListExtraFields(args: SessionJobToolArgs): boolean {
|
||||
return [
|
||||
args.jobKey,
|
||||
args.label,
|
||||
args.status,
|
||||
args.done,
|
||||
args.total,
|
||||
args.remaining,
|
||||
args.unit,
|
||||
args.detail,
|
||||
args.expectedRunId,
|
||||
args.startedAt
|
||||
].some((value) => value !== undefined)
|
||||
}
|
||||
|
||||
export async function handleSessionJobTool(
|
||||
args: SessionJobToolArgs,
|
||||
defaultSessionId: string
|
||||
): Promise<{ text: string; isError: boolean }> {
|
||||
// Own-session only — sessionId is not in the schema so auto-approve cannot
|
||||
// become a silent cross-session write (cold-review pass 3 Major).
|
||||
const sessionIdPrefix = (defaultSessionId || process.env.HAPI_SESSION_ID || '').trim()
|
||||
if (!sessionIdPrefix) {
|
||||
return {
|
||||
text: 'own session id required (set HAPI_SESSION_ID / call from a HAPI-wrapped session)',
|
||||
isError: true
|
||||
}
|
||||
}
|
||||
|
||||
// Hard footgun close: MCP must not create orphan meters (set + idle agent).
|
||||
if (args.action === 'set') {
|
||||
return { text: SESSION_JOB_SET_REFUSED_TEXT, isError: true }
|
||||
}
|
||||
|
||||
if (args.action === 'list' && sessionJobMcpListExtraFields(args)) {
|
||||
return { text: 'action=list does not accept job fields', isError: true }
|
||||
}
|
||||
|
||||
try {
|
||||
if (args.action === 'list') {
|
||||
const result = await listSessionJobs({ sessionIdPrefix })
|
||||
if (result.jobs.length === 0) {
|
||||
return { text: `session ${result.sessionId}\n(no jobs)`, isError: false }
|
||||
}
|
||||
const lines = result.jobs.map((job) => {
|
||||
const mark = result.primary?.key === job.key ? '*' : ' '
|
||||
return `${mark} ${formatJobLine(job)}`
|
||||
})
|
||||
return { text: `session ${result.sessionId}\n${lines.join('\n')}`, isError: false }
|
||||
}
|
||||
|
||||
if (!args.jobKey?.trim()) {
|
||||
return { text: 'jobKey is required for update/clear', isError: true }
|
||||
}
|
||||
const jobKey = args.jobKey.trim()
|
||||
|
||||
if (args.startedAt !== undefined) {
|
||||
return {
|
||||
text: 'startedAt is not valid over MCP (set is refused; use CLI job set --started-at)',
|
||||
isError: true
|
||||
}
|
||||
}
|
||||
|
||||
if (args.action === 'clear') {
|
||||
if (sessionJobMcpMutationFieldsUsed(args)) {
|
||||
return {
|
||||
text: 'action=clear only accepts jobKey and expectedRunId',
|
||||
isError: true
|
||||
}
|
||||
}
|
||||
const result = await clearSessionJob({
|
||||
sessionIdPrefix,
|
||||
jobKey,
|
||||
...(args.expectedRunId !== undefined
|
||||
? { expectedRunId: args.expectedRunId }
|
||||
: {})
|
||||
})
|
||||
return { text: `cleared ${jobKey} on ${result.sessionId}`, isError: false }
|
||||
}
|
||||
|
||||
// update
|
||||
const body: AttachedJobPatch = {
|
||||
...(args.label !== undefined ? { label: args.label } : {}),
|
||||
...(args.status !== undefined ? { status: args.status } : {}),
|
||||
...(args.done !== undefined ? { done: args.done } : {}),
|
||||
...(args.total !== undefined ? { total: args.total } : {}),
|
||||
...(args.remaining !== undefined ? { remaining: args.remaining } : {}),
|
||||
...(args.unit !== undefined ? { unit: args.unit } : {}),
|
||||
...(args.detail !== undefined ? { detail: args.detail } : {}),
|
||||
...(args.expectedRunId !== undefined
|
||||
? { expectedRunId: args.expectedRunId }
|
||||
: {})
|
||||
}
|
||||
// Empty body is a heartbeat-only update; hub stamps heartbeatAt.
|
||||
const result = await updateSessionJob({ sessionIdPrefix, jobKey, body })
|
||||
return {
|
||||
text: `updated ${formatJobLine(result.job)} on ${result.sessionId}`,
|
||||
isError: false
|
||||
}
|
||||
} catch (error) {
|
||||
if (isSessionJobNotFoundError(error)) {
|
||||
if (args.action === 'clear') {
|
||||
return { text: 'job is already absent; nothing to clear', isError: false }
|
||||
}
|
||||
return {
|
||||
text: `session_job failed: ${formatSessionJobNotFoundHint('update')}`,
|
||||
isError: true
|
||||
}
|
||||
}
|
||||
const message = error instanceof SessionJobError
|
||||
? error.message
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: String(error)
|
||||
return { text: `session_job failed: ${message}`, isError: true }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user