Files
hapi/docs/guide/session-jobs.md
T
weishu 35898c09cd feat(android): web-parity presence badges, sort/filter and attached jobs
The home list showed presence only for connected sessions, offered no
sort or status choices, and ignored session-attached jobs. Its strict
SessionPatch parser also rejected every `attachedJob` SSE patch, so each
job heartbeat fell back to a REST list refetch.

- Presence badge follows web #2296: solid green pulsing while working,
  solid blue pulsing for background tasks only, a green ring when
  connected and waiting, and a power mark when stopped or archived.
- The Sort & filter sheet adds Show (all / active only / archived only)
  and Unread only next to machines and dates, then Sort by (last message
  or date created) and Active first (on by default; manual pins still
  lead). Sort and Active first persist app-wide in hapi_prefs; filters
  stay transient, keep the open session listed, and Reset leaves the
  order alone. Search keeps relevance with the base tie-break. The share
  picker keeps the base order.
- Decode AttachedJob on summaries and the versioned `attachedJob` patch,
  applied only when strictly newer, as on web. Full-session events keep
  the row's job. A running job counts as working on the badge and as
  active for the Show filter (web #1404), and adds a row line with
  label, remaining or percent, elapsed time and a thin bar, amber with
  "no heartbeat" after 15 minutes.
- HomeFilterWindowTest's click helper now scrolls back once it reaches
  the end; the taller sheet otherwise stranded targets above the
  viewport.
- Docs describe the Android sheet, row and job display.
2026-11-11 09:40:45 +08:00

19 KiB
Raw Blame History

Session-attached jobs

Hub-persisted progress for work that outlives the agent — batch imports, nohup scripts, long drains — so the session list still shows something truthful while the chat is idle (active: false).

This is not in-agent thinking progress, todos, or backgroundTaskCount. Those die when the agent disconnects. Attached jobs live on the hub until you clear them.

Upstream: tiann/hapi#1404.

Relation to A2A (not work advertisements)

HAPI's Agent-to-Agent control plane (discussion #1332) is a different object family. Do not merge them.

Session-attached jobs (#1404) A2A work_ad (Layer 1)
Store session_jobs events / work-graph ledger
Surface SessionSummary.attachedJob (list chrome) Durable collaboration ledger
Question answered "Is a long process still running on this session, and how far?" "What is this session claiming about turn/project work for peers/overseer?"
Progress Heartbeats + honest counts / indeterminate Status vocabulary (in_progress, done, failed, stale, …)
Silence UI amber after ~15m without heartbeat; status stays running until explicit exit expires_at → stale / unknown — silence is not failure
Self-report Optional counts/detail; hapi job run exit code is machine fact Optional AGENT_NOTIFY_SUMMARY elevation (stays optional forever)

Jobs enrich Layer 0 session summaries (same layer as cite / inspect / ping). They are not Google A2A Tasks, and they are not a substitute for handoffs or work ads. Do not write job heartbeats into the A2A ledger. A privileged reader may observe attachedJob later; workers still must not poll the ledger as a work queue.

When to attach

Attach a job before (or immediately when) you start process-shaped work that will keep running after the agent goes idle:

Attach Do not attach
nohup / setsid / systemd oneshot that runs for hours–days A tool call that finishes in this turn
Beets / rclone / compile / migrate / download batches Normal coding edits and tests
External daemon you own for this session's goal Claude/Codex Ctrl+B-style background tools

If the operator would reopen the chat only to ask "how's it doing?", it belongs here.

Which session id (contract)

Attached jobs bind to the hub session row the operator sees — the UUID in the web URL /sessions/<id>, the session list tile, and the chat transcript. That row is the only target for PUT/PATCH/DELETE /api/sessions/:id/jobs/... and the only place attachedJob appears in the UI.

Surface Session id source Must match operator chat row
Shell hapi job … First positional arg; docs use "$HAPI_SESSION_ID" Yes
MCP session_job Owning hapi CLI client.sessionId (stdio bridge is not a second id) Yes
HAPI_SESSION_ID env Exported by exportHapiSessionEnv when the session CLI bootstraps Yes — this chat, not an internal worker row

Intended: one hub row per operator chat. Runner resume/spawn passes existingSessionId so bootstrap, MCP bridge, and HAPI_SESSION_ID all equal the row the web UI opened.

Known bug (remote Cursor runner): shell HAPI_SESSION_ID can point at a runner worker row while the operator watches a different hub chat row. Jobs on the worker id update a session the operator is not viewing; MCP session_job on the chat row still works because the bridge is wired to the chat client.sessionId. Until fixed, pass the chat URL uuid explicitly to hapi job instead of trusting $HAPI_SESSION_ID. Hub merge/clear redirects (jobsTransferredToSessionId, supersededBySessionId) apply only when metadata links rows — not for unrelated live duplicates.

Agent contract (specification)

Treat this like ping_peer / inspect_peer: it is first-class HAPI tooling, not a docs footnote.

CLI supervisor (required for process-shaped work)

hapi job run registers the job, heartbeats on a timer while the child runs, then marks completed/failed from the exit code. An idle agent cannot heartbeat. Heartbeats do not advance --done / --total — those flags on job run are initial meter state only.

Prefer "$HAPI_SESSION_ID" only when it matches the operator chat URL uuid. Remote Cursor runner: pass /sessions/<id> explicitly (see "Which session id").

Progress mode (required on run / set)

--progress is required on create. Omission used to default to indeterminate stripes and hid known-duration countdowns (dogfood postmortem 2026-11-08). Pick deliberately:

Mode Flags List chrome
unknown no counts / no --until running · elapsed + indeterminate stripes
fraction --remaining N --total M or --done N --total M determinate fill
until --until <ISO-8601|epoch-ms> determinate countdown (s); job run heartbeats re-stamp remaining

The bar and stripes are the Web list. The native lists show the same job as one text line (label · remaining or percent · elapsed, amber with no heartbeat after ~15m) and a working presence badge: Android adds a thin bar under the row's meta line (Material indeterminate animation instead of stripes); iOS puts the line in place of the project name, without a bar.

Alive-only / indeterminate (--progress unknown)

hapi job run "$HAPI_SESSION_ID" beets \
  --label 'beets import' \
  --progress unknown \
  --detail 'phase: …' \
  -- ./beets-import.sh

List shows running · elapsed plus a subtle indeterminate progress bar: a real track with soft diagonal stripes that drift slowly (HTML5 <progress> indeterminate vibe, quiet contrast). Means "still moving," claims zero percent. Use this when size is genuinely unknown — not for a wall-clock deadline (use --progress until).

Fraction / display bar (0→100%)

--done / --total (or --remaining + --total) only move the bar when something keeps PATCHing them for the whole run. Forbidden for a display meter:

# WRONG — looks like a progress bar; stays frozen at the launch stamp (often 0/N)
# under live heartbeats while the child actually works.
hapi job run "$HAPI_SESSION_ID" beets \
  --label 'beets import' --progress fraction --done 0 --total 1787 -- \
  ./beets-import.sh

Required for a moving fraction bar — pick one:

  1. Portable (upstream): hapi job run --progress unknown while the child runs, plus a continuous updater (hapi job update / MCP session_job update, or your own JSONL→update feeder) from the first progress event through exit. Or --progress fraction only if that updater keeps --done/--remaining moving.
  2. Known deadline: --progress until --until <ISO> (heartbeats re-stamp remaining; optional --started-at <epoch-ms> = window start on mid-window re-attach).
  3. Optional estate helper (not part of upstream HAPI): some operators ship hapi-job-run-metered locally to refuse fraction meters without a feeder. Do not assume it exists on PATH for every HAPI install.
# Portable fraction (updater required from t=0):
hapi job run "$HAPI_SESSION_ID" beets --label 'beets import' --progress unknown -- ./beets-import.sh &
# …and from t=0, something continuously: hapi job update … --done N --total 1787

# Dogfood / countdown window (numeric sleep N without until is refused):
hapi job run "$HAPI_SESSION_ID" dogfood-1424-48h \
  --label 'dogfood #1424 48h' --progress until --until 2026-11-09T21:20:14Z \
  --wake-on-terminal -- sleep 999999

# Mid-window re-attach — keep the original 48h denominator:
WINDOW_START_MS=$(( $(date -u -d '2026-11-07T21:20:14Z' +%s) * 1000 ))
hapi job run "$HAPI_SESSION_ID" dogfood-1424-48h \
  --label 'dogfood #1424 48h' --progress until --until 2026-11-09T21:20:14Z \
  --started-at "$WINDOW_START_MS" --wake-on-terminal -- sleep 999999

Non-JSONL children need an adapter (line regex → job update, dual writer, or fall back to alive-only). Do not invent a fake percent.

Exit ≠ semantic failure: job run stamps failed on nonzero exit even when the batch mostly succeeded (e.g. indexer errors > 0 but run completed). Prefer the child exiting 0 when the run finished and putting item-error counts in --detail / logs; do not teach agents to ignore exit codes blindly.

Wardrobe failures (frozen / lying bars)

Do not:

  • MCP session_job set or one-shot CLI set + background the real work (no heartbeat).
  • hapi job run --done 0 --total N -- cmd with no continuous count writer (frozen 0/N under a live heartbeat — the common agent footgun).
  • hapi job run --progress unknown -- sleep 150747 (or any numeric sleep N) — that is a known-duration countdown; CLI refuses it. Use --progress until --until … (or sleep infinity under unknown).
  • Wrap hapi-restart-hub / hapi-use-worktree / hapi-use-driver / hapi-watch-activate-driver inside hapi job run. The hub is down exactly when the terminal completed/failed PATCH must land → ECONNREFUSED → zombie running meter (CLI refuses these argv tokens). Run remat/work under the job; run the hub restart after the job exits (same shape as soup remat #205).
  • Claim done / invite archive while a zombie running meter remains.

If the hub is briefly unreachable for other reasons after the child exits, job run keeps retrying the terminal PATCH for up to ~10 minutes (connection / 502–504). If it still cannot mark the meter, the supervisor exits 1 even when the child exited 0 — do not treat that as a silent success.

Hygiene (list on resume / before done)

Agents must inventory their own jobs — do not wait for the operator to notice a sticky running meter before archive (delete returns 409 while a job is running).

  1. Call session_job action=list (or hapi job list <session>) on start/resume and again before claiming done / inviting archive.
  2. If a job is running but the process is dead (or you cannot prove it is alive): clear or update with status: failed. Prefer clear when progress is meaningless. Never ask the operator to clean meters.
  3. Leave live jobs with fresh heartbeats alone; mention them if still running when you summarize.

Hub does not auto-clear silent jobs (quiet legitimate long runners must not be murdered). A structured stale flag on list is a follow-up; until then, agent judgment + the ~15m UI amber threshold apply.

MCP (update / clear / list only)

Tool name: session_job (Claude: mcp__hapi__session_job; Codex: functions.hapi__session_job; OpenCode/ACP: hapi_session_job).

action=set is refused over MCP. Start the meter with Shell + hapi job run (above). Then you may:

{ "action": "update", "jobKey": "beets", "done": 1638, "total": 1787 }
{ "action": "update", "jobKey": "beets", "status": "completed" }
{ "action": "clear", "jobKey": "beets" }
{ "action": "list" }

CLI manual path (self-heartbeating wrapper only)

Only when you own a wrapper that calls update at least every ~10 minutes (not an idle agent). Mint one UUID per wrapper run and fence every PATCH so a key-reuse cannot steal progress:

RUN_ID="$(uuidgen)"   # or python -c 'import uuid; print(uuid.uuid4())'

hapi job set "$HAPI_SESSION_ID" beets \
  --label 'beets import' \
  --progress fraction \
  --run-id "$RUN_ID" \
  --remaining 150 --done 1637 --total 1787 --unit units \
  --detail 'album: Some Artist - Some Album'

hapi job update "$HAPI_SESSION_ID" beets \
  --expected-run-id "$RUN_ID" \
  --remaining 149 --done 1638 --detail '…'

hapi job update "$HAPI_SESSION_ID" beets \
  --expected-run-id "$RUN_ID" \
  --status completed
# or
hapi job clear "$HAPI_SESSION_ID" beets --expected-run-id "$RUN_ID"

Same auth as hapi ping-peer (HAPI_API_URL / CLI_API_TOKEN or hapi auth login).

Wake owning session on terminal (opt-in, #1489)

By default jobs are meter-only: terminal completed/failed does not resume the agent. For DJ / beets-style batches where the idle owner must verify and start the next chunk, opt in:

hapi job run "$HAPI_SESSION_ID" beets \
  --label 'beets import' \
  --progress fraction \
  --wake-on-terminal \
  --wake-prompt 'If exit looked clean, start the next album batch.' \
  --remaining 150 --done 1637 --total 1787 --unit units \
  -- ./beets-import.sh

When the hub accepts terminal status (and the opt-in was set on that run):

  1. Claims a one-shot wake for that runId (retries / duplicate terminal PATCH do not re-fire).
  2. Resumes the owning session if inactive (same resume path as ping-peer).
  3. Posts a user message naming job key, status, last detail, plus optional --wake-prompt.

This does not treat heartbeats as thinking. Default remains off until dogfood proves the loop.

Progress honesty (tiers)

What you know --progress + flags What the list shows
Countable leftover fraction + --remaining N --total M 150 units left · 2d 4h + fill
Countable fraction fraction + --done N --total M 91% · 1637/1787 units · 2d 4h + fill
Known deadline until + --until <ISO|epoch> countdown fill (s)
Stage only / unknown size unknown + --detail + heartbeats running · 2d 4h + indeterminate stripes

Determinate fill: left→right width moves only when total is set and something keeps sending --done/--total or --remaining/--total (update/feeder), not when those flags appear only on job run launch. Indeterminate stripes: when there is no honest fraction (total missing), the same track slot shows soft diagonal stripes that drift slowly with no claimed percent — not spinner-only, not an empty track, and not a loud sliding chunk. --remaining alone (without total) updates the text label and keeps the striped bar; it is not a percent.

Elapsed is always derived from hub startedAt (wall clock). It is not an ETA and there is no time-remaining field - operators get "how long has this been going" plus whatever honest count/detail you report, without a fake completion estimate.

Rules:

  • Prefer remaining+total (via continuous update) when the operator cares about "how much left" and you know the denominator.
  • Prefer done+total (via continuous update / your feeder) when you want visible byte-style progress.
  • Do not put --done/--total on bare job run and walk away — that freezes the launch stamp under live heartbeats.
  • Do not send remaining alone expecting the bar to move — include total or use done/total.
  • If you only know a stage name, put it in --detail and keep heartbeating — do not fake total=100.
  • There is no --percent flag and no ETA / time-remaining field. Inventing either would train agents to lie.

startedAt / elapsed (late attach)

Elapsed is honest wall clock from hub startedAt. Dogfood gotcha (music drain / beets):

Call startedAt behavior
PATCH / hapi job update Rejected if you send startedAt (unrecognized_keys). Progress/heartbeat only.
PUT / hapi job set without --started-at Keeps the existing clock when the job already exists; first create stamps now.
PUT / hapi job set --started-at <epoch-ms> Sets/corrects the clock (explicit body field).
DELETE then PUT with startedAt Always works — including older hubs that ignored PUT corrections.

Prefer update for heartbeats so you never wipe the clock. Only correct historical start when a late attach stamped attach-time instead of process start:

# epoch ms for when the drain actually started (example)
START_MS=1785304595000

hapi job clear "$HAPI_SESSION_ID" beets
hapi job set "$HAPI_SESSION_ID" beets \
  --label 'beets import' \
  --progress fraction \
  --started-at "$START_MS" \
  --remaining 0 --done 1787 --total 1787 --unit units \
  --status completed \
  --detail 'ALL_DONE'

# or, on hubs that honor explicit PUT startedAt without delete:
hapi job set "$HAPI_SESSION_ID" beets \
  --label 'beets import' \
  --progress fraction \
  --started-at "$START_MS" \
  --remaining 12 --done 1775 --total 1787 --unit units

Then keep using hapi job update for counts/detail/status.

Heartbeat recipe

Wrap the long process so something calls hapi job update on a timer (or on each unit completed). Minimum viable indeterminate job:

RUN_ID="$(uuidgen)"
hapi job set "$HAPI_SESSION_ID" rsync-backup \
  --run-id "$RUN_ID" --label 'rsync backup' --progress unknown --detail 'phase: copy'
# in a loop / cron / companion script:
hapi job update "$HAPI_SESSION_ID" rsync-backup \
  --expected-run-id "$RUN_ID" --detail "phase: copy · $(date -u +%H:%M)Z"

When the process exits, mark completed/failed or clear. A stuck green/amber chip with a dead PID is worse than no chip.

CLI / API reference

hapi job set <session> <job-key> --label <text> --progress unknown|fraction|until […]
hapi job update <session> <job-key> [--expected-run-id UUID] [progress flags]   # no startedAt
hapi job clear <session> <job-key> [--expected-run-id UUID]
hapi job list <session>
hapi job run <session> <job-key> --label <text> --progress unknown|fraction|until […] -- <cmd>…
hapi job --help

Needs a hub/CLI build that includes job (soup / feat — global npm releases may lag).

Method Path Notes
GET /api/sessions/:id/jobs List jobs
PUT /api/sessions/:id/jobs/:jobKey Upsert (AttachedJobUpsert; optional startedAt, runId)
PATCH /api/sessions/:id/jobs/:jobKey Progress/heartbeat (AttachedJobPatch; no startedAt; optional expectedRunId)
DELETE /api/sessions/:id/jobs/:jobKey?expectedRunId= Clear (optional fence; 409 on run mismatch)

Primary running job is enriched onto GET /api/sessions as attachedJob and pushed on session-updated SSE patches.

Sidebar pin (Settings → Display)

Attached jobs ship with a tri-state "Pin in-progress sessions" control (not a yes/no):

Mode Floats to In progress
Off Nothing
Long-running jobs (default) Sessions with a running attached job (even when the agent is idle)
Working & pending Jobs plus thinking / pending / in-agent background tasks (storage key all). Quiet connected stays in project folders.

Unset preference defaults to Long-running jobs — that is the product stand for this capability. Legacy true maps to Working & pending; legacy false maps to Off.