Repository navigation
Conversation
A message scheduled with the clock button only went out if the session happened to be running when it came due. The 5s tick releases mature rows into the session's Socket.IO room and nudges a live session process; when no process is attached, the row waits until something else opens the session — the user, or the next message they send, when the stale prompt goes out alongside it. - messageService: releaseMatureScheduledMessages returns the sessions it released a row to. Held and delivery-gated sessions are skipped before that, so they are never resumed. - syncEngine: on the same tick, the inactive ones go through a SessionWakeGate that resumes each session the way the job-complete wake (tiann#1489) does — resume, wait until active — and leaves delivery to the existing release path on its next tick. - SessionWakeGate: one attempt per session at a time, and a 15s → 60s backoff after a failure, so a sleeping machine costs one cheap no_machine_online rejection per minute instead of one per tick. - docs: the scheduled-matured row of the SSE contract and the composer guide's limits. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
The panel's hint still described the old behaviour (the CLI catches up the next time it connects). It now matches what the hub does when a scheduled message comes due and the session is not running. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
Scheduled messages are one-shot and capped at 7 days. There was no way to ask for "this prompt every 30 minutes" or "send these three prompts, ten minutes apart" — the recurring-runs gap in tiann#1524. A task is a schedule the hub owns per session, stored in a new session_tasks table (schema v36→v37): - repeat: one prompt on a fixed grid (startAt + k × intervalMs), optionally bounded by maxRuns. A slot that comes due while the previous prompt is still waiting to be taken is skipped, so a busy agent never has two of the task's prompts queued. - queue: prompts sent in order, each intervalMs after the CLI acknowledged taking the previous one. - shared: SessionTask / CreateSessionTaskRequest / UpdateSessionTaskRequest schemas, the session-tasks-changed SSE event, and nextRepeatRunAt (a late run skips the slots it missed and later runs stay on the original grid). - store: SessionTaskStore. A task has at most one prompt outstanding (pending_local_id), and markSent is a compare-and-set so two overlapping ticks cannot both count a send. - sync: SessionTaskRunner on the existing 5s tick. It inserts an ordinary user message (localId hapi-task:<taskId>:<n>), which makes the insert idempotent across a hub restart, and steps the task forward only on that row's real invokedAt. The prefix is therefore exempt from the session-end sweep, like hapi-job-wake:. An inactive session is resumed first through the SessionWakeGate. - no_machine_online keeps the task due with lastError 'machine_offline'; a session that cannot be resumed pauses the task with 'session_unavailable'. Finished tasks delete themselves, and a merged-away session's tasks follow it to the survivor. - web routes: GET/POST /sessions/:id/tasks and PATCH/DELETE /sessions/:id/tasks/:taskId, scoped to the session's access check. Deleting a task cancels a prompt the agent has not taken yet. - docs: REST and SSE client contracts. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
…unts Both halves of the next step (the hub that serves these routes and the web app that calls them) are written against this commit, so the shapes are fixed here first: - SessionTask gains startAt (when the task was meant to run first). - UpdateSessionTaskRequest takes any subset of the editable fields: paused, text (repeat), items (the prompts a queue has not sent yet), intervalMs and maxRuns (null clears it). - SessionTaskDeleteResponse reports what became of a prompt the agent had not taken: none, cancelled, taken or unconfirmed. - SessionTaskRun and its list query/response describe the run history. - SessionTaskErrorCode gains session_archived, prompt_indeterminate and prompt_not_taken; none of the codes pauses a task by itself any more. - SessionSummary gains activeTaskCount and nextTaskRunAt, next to the scheduled-message fields. - SESSION_TASK_MAX_ACTIVE_PER_SESSION caps the tasks a session may hold. Only shared/ compiles cleanly at this commit: the hub and web follow in their own commits. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
The phase-1 audit confirmed a set of hub defects around the task scheduler and the wake gate. This fixes them; the wire shapes are the ones b4eb155 already fixed (startAt, SessionTaskDeleteResponse, the six error codes). - The wake gate answers with an explicit outcome (active, refused with a reason, or deferred) instead of a bare boolean. It refuses an archived session with `session_archived` before calling resumeSession (archiving used to be undone by the next due task, which respawned the session and spent tokens unattended), waits on and keys its state by the id a resume rotates the session to, and runs at most 3 resumes at once across the hub. - deliver re-reads the task after the wake and right before the insert, so a task deleted or paused while its session was being resumed sends nothing; a prompt whose send could not be recorded (markSent lost the compare-and-set) is taken back instead of being left untracked. - settle looks a pending prompt up where it actually lives (an OpenCode /clear redirects it to the replacement session) instead of counting it as cancelled, records `prompt_indeterminate` for a row whose outcome is unknown, stops waking after three wakes the agent did not take the prompt in (`prompt_not_taken`), and puts the wake failure of a pending prompt on the task (`machine_offline`, `session_unavailable`) once. - Nothing pauses a task any more: `resume_unavailable` can be transient, so the task stays due with the error and the gate's backoff paces the retries. - findRunnable runs two indexed queries (pending rows; active rows due now) merged in a fixed order, and a test pins the query plan of both; the single OR query scanned the whole table on every 5s tick. - A task keeps its first-run time (`start_at`, schema v37→v38), so resuming a task that has not run yet keeps it instead of firing at once. - DELETE answers what became of a pending prompt. - Tasks moved into a session by a merge or a clear are announced with `session-tasks-changed` for the survivor. - The task routes take at most a 1 MB body (413) and refuse a queue with more than 50 prompts before Zod validates the elements. - Archived sessions are held out of the scheduled-message release too. Tests whose phase-1 premise changed are rewritten to pin the new behaviour: the gate tests assert the outcome instead of a boolean, the runner test that expected `resume_unavailable` to pause now expects the task to stay due, and the store tests pause and resume through `update` (`setPaused` and `pauseWithError` are gone). Migration tests pin that the v26 fast path and the legacy chain create session_tasks with the column. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
Phase 2 of session tasks: the controls the first cut lacked, and the record of what a task did. - `session_task_runs` (schema v38): one line per prompt sent (stamped `taken_at` when the CLI acknowledges it, flipped to `cancelled` when the user or a delete removes it before that), per skipped repeat slot (`previous_prompt_waiting`) and per run that could not go out, written when the failure is new for the task rather than on every tick. Retention: 500 rows per session, rows older than 30 days go at most once an hour. Runs follow their session through a merge like tasks do. - `GET /api/sessions/:id/tasks/history?limit=` (1–200, default 50), newest first. - PATCH edits a task: `text` (repeat), `items` (the prompts a queue has not sent yet; the sent prefix is kept), `intervalMs` (re-anchors a task that has already run and has nothing pending), `maxRuns` (null removes it; below what already ran is `invalid_max_runs`, equal to it ends the task once the pending prompt is taken or at once when nothing is pending); a field of the other kind is `wrong_task_kind`. - `POST .../tasks/:taskId/run` sends the next prompt now (409 `prompt_pending` while one is waiting). - At most 20 active tasks per session (`too_many_tasks`). - `activeTaskCount` / `nextTaskRunAt` on every session-list and content-search summary, next to the scheduled-message fields. - REST, SSE and error contract docs for all of the above. Both halves are written against b4eb155; shared gains two additive exports (the preview length and the run outcome type) and no shape change. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
The review of the phase-2 hub half found three ways an edit or a run-now
request got around what pause and the per-session cap promise.
- PATCH `{ intervalMs }` on a paused task that has run once resumed it:
the re-anchor checked `!patch.paused`, which is true for an absent
field, and wrote an active state. An edit form that submits only the
changed field silently started an unattended sender again. The
re-anchor now applies only to a task that may run (it is active, or
the same request resumes it).
- Resuming a task with `maxRuns` equal to what already ran skipped the
end-at-once check (`!resuming`), so the task ran one prompt past its
limit. The check no longer looks at how the task became active.
- The cap of 20 active tasks was enforced on create only. Resuming a
task through PATCH (400) and running a paused task now (409) count
against it as well and answer `too_many_tasks`.
- `nextTaskRunAt` could be a past time for as long as a due task was
blocked (machine offline, session archived); it is clamped to now, so
it means "due now or later" like `nextScheduledAt` never lies.
The REST and error contract docs follow. One engine test compared
`startAt` with a `Date.now()` read a millisecond earlier and failed
about once in twenty runs; it checks the range now.
via [HAPI](https://hapi.run)
Co-Authored-By: Claude Code <noreply@anthropic.com>
The scheduler's history and error reporting had a few places where the line a user reads did not match what happened, and one where the hub gave up for good. - A repeat task whose prompt sat on an archived session, or had reached `prompt_not_taken`, wrote one `skipped` row and one `session-tasks-changed` event per interval, indefinitely (520 rows and 522 events in a night), and the per-session cap of 500 soon evicted the real history. The grid still moves on in those states, but no row and no event are written for the slot. While the hub is still trying (machine offline, paced by the wake backoff) a skip is still a line. - A failed run of a queue task previewed the first prompt, because the preview defaulted to `items[0]`; it now previews the prompt that was due, the one after the last sent. - A resume that threw or did not come up within 30 s was reported as `send_failed` although nothing was sent; it is `session_unavailable`, like every other resume failure. `send_failed` stays for an insert that threw. - `prompt_not_taken` survived an explicit resume: the update cleared the error, but the in-memory wake count was still at three, so the next tick re-set the error without waking the session. The runner exposes `forgetPrompt`, which the engine calls on a resume with a prompt pending and on delete (nothing is left to count for). - A pause that landed while the prompt was being inserted (seconds, with input translation on) still sent it, because the re-read ran before the insert only. The task is re-read after it; a prompt of a task that is no longer active is taken back like one whose send was not recorded. The take-back also looks the row up where it lives: the replacement session an OpenCode /clear redirected it to, not the source. Tests whose premise changed are rewritten to pin the new behaviour: the history test that expected `resume_failed` to read `send_failed` now expects `session_unavailable`, and the runner test that pinned "a prompt on its way when the task was paused stays tracked" now expects it taken back. The engine test harness gains a confirmed-cancel stub (a test that ends with a send in flight used to log a failed take-back). via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
Two store-side review points on the migration step and the query-plan pin. - The v37→v38 backfill dated every existing task's `start_at` from its creation. A task created under phase 1 with a first run still in the future had that time only in `next_run_at`, so after the upgrade a pause and resume sent it at once instead of at the time its user chose — the case `start_at` was added for. A task that has not run yet now takes its planned first run from `next_run_at`; one that has run is still dated from its creation. The migration test pins both, and the paused never-run case that has no next run to take. - The hub-4 test ran `EXPLAIN QUERY PLAN` on simplified SQL, not on the statements `findRunnable` executes, so a later edit of the real WHERE could have fallen back to a table scan with the test still green. The two statements are exported constants the store runs and the test explains; changing the due query back to a single OR fails it. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
`Bun.build({ compile })` writes a `<hash>-00000000.bun-build` file next
to its outfile and renames it when it is done. The executable case of
`passkey.bundle.test.ts` compiles into the package directory, so when
that case fails (it does under the full parallel run on some machines)
a 63 MB Mach-O stays next to the sources — and `git add -A` swept one
into the previous commit on this branch. The blob was dropped from that
commit before anything was pushed; `**/*.bun-build` is ignored from now
on.
The repository has no hooks path configured, so a pre-commit hook would
not run for anyone; the guard is a hub test instead, which CI runs: the
artifact path is ignored, and no `*.bun-build` file is tracked. It
skips outside a git work tree.
via [HAPI](https://hapi.run)
Co-Authored-By: Claude Code <noreply@anthropic.com>
…ot resume A scheduled message that comes due while its session is inactive makes the hub resume the session, and a refused resume is retried with backoff for as long as the message waits. When the session cannot be resumed at all (the runner is online but the agent will not start, the session is gone or not ours), that went on forever and the user saw nothing: the message simply never went out. The wake of a session with a mature scheduled message now reports such a refusal (every code that reads `session_unavailable` for a task) through the existing `toast` SSE event: title `Scheduled message not sent`, body naming the message and the session, `url` opening it, once per scheduled message and hub process. A machine that is offline clears by itself and an archived session is a state the user chose, so neither is reported. The toast is offered again on the next refused attempt while no visible connection has received it, so "once" means the user was told once, not that the hub emitted it once into an empty room. `EventPublisher.sendToast` delegates to `SSEManager.sendToast`; a toast is neither broadcast nor recorded nor replayed, so it does not go through `emit`. `taskErrorCodeFor` is exported for the engine to read the same classification the scheduler uses. The REST and SSE contracts document the frame. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
PATCH `{ paused: false, maxRuns: runCount }` on a paused task was refused
with `too_many_tasks` when the session already held 20 active tasks,
although the task would have ended at once: the cap was a uniform check
that ran before the edit was computed, so it only ever saw the paused
task about to become active.
The cap now looks at the state after the change. A resume counts, as
before; a resume that ends the task at once (the limit brought down to
what already ran, nothing pending) leaves the session as it was and
fits; an edit that keeps a task paused was never refused and is now
pinned to stay that way. A resumed task that ends only once its pending
prompt is taken is active until then, and still counts.
The REST and error contract docs follow.
via [HAPI](https://hapi.run)
Co-Authored-By: Claude Code <noreply@anthropic.com>
… an hour A repeat task whose previous prompt is still waiting skips the slot that comes due. Each skip was one `skipped` row and one `session-tasks-changed` event: a machine asleep overnight on a one-minute task wrote 480 rows and evicted the real history from the 500-row per-session cap. The previous fix only silenced the two states in which the hub had stopped trying (`session_archived`, `prompt_not_taken`); the same flood stayed for a machine that was offline, or any prompt that simply keeps waiting. One rule now covers every skip. The first slot skipped while a prompt waits is a line and an event; for as long as that same prompt keeps waiting, at most one further line an hour is written, and a slot that writes no line announces nothing. The grid moves on as before, and the next prompt's first skipped slot is a line again. The bookkeeping is per hub process, like the wake count, so a restart costs one extra line. `promptStuck` goes away with its special case, and the tests that pinned "no line while stuck" pin the new rule instead: the archived and `prompt_not_taken` cases write the first slot and one an hour, an eight-hour outage on a one-minute task writes eight lines, and a second prompt's first skip is written within the hour. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
The routes existed since phase 1 and the storage tables since v37, but the README's route list jumped from Messages to Permissions and the storage overview did not mention either table, so the hub's own map had a hole where a whole module lives. A "Session tasks" block next to the other route modules (what a task is, where the scheduler and the wake gate live, the six routes, the SSE event and the list fields) and one storage bullet for `session_tasks` / `session_task_runs`. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
A task body over 1 MB with a declared Content-Length was refused from the header alone, before any of it was read. Bun closes a connection whose request body it did not read, and a close over unread data is a reset, which can reach the client before the answer does: a client that sends the whole body before it reads (Python's urllib) got a reset instead of the 413 in 5 to 11 of 12 attempts on a throwaway hub, while a client that read while sending, or sent chunked, got it every time. The route's answer was right; only its delivery was racy. The two task routes now read the body themselves instead of relying on hono's bodyLimit. A body within the limit is handed on buffered, whole, so the handler parses the same bytes; an oversize one is read to its end and discarded before the 413 goes out, declared length or not. The drain is bounded at 8 MB — above the about 4 MB the field limits can produce — so a sender far beyond the limit is still cut off, and meets the reset after all. The route tests drive the middleware with a stream that records how far the hub read it: a refused body is read to its end with and without a declared length, an endless one stops at the drain cap, and the largest schema-valid body arrives at the engine intact. The client contract documents the limit and the read. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
PATCH `{ paused: true, intervalMs }` on an active task that had already
run, with nothing pending, answered 200 with the task still active, and
it went on sending prompts although the caller had asked to pause it.
The schema and the contract allow any subset of the fields, so the
request is valid; only the web never sends the two together.
The pause wrote `state: paused, nextRunAt: null` into the change set,
and the re-anchor of a new interval then tested the state the task had
before the request, found it active, and overwrote the change set with
`state: active, nextRunAt: now + intervalMs`. The re-anchor is about a
task that may run after the request, so it now asks for that state: the
task stays active and the request does not pause it, or the request
resumes it. A task the request pauses cannot run after it, so there is
nothing to re-anchor and the pause stands; a task already paused keeps
its pause and only takes the interval, as before.
The engine test pins both kinds on the pause-plus-interval request and
the already-paused case. The contract's Edit bullet says which task a
new interval re-anchors.
via [HAPI](https://hapi.run)
Co-Authored-By: Claude Code <noreply@anthropic.com>
When a task's prompt row became indeterminate, the runner recorded `prompt_indeterminate` on the task, and nothing cleared it until the agent took the prompt or the user discarded it. Retry in the queued-message bar queues the row again, and from then on it is plainly waiting — the next tick even wakes the session for it — but the task went on saying the take was unknown. The web reads that error before `pending`, so the bar kept telling the user to retry or discard a prompt that was already queued, and offered Retry on a row that was no longer indeterminate. The window closed only when the agent got to the prompt. `settle` now clears the error when it finds the row queued or being dispatched: a row can only leave `indeterminate` through Retry (or through the agent taking it and the user discarding it, both of which return earlier), so a stale `prompt_indeterminate` there means the user retried the prompt. The clearing announces a change, once. The runner test retries an indeterminate prompt through both the dispatching and the queued lookup and checks that the error is gone while the prompt is still pending, with nothing announced on the tick after. The contract's error sentence notes that Retry clears the error at once. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
A repeat task whose previous prompt is still waiting skips the slot that comes due, and its next run moves on to the slot after it. b5d23909 limited the history line for that to the first skipped slot and then one an hour, and took the `session-tasks-changed` event with it. The task row still changed on every skipped slot, so a client that had fetched the task before kept the old `nextRunAt` for up to an hour: the session list, which reads a past time as "Due now", showed a task as due long after the hub had moved past that slot. The two are separate now. The history line keeps its rule; the event goes out for every skipped slot, because the next run moved each time. That is at most one event per interval of a stuck task (a minute at the least), on a par with the list refetches the web already makes for ordinary message events. The tests that pinned "no event while stuck" pin the new rule: one event per skipped slot, the hourly line unchanged. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
The runner keeps two things per task in memory: when it last wrote a skipped slot to the history, and when a failed send is due for a retry. Only `remove` forgot them, and the routes do not go through it: a delete and an edit that ends the task remove the row from the store directly, as does a session that takes its tasks with it. What was kept for those tasks stayed for the life of the hub process. A task id is never reused, so nothing of a deleted task could mislead a later one; this was a slow leak. Each tick now drops the entries of tasks that have no row. A task without bookkeeping costs no lookup, and a skipped slot or a failed send is rare enough that the maps stay small. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
The shared wire commit (b4eb155) added SessionTask.startAt and the SessionSummary fields activeTaskCount and nextTaskRunAt, so every web test fixture that builds one of those objects stopped typechecking. This only adds the fields: startAt on the three task fixtures, and a count of 0 with no next run on the summary fixtures, which is what a session without tasks carries. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
The hub asks the CLI whether it dropped a queued prompt and waited 500 ms
for the answer. A task's cancel (the user deleting a repeat or queue task,
or pausing it) is the one cancel that must be right: the answer is the only
proof that the prompt will not go out later. On a distant machine the round
trip takes about 330 ms; a little jitter and the hub gave up, marked the row
indeterminate, deleted the task all the same, and the prompt stayed in the
session's queue to run once the agent was free.
cancelQueuedMessage takes an optional `{ probeTimeoutMs }` that reaches every
probe it makes. Callers that pass nothing keep the 500 ms, so the
queued-message bar's own cancel is unchanged.
The branch for a session with no CLI socket in its room now says what it
did: it removed the hub's row with nobody to ask. The result carries
`unconfirmed: true`, because a wrapper that is alive with its socket down
(the company network reclaims long WebSockets) still holds the prompt in its
own memory and feeds it to the agent when the agent is free. The hub used to
report a plain `cancelled` there.
The message service tests time a CLI that answers after 900 ms against both
budgets, check that each of the three probes gets the budget it is given,
and pin the old shape for a caller without options.
via [HAPI](https://hapi.run)
Co-Authored-By: Claude Code <noreply@anthropic.com>
… back on pause A user deleted his repeat task and the hub said `cancelled`; the prompt went out all the same. Two ways that happened, both on the hub's side: - With no CLI socket in the session's room the cancel removed the hub's row and reported success. A wrapper that is alive with its socket down (the company network reclaims long WebSockets) still held the prompt in its own queue and fed it to the agent when the agent was free. - A pause stopped new prompts but left the one already inserted: for a user who presses Pause to make it stop, that is "I cancelled it and it still sent". A task's cancel now uses the patient probe (3000 ms, see the previous commit) and is honest about what it could not confirm. When no CLI confirmed that it holds no copy, the run row carries `cancel_unconfirmed` and the hub keeps the matter on a follow-up list: on every task tick, a CLI that is in the room is asked again (2000 ms). `removed` or `not-found` ends it (the row reads cancelled); `consumed` means the agent got there first (the row goes back to sent with its taken time); anything else waits for the next tick. After two minutes the hub gives up and the row keeps its marker. The list is rebuilt at hub start from the marked rows, so a restart loses nothing. Every change of a run row is announced with `session-tasks-changed`. A pause now takes the waiting prompt back when the CLI confirms the cancel: the run row is cancelled and the task is as before the send (pending cleared, run count one lower, last run the one that still counts), so a resumed queue sends that same prompt again and a repeat task does not count a prompt that never reached the agent. The runner leaves the task alone meanwhile (`SessionTaskRunner.hold`/`release`), so it cannot settle the task on the half-changed prompt. A prompt the agent already took stays counted; one the CLI could not be asked about stays pending exactly as before (the task still owns it, so nothing is followed up). `updateSessionTask` is async now; the route awaits it and answers with the task as it is after the pull-back. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
The contract described a pause as keeping the sent prompt in the queue and a delete's `cancelled` as the end of the matter. Both changed with the follow-up and the pull-back, and the run history grew a `detail` value a client may now see for up to two minutes (or longer, when the hub gave up). The REST section says when PATCH and DELETE wait for the CLI's answer, what the pause's answer shows after a pull-back, what `cancel_unconfirmed` means on either outcome, and that `session-tasks-changed` follows each follow-up change. The hub README names the two budgets. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com>
…e prompt back on a pause with no CLI in the room
Review of the cancel follow-up found three ways a prompt could still go
out after the user stopped its task.
- The follow-up gave up two minutes after the cancel, whether or not a CLI
had ever been in the room. A wrapper that is away for longer (its
machine offline, its socket down) kept its copy and was never asked. The
two minutes now count from the first tick on which a CLI is there; a
follow-up whose session is gone is dropped.
- A pause with no CLI in the room: the hub removed its row, and the runner
then settled the prompt as cancelled, so the queue moved on to its next
prompt, and a wrapper alive with its socket down could still feed the
pulled-back one to the agent. The pause takes the prompt back in that
case too (the task is as before the send) and registers the follow-up;
until a CLI has confirmed it dropped its copy, the task does not send
that prompt again (the runner's `promptHeld`), because a second copy
under the same localId would be dropped together with the first. A CLI
that then reports the agent took the prompt makes the task count it
again (`recountUnsent`) and go on after it.
- The runner's own take-back (the task was deleted or paused while the
insert was under way) asked with the bar's 500 ms and left an
unconfirmed prompt to nobody. It asks with the task's budget now, and
writes the run row that lets the follow-up outlive a restart.
When a CLI reports that the agent took a prompt after all, the hub says so
with a toast ("Deleted task prompt was taken", "Paused task prompt was
taken"). A settled follow-up kicks the scheduler at once, so a run that
waited for it does not wait for the next tick.
End to end on a throwaway hub (scenario 20): a pause with the CLI's
socket gone, resumed at once. The task waits; the CLI is asked four
seconds after it reconnects; only then does the same prompt go out again.
via [HAPI](https://hapi.run)
Co-Authored-By: Claude Code <noreply@anthropic.com>
There was a problem hiding this comment.
Review mode: initial
Requirement — Pass
Persistent repeat prompts and acknowledgement-spaced queues let users schedule unattended work in an existing session. One-shot scheduled send and job-completion wakes each cover a single delivery. Fixed intervals address the recurring-runs use cases in #1524, with cron expressions and time zones left for later.
Evidence
- Issue #1524 describes recurring reports, checks, and maintenance on existing sessions.
- Base docs/guide/composer.md:47 documents one-shot scheduled send with a seven-day limit.
- Base docs/guide/session-jobs.md:207 documents an opt-in wake tied to a job's terminal state.
Approach — Pass
Keeping schedules in the hub lets them survive restarts and run without a connected client. Reusing the wake gate and ordinary message delivery preserves the existing CLI path, and using the CLI acknowledgement gives the scheduler a basis for advancing each task.
Evidence
- hub/src/store/sessionTasks.ts:135 persists task state separately from the message queue.
- hub/src/sync/syncEngine.ts:1485 wires scheduled delivery through a shared wake gate.
- hub/src/sync/sessionTaskRunner.ts:222 settles pending prompts from stored message state.
- hub/src/web/routes/sessionTasks.ts:140 uses the existing session access guard for task creation.
Code — Reviewed
The fixed merge-base diff includes the stacked wake changes from #2613. The findings concern prompt delivery races, cancellation recovery, and repeat-slot timing.
- [Major] Revalidate the task immediately before dispatch —
hub/src/sync/sessionTaskRunner.ts:363 - [Major] Let a resumed task recover when its CLI exited —
hub/src/sync/sessionTaskRunner.ts:203 - [Major] Require a CLI acknowledgement before confirming a task cancellation —
hub/src/sync/syncEngine.ts:1910 - [Major] Coordinate explicit Retry with cancellation follow-up —
hub/src/sync/syncEngine.ts:1646 - [Minor] Follow pending cancellation probes through session merges —
hub/src/sync/syncEngine.ts:1595 - [Minor] Skip repeat slots that elapsed before acknowledgement —
hub/src/sync/sessionTaskRunner.ts:233
Testing
Not run (automation; PR code execution is prohibited).
- GitHub reported the Test workflow and fixture drift gate successful on the fixed head. A separate advisory review run failed, another was cancelled, and the current review run was in progress.
- The merge-base diff passed git diff --check. No PR code, tests, or builds were run during this review.
- The checked-in tests cover cancellation and scheduling separately. The identified gaps include edits during real message translation, Retry during cancellation follow-up, and acknowledgement just after a repeat slot between ticks.
HAPI Bot
| // A previous hub process may have inserted this prompt and stopped | ||
| // before recording it. The localId makes that insert idempotent. | ||
| if (this.deps.store.messages.lookupQueuedMessage(this.promptSessionId(task), localId).status === 'absent') { | ||
| await this.deps.sendMessage(session.id, { text, localId }) |
There was a problem hiding this comment.
[Major] Revalidate the task immediately before dispatch
While input translation is pending, PATCH can replace a queue's unsent items. The message service then emits the old text, and markSent advances the edited queue past its new first item. A pause or delete during translation has a similar race. The post-send check runs after the CLI receives the prompt and may already have taken it.
Suggested fix
After asynchronous preparation, revalidate the task's state, next prompt, and due time at the insert-and-emit boundary. If the run changed, leave the updated task for the scheduler to pick up.
| if (task.state !== 'active' || task.nextRunAt === null || task.nextRunAt > now) return | ||
| // The prompt goes out under the localId of its run number: while an earlier copy of it is still | ||
| // unaccounted for (see `promptHeld`), the run waits for the next tick. | ||
| if (this.deps.promptHeld?.(buildSessionTaskMessageLocalId(task.id, task.runCount + 1))) return |
There was a problem hiding this comment.
[Major] Let a resumed task recover when its CLI exited
Pausing a pending task after its CLI exits removes the hub row and registers a cancellation follow-up. Resuming the task returns it to active, but promptHeld stops the runner before it reaches the wake gate. The follow-up waits for a socket before probing or starting its timeout. With no process left to reconnect, the task stays due indefinitely even when its machine is online.
Suggested fix
For a due active task, allow the wake gate to bring up the session for cancellation reconciliation while continuing to hold the replacement prompt. Release the hold after the old delivery is resolved.
| const result = await this.cancelQueuedMessage(promptSessionId, localId, { probeTimeoutMs: SESSION_TASK_CANCEL_PROBE_MS }) | ||
| if (result.status === 'cancelled') { | ||
| // Confirmed by the CLI itself: it answered, and this call removed the row. | ||
| return { type: 'cancelled', confirmed: result.unconfirmed !== true && result.localId === localId } |
There was a problem hiding this comment.
[Major] Require a CLI acknowledgement before confirming a task cancellation
A cancel timeout can leave a prompt indeterminate. If the CLI disconnects and the user then deletes the task in a non-shared session, MessageService removes the indeterminate row and returns cancelled with its local ID even though it reached no CLI. The task treats that as confirmed and skips follow-up, so a disconnected wrapper can still deliver the prompt without the history or toast reflecting it.
Suggested fix
Carry the actual CLI acknowledgement through the cancellation result. Treat deletion of the hub row without a positive acknowledgement as unconfirmed and retain the follow-up.
| let settled: 'removed' | 'consumed' | null = null | ||
| let takenAt = 0 | ||
| if (this.store.messages.lookupQueuedMessage(promptSessionId, localId).status !== 'absent') { | ||
| const result = await this.cancelQueuedMessage(promptSessionId, localId, { probeTimeoutMs: SESSION_TASK_CANCEL_FOLLOW_UP_PROBE_MS }) |
There was a problem hiding this comment.
[Major] Coordinate explicit Retry with cancellation follow-up
After an unconfirmed task delete, the queued-message bar still offers Retry. A successful retry requeues the same local ID but leaves the follow-up armed. On the next tick, the follow-up can remove the prompt while it is waiting behind a busy turn, undoing the user's successful Retry.
Suggested fix
Serialize explicit retries with follow-up probes for the same prompt. Retire the follow-up and clear its history marker when Retry succeeds.
| for (const followUp of [...list]) { | ||
| if (followUp.probing) continue | ||
| // The runs of a merged-away session moved to its survivor: follow them. | ||
| followUp.sessionId = this.store.resolveMessageTarget(followUp.sessionId) ?? followUp.sessionId |
There was a problem hiding this comment.
[Minor] Follow pending cancellation probes through session merges
A session merge moves the run history and removes the source row. resolveMessageTarget reads only metadata on an existing row, so the next follow-up tick discards the probe when it sees the old ID is gone. The survivor keeps a cancel_unconfirmed history entry that the running hub no longer reconciles.
Suggested fix
Rebind the run owner and prompt location through the merge hook or the namespace-scoped durable redirect before deciding to drop the follow-up.
| if (lookup.status === 'invoked' || lookup.status === 'absent') { | ||
| const taken = lookup.status === 'invoked' | ||
| const consumedAt = taken ? (lookup.message.invokedAt ?? now) : now | ||
| this.completeSend(task, localId, taken, consumedAt, now) |
There was a problem hiding this comment.
[Minor] Skip repeat slots that elapsed before acknowledgement
If a repeat slot comes due between ticks and the previous prompt is acknowledged just after that slot, settle takes the invoked branch before checking for missed slots. It leaves the elapsed slot scheduled, and the next tick sends it late even though the previous prompt was still waiting when the slot came due.
Suggested fix
When settling a repeat prompt, compare the next slot with the stored invokedAt. Advance past slots that matured while the prompt was pending and record the skip under the existing history policy.
…p, after main's run_id backfill Main took v36→v37 for the session_jobs run_id backfill (tiann#2664) and added its own migration-v37.test.ts, so the two steps this branch adds move up one: session_tasks is now v37→v38, start_at + session_task_runs is v38→v39, and SCHEMA_VERSION is 39. main's v36→v37 step and its test stay as they are. - hub/src/store/index.ts: main's restructured initSchema is kept; the step ladder, the v26 fast path and the comments carry the three steps in order, and the rollback notes give the new numbers. - migration-v37.test.ts is main's run_id test, now ending at 39 like every migration test; its two pinned log lines read "v36 to v39". - The branch's session_tasks test is migration-v38.test.ts (v37→v38); its downgrade now also drops session_task_runs, since a v37 database has neither table. Its start_at test is migration-v39.test.ts (v38→v39). - The older migration tests (v13…v36) end at 39; the v36 test's pinned log lines read "v35 to v39". - web/src/components/SessionList.open-tick.test.tsx: main deleted it in tiann#2643 in favour of SessionList.directory-action.test.tsx, into which the merge already carried this branch's two fixture fields, so the deletion stands. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run>
Two comments the merge left on the old numbers, and one it made inaccurate: - sessionTasks.ts pointed at "the v37→v38 step (Store.migrateFromV37ToV38)" for the column a phase-1 database lacks; that step is now v38→v39. - The v26 fast-path test said the path "returns before the required-tables check". main's initSchema no longer checks the tables after a migration at all; it checks them on the next open of an already-current database, which is when a v26 database upgraded without the task steps would fail. Comments only; no behaviour changes. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run>
tiann#2614 pauses a task whose prompt is waiting by cancelling that prompt, and on resume sends it again under the same local id. Remembered as a cancel that stood, the second send would be dropped as cancelled before arrival — while the task's runner counted the run as sent, so a task resumed within ten minutes of its pause lost a prompt and nothing said so. The hub's own prompts were already left out of what a cancel is remembered for, the two kinds there are today (a peer ping, a job's wake); a session task's is a third, for the same reason: it goes under the same id again, and no device cancels it in flight. The prefix is declared here until tiann#2614, which declares it in the protocol package, merges. The test is red without this. Co-Authored-By: Claude Code <noreply@anthropic.com> via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run>
|
On this branch alone: typecheck clean, 🤖 Generated with Claude Code — agent framework run through HAPI, powered by GLM |
There was a problem hiding this comment.
Review mode: follow-up after new commits
Requirement — Pass
Persistent repeat prompts and acknowledgement-spaced queues let users schedule unattended work in existing sessions. Fixed intervals cover recurring checks and reports, with cron expressions and time zones deferred.
Evidence
- Issue #1524 describes recurring reports, checks, and maintenance in existing sessions.
- The base composer guide documents scheduling a single message up to seven days ahead. docs/guide/composer.md:47
- The PR description defines fixed-interval repeats and queues spaced from CLI acknowledgement.
Approach — Pass
Persisting schedules in the hub lets them survive restarts and run without a connected client. Reusing the wake gate and ordinary message delivery preserves the CLI path, and the stored acknowledgement gives the scheduler a basis for advancing each task.
Evidence
- The task store persists schedules and history separately from the message queue. hub/src/store/sessionTasks.ts:133
- The scheduler uses the shared wake gate and ordinary message send path. hub/src/sync/syncEngine.ts:1495
- The runner uses stored message state to settle a pending prompt. hub/src/sync/sessionTaskRunner.ts:222
- Task creation uses the existing session access guard. hub/src/web/routes/sessionTasks.ts:145
Code — Reviewed
The fixed merge-base diff includes the stacked wake changes from #2613. The migration now advances the base schema from v37 to v39. The six earlier delivery and cancellation findings still apply, and the current code also permits stale translated text after an edit and an extra send after a late acknowledgement.
- [Major] Revalidate the task immediately before dispatch —
hub/src/sync/sessionTaskRunner.ts:363 - [Major] Refresh translations when a pulled-back prompt is edited —
hub/src/sync/sessionTaskRunner.ts:358 - [Major] Let a resumed task recover when its CLI has exited —
hub/src/sync/sessionTaskRunner.ts:203 - [Major] Require a CLI acknowledgement for confirmed cancellation —
hub/src/sync/syncEngine.ts:1910 - [Major] Coordinate explicit Retry with cancellation follow-up —
hub/src/sync/syncEngine.ts:1646 - [Major] Finish bounded repeats when a late acknowledgement reaches the limit —
hub/src/sync/syncEngine.ts:1695 - [Minor] Follow pending cancellation probes through session merges —
hub/src/sync/syncEngine.ts:1595 - [Minor] Skip repeat slots that elapsed before acknowledgement —
hub/src/sync/sessionTaskRunner.ts:233
Testing
Not run (automation; PR code execution is prohibited).
- GitHub reported the Test workflow and fixture drift gate successful on head 237124c. One advisory review run was cancelled and the current one was in progress when checked.
- The fixed merge-base diff passed git diff --check. No PR code, tests, or builds were run during this review.
- The checked-in tests cover migration and basic scheduling and cancellation. Missing cases include real input translation across task edits, Retry against a pending cancellation probe, late acknowledgement of a bounded task's final run, and acknowledgement just after a repeat slot between ticks.
HAPI Bot
| // A previous hub process may have inserted this prompt and stopped | ||
| // before recording it. The localId makes that insert idempotent. | ||
| if (this.deps.store.messages.lookupQueuedMessage(this.promptSessionId(task), localId).status === 'absent') { | ||
| await this.deps.sendMessage(session.id, { text, localId }) |
There was a problem hiding this comment.
[Major] Revalidate the task immediately before dispatch
While input translation is pending, PATCH can replace the queue's unsent prompts. The message service then emits the old text, and markSent advances the edited queue past its new first item. A pause or delete during translation can also finish before the old prompt is emitted. The check after send runs after the CLI can take it.
Suggested fix
After asynchronous preparation, compare the current task state, session, run number, prompt, and due time immediately before inserting and emitting. Leave a changed run for the scheduler to pick up from current state.
| this.changed(task, this.remove(task)) | ||
| return | ||
| } | ||
| const localId = buildSessionTaskMessageLocalId(task.id, runNumber) |
There was a problem hiding this comment.
[Major] Refresh translations when a pulled-back prompt is edited
With input translation enabled, pause a waiting repeat prompt after it has been translated, confirm the cancellation, edit it to other text that also needs translation, and resume. The rollback reuses the same local ID, and the translation cache at hub/src/sync/inputTranslation.ts:152 is keyed by session and local ID. The CLI receives the old translation even though the edit completed before resume.
Suggested fix
Include the original text in the translation cache identity or invalidate that cache entry when the prompt changes. Preserve the stable message ID used for delivery deduplication.
| if (task.state !== 'active' || task.nextRunAt === null || task.nextRunAt > now) return | ||
| // The prompt goes out under the localId of its run number: while an earlier copy of it is still | ||
| // unaccounted for (see `promptHeld`), the run waits for the next tick. | ||
| if (this.deps.promptHeld?.(buildSessionTaskMessageLocalId(task.id, task.runCount + 1))) return |
There was a problem hiding this comment.
[Major] Let a resumed task recover when its CLI has exited
Pausing a pending task after its non-shared CLI exits removes the hub row and registers a cancellation follow-up. Resuming makes the task active, but promptHeld returns before the wake gate. The follow-up waits for a socket before probing or starting its timeout. With no wrapper left to reconnect, the task stays due indefinitely even when its machine is online.
Suggested fix
Allow the wake gate to bring up the session for cancellation reconciliation on a due active task. Keep the replacement prompt held until the earlier delivery is resolved.
| const result = await this.cancelQueuedMessage(promptSessionId, localId, { probeTimeoutMs: SESSION_TASK_CANCEL_PROBE_MS }) | ||
| if (result.status === 'cancelled') { | ||
| // Confirmed by the CLI itself: it answered, and this call removed the row. | ||
| return { type: 'cancelled', confirmed: result.unconfirmed !== true && result.localId === localId } |
There was a problem hiding this comment.
[Major] Require a CLI acknowledgement for confirmed cancellation
If a cancel timeout leaves a task prompt indeterminate and the non-shared CLI then disconnects, deleting the task takes MessageService's indeterminate discard branch. That branch removes the row and returns its local ID without the unconfirmed flag at hub/src/sync/messageService.ts:707. The task treats this as confirmed and skips follow-up, so a disconnected wrapper holding the prompt can still deliver it after the history reports cancellation.
Suggested fix
Carry positive CLI acknowledgement explicitly in the cancellation result. Keep follow-up armed whenever the hub discards its row without that acknowledgement.
| let settled: 'removed' | 'consumed' | null = null | ||
| let takenAt = 0 | ||
| if (this.store.messages.lookupQueuedMessage(promptSessionId, localId).status !== 'absent') { | ||
| const result = await this.cancelQueuedMessage(promptSessionId, localId, { probeTimeoutMs: SESSION_TASK_CANCEL_FOLLOW_UP_PROBE_MS }) |
There was a problem hiding this comment.
[Major] Coordinate explicit Retry with cancellation follow-up
After an unconfirmed task delete, the queued-message bar offers Retry. A successful retry restores the same local ID to the queue and leaves the follow-up armed. If the prompt is waiting behind a busy turn, the next follow-up probe can remove it and undo the successful Retry.
Suggested fix
Serialize explicit retries and follow-up probes for the same prompt. Retire the follow-up and clear its history marker when Retry succeeds.
| if (pulledBack && prompt !== null) { | ||
| const after = runs.getById(prompt.taskId) | ||
| // Resumed since the pause: nothing else is pending, so the task goes on one interval after this take. | ||
| if (after !== null && after.state === 'active') { |
There was a problem hiding this comment.
[Major] Finish bounded repeats when a late acknowledgement reaches the limit
A repeat with maxRuns set to 1 can be paused while its CLI is offline and resumed before cancellation reconciliation. If the CLI reconnects and reports that it took the original prompt, recountUnsent restores runCount to 1 and this branch schedules another run. The runner only checks the limit after settling a pending prompt, so it sends a second prompt.
Suggested fix
Apply the normal task completion rule immediately after restoring the count from a late acknowledgement. Schedule a next run only when the task has remaining prompts or runs.
| for (const followUp of [...list]) { | ||
| if (followUp.probing) continue | ||
| // The runs of a merged-away session moved to its survivor: follow them. | ||
| followUp.sessionId = this.store.resolveMessageTarget(followUp.sessionId) ?? followUp.sessionId |
There was a problem hiding this comment.
[Minor] Follow pending cancellation probes through session merges
A session merge moves run history to the survivor and deletes the source row. resolveMessageTarget reads metadata from a live row, so the next tick drops the old session's follow-up. The survivor retains a cancel_unconfirmed history entry that the running hub has stopped reconciling.
Suggested fix
Rebind both the history owner and the prompt location through the merge hook or the namespace-scoped durable redirect before discarding the follow-up.
| if (lookup.status === 'invoked' || lookup.status === 'absent') { | ||
| const taken = lookup.status === 'invoked' | ||
| const consumedAt = taken ? (lookup.message.invokedAt ?? now) : now | ||
| this.completeSend(task, localId, taken, consumedAt, now) |
There was a problem hiding this comment.
[Minor] Skip repeat slots that elapsed before acknowledgement
When a repeat slot falls between scheduler ticks and the previous prompt is acknowledged just after that slot, settle takes the invoked branch before checking for skipped slots. The elapsed slot stays due and is sent late on the next tick, even though the previous prompt was still waiting at its scheduled time.
Suggested fix
Use the stored invokedAt when settling a repeat to advance past slots that fell while its prompt was waiting. Record the skip under the existing history policy.
Clean merge: no file conflicted. Eight files were changed on both sides (hub/src/sync/syncEngine.ts, hub/src/sync/messageService.ts, the composer guide, the SSE contract page and the four locale files); git merged them without overlap and the result was checked: the wake wiring in syncEngine.ts and the released-session return of releaseMatureScheduledMessages sit next to main's own additions, and the wording changes in the docs and locales are the one-line replacements this branch makes. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
Review (Major, "Scheduled wakes bypass reopen recovery"): the wake gate called resumeSession directly, so an archived session whose spawn the runner refused lost its archived status and reason (the reopen path a client takes puts that snapshot back on a safe failure), and an inactive Pi session with a resume attempt an earlier hub left behind kept answering "Pi resume is already in progress" on every wake, its message waiting until a client stepped in (reopen asks the runner whether that child is gone and clears the marker when it is). The gate now calls reopenSession. Its `incomplete` answer (a Cursor session without its chat id) is reported to the gate as `resume_unavailable`. A reconciled stale Pi attempt costs one backoff interval before the next wake spawns, instead of never. Tests (red before, green after): an archived session stays archived after a refused spawn; a Pi session with a persisted attempt has the marker cleared and is spawned on the wake past the backoff. A Cursor session that cannot be reopened is reported unavailable and stays archived (guard). via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
Review (Minor, "Wait on the session ID returned by resume"): a successful Cursor resume can merge the requested row into a replacement and answer with the replacement's id. The gate polled the requested id, which is gone by then, for 30 s and logged "Session did not become active" although the replacement was up. The gate now polls the id the resume returned. Test: the requested row disappears, the returned one is active, the wake resolves on the first poll; a replacement that never reports active still fails at its deadline (guard). via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
Schema: main's v37 → v38 (per-device push preferences, `06d0ea9c7`) got there first, so this change's two steps move up one: `session_tasks` is v38 → v39 and `start_at` with `session_task_runs` is v39 → v40 (`SCHEMA_VERSION` 40). In hub/src/store/index.ts the step table, the v26 fast path and the two step functions are renumbered, main's push-preferences step kept as it is; the rollback notes follow. Tests: the 13 step-ladder tests (v13 … v37) keep main's lines and expect the new final version; main's migration-v38.test.ts stays as main wrote it (only the version a v37 database now reaches changed), this branch's cases in it moved to a new migration-v39.test.ts, and the branch's migration-v39.test.ts became migration-v40.test.ts (renumbered like the steps). web/src/components/SessionList.groups.test.tsx is main's new fixture; it gets the two summary fields this change adds to `SessionSummary` (`activeTaskCount`, `nextTaskRunAt`), as the other fixtures did. The other 19 files both sides changed merged without overlap and were read against main: this change's additions sit next to main's (session groups, push / pairing, deliveryMode targeting, the acknowledgement guard), nothing of main's was dropped. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
Brings the two review fixes of tiann#2613. The wake gate of this branch already waited on the id a resume returns, so its file and test keep this branch's version (the two tests tiann#2613 added for it are the same case as "waits on, and keys its state by, the id a resume rotates the session to" here, and were dropped). The gate's wiring in syncEngine.ts takes tiann#2613's change — it calls `reopenSession`, which clears a Pi resume attempt an earlier hub left behind once the runner says that child is gone — next to this branch's `wakeableSession` (an archived session is refused before any resume). The real-engine Pi test of tiann#2613 is kept; its two archived-session cases are not, since the gate never resumes an archived session here. The tests that stood in for the resume (`stubResume`, the archived-session guard) now stand in for `reopenSession`, so they watch what the gate calls. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
…s session, a slot due before the acknowledgement is skipped Three review points on the task runner, each checked against the code first. - "Revalidate the task immediately before dispatch": with input translation on, the insert of a task prompt is an LLM call taking seconds. A PATCH that replaced a queue's unsent prompts in that window left the old text to be emitted and `markSent` to count it, so the edited first prompt was never sent; a pause or delete in that window relied on taking the prompt back after the CLI had received it. The message service now asks the sender, right before the row is inserted (after the translation and its turn in the session's send chain), whether the prompt is still wanted (`sendMessage`'s `stillWanted`); the runner answers from the task as it is now (active, same session, run, prompt and due time, nothing else recorded as sent) and leaves a changed task to the scheduler. `SyncEngine.sendMessage` answers whether the prompt went out. - "Let a resumed task recover when its CLI exited": a due run whose prompt was held for an unconfirmed cancel returned before the wake gate, and the follow-up only asks once a CLI is in the room. With the CLI gone the task waited for good. A held run now brings the session up (the prompt stays held), so a CLI is there to be asked. - "Skip repeat slots that elapsed before acknowledgement": a repeat slot that came due between ticks, with the previous prompt acknowledged just after it, stayed scheduled and was sent late, although the prompt was waiting when the slot came due (the tick would have skipped it had it seen that). Settling now advances past such a slot and records it under the existing history policy. Tests (red before, green after): the edited queue sends its new first prompt and the stale one never reaches the queue; a pause during the preparation inserts nothing; a held run on a session that is not running wakes it and sends once the hold is gone; the slot due before the acknowledgement is skipped and the next one is sent on time. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
…follow-up ends with a Retry, a merge or a finished task Four review points on a task prompt the hub cancelled without a CLI confirming it holds no copy, each checked against the code first. - "Require a CLI acknowledgement before confirming a task cancellation": an indeterminate row discarded with no CLI in the room (the CLI had disconnected) was reported as a plain `cancelled`, and the task took that as confirmed: no follow-up, while a wrapper alive with its socket down could still hold the prompt. `cancelQueuedMessage` now reports that discard as `unconfirmed: true`, like the offline delete of a queued row; the task keeps asking about it. - "Coordinate explicit Retry with cancellation follow-up": after such a delete the queued-message bar still offers Retry, which requeues the same localId while the follow-up stays armed; the next probe then took the retried prompt back. A Retry now waits for a probe under way, keeps the tick off the prompt while it runs, and on success retires the follow-up: the run counts as sent (or taken, when the CLI reports the agent got it). - "Follow pending cancellation probes through session merges": a merge moves the run history to the survivor and removes the source row; the follow-up read the old id, found the session gone and dropped the prompt, leaving a `cancel_unconfirmed` row nobody reconciled. The follow-up now follows the durable merge redirect (namespace-scoped) before deciding the session is gone, and asks in the survivor. - "Finish bounded repeats when a late acknowledgement reaches the limit": a repeat with `maxRuns` 1, paused while its CLI was offline and resumed, got its run count restored when the CLI reported the prompt taken, and that branch scheduled another run. The completion rule of an ordinary acknowledgement now applies: the task ends. Tests (red before, green after) at the message service and the engine: the no-CLI discard of an indeterminate row reports unconfirmed; a Retry leaves the retried prompt queued, asks no CLI and marks the run sent; a merge's survivor is asked and its row cleared; a repeat at its limit ends on the late take. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
…he same localId
Review ("Refresh translations when a pulled-back prompt is edited"): a
repeat prompt pulled back by a pause keeps its localId when the task is
resumed (the rollback and the dedupe of the prompt depend on it), and the
input-translation cache was keyed by session and localId only. Edited
after the pull-back and translated before it, the prompt went out under
the old translation.
The cache now keeps the text that was translated with the result and
answers from it only for the same text. Test: the same key with another
text asks the provider again.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
Co-Authored-By: Claude Code <noreply@anthropic.com>
|
Merged Conflicts. Addressed — every open thread was checked against the code first; all ten hold, and each fix has a test that was red before it.
Gates on |
Schema: main's v38 → v39 (session receipts, tiann#2747) got there first, so this change's two steps move up one again: `session_tasks` is v39 → v40 and `start_at` with `session_task_runs` is v40 → v41 (`SCHEMA_VERSION` 41). In hub/src/store/index.ts the step table and the two step functions are renumbered; the v26 fast path takes main's (`runStepMigrations`), which runs the same step table, so the hand-written list of steps goes. The rollback notes follow. Tests: the 14 step-ladder tests (v13 … v38) keep main's lines and expect the new final version; main's migration-v39.test.ts (the receipts step) stays as main wrote it, this branch's cases in it moved to a new migration-v40.test.ts, and the branch's migration-v40.test.ts became migration-v41.test.ts (renumbered like the steps). tiann#2748 came in with the same merge: in messageService.ts the sweep at session end now skips both session-task prompts and receipt replies. via [HAPI](https://hapi.run) Co-Authored-By: Claude Code <noreply@anthropic.com> Co-Authored-By: HAPI <noreply@hapi.run>
Stacked on #2613 (the wake gate it reuses). Only the commits after that are new.
Updated 2026-12-07.
mainis merged in again (afd174d7d), which brings #2747 and #2748. Main's v38 → v39 (session receipts) got there first, so the two migrations of this change moved up one more step:session_tasksis now v39 → v40, andstart_atwith the run history v40 → v41 (SCHEMA_VERSION41). InmessageService.tsthe sweep at session end skips both session-task prompts and receipt replies.Before that, on 2026-12-04:
mainwas merged in (62132a289, plus #2613's review fixes ineaefb8b14). Main's own v36 → v37 (therun_idbackfill of #2664) and v37 → v38 (per-device push preferences) got there first, so the two migrations of this change moved up two steps at the time.Problem
Scheduled messages are one-shot and capped at 7 days. There is no way to ask for "this prompt every 30 minutes" or "send these three prompts, ten minutes apart" — the recurring-runs gap in #1524.
Change
A task is a schedule the hub owns per session, stored in a new
session_taskstable (schema v39 → v41: v40 adds the tasks, v41 their first-run time and the run history). Two kinds:startAt + k × intervalMs), optionally bounded bymaxRuns. A slot that comes due while the previous prompt is still waiting to be taken is skipped, so a busy agent never has two of the task's prompts queued — also when the acknowledgement lands right after that slot, before the tick saw the prompt waiting. A run that went out late (hub down, machine asleep) skips the slots it missed, and later runs stay on the original grid.intervalMsafter the CLI acknowledged taking the previous one.The scheduler (
SessionTaskRunner) rides the existing 5s tick:sentFrom: 'webapp',localId: hapi-task:<taskId>:<n>) and records the local id; the task steps forward only on that row's realinvokedAt. The local id makes the insert idempotent across a hub restart, andmarkSentis a compare-and-set so two overlapping ticks cannot both count a send. The prefix is exempt from the session-end sweep for the same reason ashapi-job-wake:.machine_offline,session_unavailableandsession_archivedkeep it due withlastErrorset, which clears on the next run that goes out.prompt_indeterminatesays the prompt was sent but whether the agent took it is unknown (the queued-message bar offers Retry or Discard);prompt_not_takensays the hub stopped waking the session for that prompt after three attempts.detail: 'cancel_unconfirmed', and on every tick a CLI that is in the session's room is asked again, for up to two minutes from the first tick on which it is there (a CLI that is away is asked when it comes back). When the CLI confirms it holds no copy the row readscancelled; when it reports that the agent took the prompt after all, the row becomessentand the user is told with a toast (Deleted task prompt was taken); a repeat that reached its limit with that take ends, as after any acknowledgement. Only a CLI's answer confirms a cancel: a row the hub discarded with no CLI in the room counts as unconfirmed too. A Retry of the prompt from the queued-message bar ends the asking (the run counts as sent), and the asking follows the runs when a merge moves them to the surviving session. A task whose prompt is held this way brings its session up, so a CLI is there to be asked; a prompt pulled back and edited is translated again./clearredirects the prompt to the replacement session.session_task_runs): one row per prompt sent (stamped when the agent takes it, flipped tocancelledwhen the user skips it), per skipped slot, and per run that could not go out, with its reason. The first slot skipped while a prompt waits is a row, then at most one an hour for as long as that prompt keeps waiting; every skipped slot is still announced, because the task's next run moved. At most 500 rows per session; rows older than 30 days are dropped.too_many_tasks; paused ones do not count). Task request bodies are limited to 1 MB.Scheduled message not sent), since the hub goes on retrying and nobody would see why it never goes out.REST, scoped to the session's access check:
GET /api/sessions/:id/tasks{tasks: SessionTask[]}POST /api/sessions/:id/tasks{kind: 'repeat', text, intervalMs, startAt?, maxRuns?}or{kind: 'queue', items: [{text}], intervalMs, startAt?}{task}—intervalMs1 minute to 30 days, 1–50 prompts,startAtat most 366 days ahead; 400invalid_start_at,too_many_tasksPATCH /api/sessions/:id/tasks/:taskId{paused, text, items, intervalMs, maxRuns}—itemsreplaces the prompts a queue has not sent,maxRuns: nullremoves the limit{task}, the task as it is after the change — a pause with a prompt waiting may take up to about 3 s; 400wrong_task_kind,invalid_max_runs,too_many_tasksPOST /api/sessions/:id/tasks/:taskId/run{task}— the next run is due now; a paused task becomes active again. 409prompt_pendingDELETE /api/sessions/:id/tasks/:taskId{ok: true, prompt}—none,cancelled,takenorunconfirmed: what became of a prompt the agent had not taken yet; the task is gone whateverpromptsays, and the request may take up to about 3 sGET /api/sessions/:id/tasks/history?limit=1..200{runs: SessionTaskRun[]}, newest first; the runs stay after their task is gone;detail: 'cancel_unconfirmed'marks a run whose cancelled prompt no CLI has confirmed yetEvery change emits
session-tasks-changed(session id only; clients refetch). Session list rows and content-search rows carryactiveTaskCountandnextTaskRunAt. The web UI is the next PR in this stack; the native apps ignore the event and show a task's prompts like any other user message. The last commit gives the web test fixtures the two new summary fields, so that this branch typechecks on its own.Testing
nextRepeatRunAt, first-run range, the delete outcome, the run row.markSent,settlePending,skipDueSlot, pause / resume / errors, edit rules, run history (record, stamp, flip to cancelled, cap, retention), cascade on session delete, transfer on merge; migration v39 → v41 on a file database, idempotent DDL, and a phase-1 task's planned first run kept across v40 → v41.prompt_indeterminateandprompt_not_taken; the history rule for skipped slots and its events.hapi-task:prompt stays pending next to a swept user prompt.main@a0a826d4c+ this branch (2026-12-04):bun typecheckclean;bun run test:hub2612 passed;bun run test:shared659 passed;bun run test:relay118 passed;bun run test:web5082 passed with the 1 expected failure;bun run test:cli6197 passed with the 4 failuresmainhas on this machine;bun run test:parity31 passed with the 18 failuresmainhas on this machine;bun run test:cli:integration16 passed; no fixture drift (gen:fixtures, and the 429 web fixture tests); docs build; passkey browser test passed; the browser job's 15 e2e specs 103 of 104 passed (share-turn's wrapped export snapshot has no darwin image onmain, so that one cannot pass on this machine). Windows-only checks not run locally.main@8f667a5b6+ this branch (2026-12-07, the merge commitafd174d7d):bun typecheckclean;bun run test:hub2698 passed;bun run test:shared665 passed;bun run test:relay118 passed;bun run test:web5196 passed with the 1 expected failure;bun run test:cli6250 passed with the 4 failuresmainhas on this machine and 18 inagyReactiveWakeup(the live-agy tests; on this machine today they fail the same way onmainitself);bun run test:parity31 passed with the 18 failuresmainhas on this machine; no fixture drift; docs build. On a throwaway hub: the archived-session scenario 7 of 7, and the receipts checks of feat: peer replies through the hub (part 2 of #2746) #2748 13 of 13. The integration, passkey and browser suites were not re-run for this merge.prompt_indeterminate, and a phase-1 database upgraded with its tasks still running (the numbering before the moves; thesession_tasksstep is v39 → v40 now); and for the cancel: a CLI that answers after 900 ms (the delete is confirmed and the prompt never goes out), a CLI whose socket is gone while it holds the prompt (asked again 1.5 s after it reconnects, never taken), a pause that pulls the waiting prompt back and a resume that sends it again, and a pause with the CLI gone (the resumed task waits until the CLI is back and has dropped its copy, then the same prompt goes out).Still missing from #1524: cron expressions and per-schedule time zones.
🤖 Generated with Claude Code — agent framework run through HAPI, powered by GLM
glm-5.4(Z.ai).