feat(queue): add Send Now dispatch controls (#2292)

This commit is contained in:
Carlos Florêncio
2026-08-06 13:45:55 +01:00
committed by GitHub
parent 26bc2e1269
commit 6b42e335db
50 changed files with 5456 additions and 522 deletions
@@ -0,0 +1,64 @@
# ADR-2026-08-05-queue-send-now-replaces-turn: Queue Send Now Replaces the Active Turn
**Status:** accepted
**Date:** 2026-08-05
**Area:** backend, frontend, protocol, workflow
## Context
The queue panel needs a **Send Now** action that interrupts a busy agent and
starts a replacement turn from one selected queued message or an aggregate of
the current queue. Kandev's ordinary user Cancel action may intentionally run a
workflow step's `on_turn_complete` policy, move the task to review, or auto-start
the destination step. Reusing that path would let a request to continue working
change workflow position before its replacement prompt is dispatched.
## Decision
`message.queue.send_now` is a turn-replacement operation, not an explicit
workflow-completing cancellation.
- The orchestrator owns the whole cancel-and-dispatch operation under the
existing per-session cancellation coordinator and turn-identity guard.
- The operation gets a distinct cancellation kind. It publishes the existing
backend-owned cancellation progress, but it does not create the ordinary
**Turn cancelled** message, move the task to review, or evaluate
`cancel_triggers_turn_complete` / `on_turn_complete`.
- A promptable session dispatches the claimed queue selection without issuing a
cancel. A busy session cancels only when the active turn is confirmed to be
the same turn observed when the operation began; a successor turn is never
cancelled as a stale continuation of the request.
- Queue selection and dispatch remain one orchestrator operation. A selected
entry or click-time bulk snapshot is claimed only for this replacement turn,
and failure handling restores the original pending entries rather than
silently substituting another queue entry.
- An already accepted explicit user cancellation or another send-now operation
wins the conflict. Send Now fails closed instead of joining a
workflow-completing cancellation and dispatching after it.
## Consequences
Users can redirect a long-running turn without moving the task out of its
current workflow step. The action shares cancellation progress and race safety
with the existing coordinator while preserving a separate product meaning from
the Cancel button.
The backend needs a new WebSocket action, queue claim/aggregation behavior, and
tests for cancellation-source races, successor-turn protection, restoration,
and mixed-provenance bulk delivery. The frontend must treat Send Now as an
asynchronous cancellation operation and disable duplicate actions while the
backend projection is pending.
## Alternatives Considered
- **Call the existing explicit `CancelAgent` action, then drain the queue.**
Rejected because configured user cancellation can complete a workflow step,
move the task, and auto-start unrelated successor work before the queued
prompt is sent.
- **Queue a copy of the selected content and use the parent-message interrupt
endpoint.** Rejected because it duplicates a durable row, loses the selected
entry's identity and attachments, and exposes the wrong authorization model.
- **Cancel first and let the ordinary FIFO drain choose the next message.**
Rejected because per-row Send Now must dispatch the selected entry, while
bulk Send Now must use the click-time queue snapshot rather than whichever
row happens to be at the head after a race.
+1
View File
@@ -117,6 +117,7 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-08-03-backend-owned-cancellation-progress | [Keep Cancellation Progress Backend Owned](2026-08-03-backend-owned-cancellation-progress.md) | accepted | backend, frontend, protocol | 2026-08-03 |
| 2026-08-03-separate-message-queue-provenance-cancellation-and-capacity | [Separate Message Queue Provenance, Cancellation, and Capacity](2026-08-03-separate-message-queue-provenance-cancellation-and-capacity.md) | accepted | backend, frontend, protocol, security | 2026-08-03 |
| 2026-08-03-provider-scoped-task-mcp-tools | [Derive Provider-Scoped Task MCP Tools in the Backend](2026-08-03-provider-scoped-task-mcp-tools.md) | accepted | backend, agentctl, protocol, integrations | 2026-08-03 |
| 2026-08-05-queue-send-now-replaces-turn | [Queue Send Now Replaces the Active Turn](2026-08-05-queue-send-now-replaces-turn.md) | accepted | backend, frontend, protocol, workflow | 2026-08-05 |
| 2026-08-04-file-backed-prompt-attachments | [File-backed prompt attachments](2026-08-04-file-backed-prompt-attachments.md) | accepted | backend, frontend, protocol, infra | 2026-08-04 |
| 2026-08-04-plugin-contribution-lifecycle-authority | [Make Plugin Contribution Lifecycle Authoritative](2026-08-04-plugin-contribution-lifecycle-authority.md) | accepted | frontend, security | 2026-08-04 |
| 2026-08-04-navigation-manifest-boundaries | [Centralize Navigation and Namespace Plugin Destinations](2026-08-04-navigation-manifest-boundaries.md) | accepted | frontend | 2026-08-04 |
@@ -0,0 +1,199 @@
---
spec: docs/specs/ui/message-queue-send-now.md
created: 2026-08-05
status: implemented
---
# Implementation Plan: Arbitrate Send Now Against FIFO Handoff
## Overview
Repair the narrow race between ordinary FIFO queue draining and the explicit
Send Now operation. The diagnostic bundle shows that FIFO removes/reserves the
head and starts an asynchronous worker after the active turn becomes ready;
Send Now then sees only the in-flight marker and returns `send_now_conflict`,
so two queued messages run as separate turns instead of one replacement turn.
Add an explicit per-session handoff state with a pre-acceptance ownership
boundary. Send Now may supersede and restore an unaccepted FIFO reservation,
then claim its exact row or all-scope snapshot. Once FIFO has accepted prompt
ownership, the existing fail-closed conflict remains the safe behavior. The
fix is backend-only apart from a browser regression assertion; no queue schema,
WebSocket shape, or frontend control change is planned.
## Confirmed Root Cause
- The bundle records two queue entries, then the active turn becomes ready.
- The normal drain reserves the FIFO head and launches
`executeQueuedMessage` asynchronously.
- `SendQueuedNow` checks `isQueuedDispatchInFlight` in
`queue_send_now.go` and returns `ErrSendNowConflict` before it can aggregate
the queue.
- The worker can also record the ordinary user message and run turn-start
effects before its final prompt claim, so allowing an uncoordinated
supersession would risk duplicate transcript/workflow side effects.
- The result in the bundle is two independent queued prompts followed by the
Send Now error, matching this race rather than a cancellation-acknowledgement
failure.
## Backend
### Per-session queued-dispatch handoff
Files:
- `apps/backend/internal/orchestrator/service.go`
- `apps/backend/internal/orchestrator/event_handlers_workflow.go`
- `apps/backend/internal/orchestrator/event_handlers_agent.go`
- `apps/backend/internal/orchestrator/task_operations.go`
- `apps/backend/internal/orchestrator/queue_send_now.go`
Replace the bare session-to-entry in-flight marker with (or wrap it in) a
per-session reservation that records the exact queued source and whether the
automatic worker is still pre-acceptance or has claimed prompt ownership.
Keep the existing per-session cancellation guard as the single arbitration
point.
- Register the FIFO reservation before spawning the worker, as today.
- Make the worker claim ownership under the guard before recording an ordinary
user message, running `on_turn_start` effects, or accepting the agent prompt.
- Let Send Now, while holding the same guard, supersede only a pre-acceptance
FIFO reservation. Restore that exact ordinary or durable source, publish the
authoritative queue state at the normal transition point, and continue
through the existing exact-entry/bulk claim and replacement dispatch path.
- Preserve the existing `send_now_conflict` behavior for an accepted FIFO
handoff, explicit cancellation, or another Send Now operation. Do not
cancel or duplicate a successor that has already claimed the turn.
- Update all marker helpers and callers (`drainQueuedMessageForPromptableSession`,
targeted queue takes, lifecycle dispatch checks, and `promptTask`) so a stale
worker cannot clear a newer owner or perform side effects after losing.
### Restoration and lifecycle safety
Use the existing message-queue restoration and durable acknowledgement contract;
do not add a database migration. A superseded ordinary row must return to its
original FIFO position, and a durable lifecycle row must have its transient
reservation cleared. The winning Send Now claim remains the only source that
can create the replacement prompt and acknowledge durable sources.
Do not change explicit Cancel completion semantics, captured-turn checks,
backend-owned cancellation progress, normal FIFO ordering, or `Run next`
behavior outside this pre-acceptance arbitration window.
## Frontend and Protocol
No production frontend or WebSocket contract change is required. The existing
error mapping/refetch remains the correct response if FIFO has already accepted
its successor. Extend the desktop queue E2E assertion so the aggregate appears
as one user prompt, not merely as three strings that could have arrived in
separate turns. Re-run the existing mobile Send Now scenario because the
control and shared API path are unchanged.
## Tests
- **What:** a normal FIFO reservation can be superseded before prompt
acceptance, restored, and included in one exact bulk Send Now claim.
**File:** `apps/backend/internal/orchestrator/queue_send_now_test.go` or a
focused `queued_dispatch_arbitration_test.go` beside it.
**How:** channel-synchronized handoff barriers, no sleeps; assert one
aggregate prompt, both source IDs restored/claimed correctly, FIFO order,
and no stale worker transcript or workflow side effects.
- **What:** an accepted FIFO handoff remains terminal for Send Now.
**File:** the same focused orchestrator test file.
**How:** pause after ownership acceptance, issue Send Now, assert
`ErrSendNowConflict`, no duplicate prompt/message, no cancellation of the
successor, and untouched remaining queue.
- **What:** ordinary FIFO delivery and existing explicit-cancel/peer-interrupt
paths retain their current semantics after the handoff state change.
**Files:** focused existing queue/cancellation tests under
`apps/backend/internal/orchestrator/`.
**How:** run the targeted regression groups with `-race`; include durable
lifecycle and retry paths because they share the reservation marker.
- **What:** the browser-visible bulk action produces one replacement user
prompt containing both queued bodies in order.
**File:** `apps/web/e2e/tests/chat/message-queue.spec.ts`.
**How:** extend the existing header Send Now scenario to assert one
`user-message-bubble` contains the aggregate, then verify the queue is empty
and the turn completes. Re-run the existing mobile Send Now scenario for
shared-path parity.
## E2E Tests
- **Scenario:** while a desktop agent is busy, queue multiple messages and
activate header Send Now. Verify the replacement transcript contains one
user prompt with the concatenated bodies in FIFO order, rather than one
visible prompt per source entry, and that the queue disappears.
**File:** `apps/web/e2e/tests/chat/message-queue.spec.ts`.
- **Scenario:** on Pixel 5, run the existing row Send Now flow and verify the
shared arbitration result still leaves neighboring queue entries ordered,
preserves the 44px controls, and keeps document horizontal overflow at zero.
**File:** `apps/web/e2e/tests/chat/mobile-message-queue-management.spec.ts`.
## Verification Results
- RED before the arbitration implementation: `cd apps/backend && go test
-race ./internal/orchestrator -run
'^TestSendQueuedNowSupersedesPendingFIFOHandoff$' -count=1` failed with
`send-now operation is already in progress`, reproducing the diagnostic-bundle
race.
- Focused backend: `cd apps/backend && go test -race ./internal/orchestrator
-run 'Test(SendNow|QueuedDispatch|ExecuteQueuedMessage)' -count=1` — 25
passed.
- Queue repository: `cd apps/backend && go test -race
./internal/orchestrator/messagequeue -run 'Test.*SendNow' -count=1` — 11
passed.
- Broader queue/cancellation regression: `cd apps/backend && go test -race
./internal/orchestrator -run
'Test(.*Queued.*|.*Queue.*|.*Cancel.*|.*Interrupt.*|.*Peer.*)' -count=1` —
179 passed.
- Full orchestrator package: `cd apps/backend && go test -race
./internal/orchestrator -count=1` — 1546 passed.
- Changed-file Go lint: `cd apps/backend && golangci-lint run ./... --new-from-rev
5c51dde562e2264ae63544993be88fd7f383222d --timeout=5m` — 0 issues.
- Web lint: `cd apps && pnpm --filter @kandev/web lint` — passed.
- Web typecheck: `cd apps/web && pnpm run typecheck` — no errors.
- E2E formatting: `cd apps && pnpm exec prettier --check
web/e2e/tests/chat/message-queue.spec.ts` — passed.
- Desktop aggregate E2E: `cd apps/web && pnpm e2e:run
tests/chat/message-queue.spec.ts -- --grep 'header Send Now' --retries=0` — 1
passed.
- Mobile parity E2E: `cd apps/web && pnpm e2e:run --project mobile-chrome
tests/chat/mobile-message-queue-management.spec.ts -- --grep 'Send Now'
--retries=0` — 1 passed.
- Orchestrator compile check: `cd apps/backend && go test
./internal/orchestrator/... -run '^$' -count=1` — no tests found; compile
completed successfully.
- `git diff --check` is run before commit.
## Implementation Waves and Parallel Candidates
The default is sequential execution in the primary conversation. These waves do
not authorize subagents.
Wave 1:
- [x] [Task 01: Arbitrate FIFO and Send Now handoff](task-01-fifo-send-now-arbitration.md)
Wave 2:
- [x] [Task 02: Prove one aggregate replacement prompt](task-02-aggregate-replacement-e2e.md)
Task 02 depends on Task 01 and is not parallel-safe with it because it verifies
the changed backend timing and prompt ownership behavior.
## Risks and Boundaries
- The ownership boundary must precede visible message creation and workflow
turn-start effects; a late check can still create a duplicate transcript row.
- Restoring a reserved lifecycle entry must clear only the transient delivery
reservation and must not acknowledge or discard the durable source.
- Once an automatic prompt is accepted, combining it with a later Send Now
request is intentionally out of scope because it would require retracting or
rewriting an already visible user message. The operation fails closed there.
- No schema migration, new error code, queue reordering, arbitrary subset
selection, or change to normal FIFO/Run next semantics is planned.
## Open Questions
None. The diagnostic evidence and existing `message-queue-send-now` contract
define the repair boundary.
@@ -0,0 +1,110 @@
---
id: "01-fifo-send-now-arbitration"
title: "Arbitrate FIFO and Send Now handoff"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/ui/message-queue-send-now.md"
---
# Task 01: Arbitrate FIFO and Send Now handoff
## Acceptance
- A normal FIFO drain registers a per-session handoff with an explicit
pre-acceptance phase and an accepted/terminal phase.
- Send Now, under the existing cancellation guard, can supersede only the
pre-acceptance FIFO handoff, restore its exact ordinary or durable source,
and claim the requested exact row or all-scope snapshot without partial
mutation.
- With two queued ordinary messages at the ready boundary, header Send Now
produces one aggregate replacement prompt containing both bodies in FIFO
order; the losing FIFO worker produces no duplicate visible message,
workflow turn-start effect, or prompt.
- An accepted FIFO handoff returns the existing `send_now_conflict` behavior;
it does not cancel or duplicate the successor, and remaining queue entries
remain authoritative.
- Existing normal FIFO, explicit Cancel, peer-interrupt, lifecycle reservation,
retry, captured-turn, and cancellation-progress behavior remains unchanged
outside the new pre-acceptance arbitration window.
## Verification
```bash
cd apps/backend
go test -race ./internal/orchestrator -run 'Test(SendNow|QueuedDispatch|ExecuteQueuedMessage)' -count=1
go test -race ./internal/orchestrator/messagequeue -run 'Test.*SendNow' -count=1
```
## Files Likely Touched
- `apps/backend/internal/orchestrator/service.go`
- `apps/backend/internal/orchestrator/event_handlers_workflow.go`
- `apps/backend/internal/orchestrator/event_handlers_agent.go`
- `apps/backend/internal/orchestrator/task_operations.go`
- `apps/backend/internal/orchestrator/queue_send_now.go`
- `apps/backend/internal/orchestrator/queue_send_now_test.go`
- `apps/backend/internal/orchestrator/event_handlers_queue_test.go` or a new
focused `queued_dispatch_arbitration_test.go`
## Dependencies
None.
## Parallelism
Sequential. The task changes the shared per-session dispatch ownership
mechanism and must be implemented and verified as one concurrency surface.
## Inputs
- Amended spec scenarios: FIFO reservation superseded before prompt
acceptance, and accepted FIFO handoff failing closed.
- `apps/backend/internal/orchestrator/queue_send_now.go` current conflict gate.
- `dispatchTakenQueuedMessage` and `executeQueuedMessage` in
`event_handlers_workflow.go`/`event_handlers_agent.go`.
- `claimSessionRunningForPrompt` and the existing dispatch token checks in
`task_operations.go`.
- Existing queue lifecycle and cancellation tests that use
`markQueuedDispatchInFlight`.
## TDD Sequence
1. Add a deterministic test barrier after the FIFO source is reserved but
before the worker claims prompt ownership. Trigger header Send Now with two
queued sources and assert the current implementation returns the conflict
or otherwise fails the new expected one-prompt invariant (RED).
2. Add the accepted-handoff race case and assert the existing fail-closed
contract, plus a baseline normal FIFO case so the arbitration does not turn
every automatic drain into a Send Now claim.
3. Introduce the reservation state/ownership transition and move ordinary
message recording and turn-start effects behind the worker's guarded
ownership claim.
4. Implement Send Now supersession/restoration for only the pre-acceptance
state, then route the winner through the existing exact claim and aggregate
dispatch path.
5. Add durable lifecycle and stale-worker assertions, run the focused `-race`
commands, and confirm no marker cleanup path can remove a newer owner.
## Output Contract
Report the deterministic RED failure, the reservation states and guarded
ownership boundary, restoration behavior for ordinary/durable rows, exact
focused command results, files changed, and any remaining race or blocker.
Mark this task `done` and update its plan checkbox only after the tests pass.
## Results
- RED reproduced the reported conflict before the fix: the pending FIFO
handoff test returned `send-now operation is already in progress`.
- Added a typed per-session reservation with pending, accepted, and superseded
phases. The FIFO worker claims the reservation under `cancelInFlight` before
transcript or workflow side effects; Send Now can supersede only pending
FIFO work and restores its exact source first.
- Durable lifecycle restoration clears only the transient reservation; the
aggregate Send Now claim remains responsible for final acknowledgement.
The stale FIFO worker is covered by a synchronous no-requeue assertion.
- Focused command results: 25 orchestrator tests passed with `-race`, and 11
messagequeue Send Now tests passed with `-race`.
- Broader queue/cancellation command result: 179 tests passed with `-race`.
@@ -0,0 +1,86 @@
---
id: "02-aggregate-replacement-e2e"
title: "Prove one aggregate replacement prompt"
status: done
wave: 2
depends_on: ["01-fifo-send-now-arbitration"]
plan: "plan.md"
spec: "../../specs/ui/message-queue-send-now.md"
---
# Task 02: Prove one aggregate replacement prompt
## Acceptance
- The desktop header Send Now scenario proves the two or more queued bodies
are rendered in one user-message bubble in FIFO order, not merely that all
strings eventually appear somewhere in the transcript.
- The desktop scenario still proves the queue is empty after a successful bulk
claim and the replacement turn completes.
- The existing Pixel 5 Send Now scenario passes against the repaired backend,
preserving touch geometry, neighboring-row order, and zero document
horizontal overflow.
- The test does not rely on arbitrary sleeps to establish correctness; it uses
visible queue/prompt/idle signals and the existing mock-agent fixtures.
## Verification
```bash
cd apps/web
pnpm e2e --project=chromium e2e/tests/chat/message-queue.spec.ts --grep 'header Send Now' --retries=0
pnpm e2e --project=mobile-chrome e2e/tests/chat/mobile-message-queue-management.spec.ts --grep 'Send Now' --retries=0
```
## Files Likely Touched
- `apps/web/e2e/tests/chat/message-queue.spec.ts`
- `apps/web/e2e/tests/chat/mobile-message-queue-management.spec.ts` only if
the shared-path assertion needs a focused strengthening
## Dependencies
- Task 01 must pass its focused backend race tests and leave the backend
handoff state stable.
## Parallelism
Sequential. The browser assertions depend on the backend arbitration contract
and share the queue fixtures with the existing mobile scenario.
## Inputs
- The amended spec's one-prompt FIFO handoff scenario.
- Existing desktop header and row Send Now coverage in
`message-queue.spec.ts`.
- Existing Pixel 5 coverage in
`mobile-message-queue-management.spec.ts`.
- `data-testid="user-message-bubble"` as the transcript-level assertion for a
single aggregate user prompt.
## TDD Sequence
1. Strengthen the desktop bulk scenario to locate the replacement user bubble
containing the first body and require the second body in that same bubble;
run it against the pre-fix implementation to record the expected RED
behavior when the FIFO handoff wins.
2. Run the scenario after Task 01 and assert the queue disappearance and idle
transition only after the aggregate bubble is visible.
3. Re-run the existing mobile Send Now scenario, recording touch-target and
overflow evidence; do not alter production UI for this backend repair.
## Output Contract
Report the RED/GREEN browser results, the exact single-bubble assertion, the
mobile parity and overflow checks, files changed, generated traces/screenshots
if any, and cleanup evidence. Mark this task `done` and update its plan
checkbox only after both focused commands pass.
## Results
- Strengthened the desktop bulk scenario with a single
`user-message-bubble` assertion containing all queued bodies in FIFO order.
- Desktop managed E2E passed: 1 test for the header Send Now scenario.
- Pixel 5/mobile-chrome managed E2E passed: 1 test covering Send Now without
hover, 44px touch geometry, neighboring queue order, and zero horizontal
overflow.
- No production frontend change or generated E2E artifact was required.
+299
View File
@@ -0,0 +1,299 @@
---
spec: docs/specs/ui/message-queue-send-now.md
created: 2026-08-05
status: implemented
---
# Implementation Plan: Send Queued Messages Now
## Overview
Add one explicit WebSocket operation that asks the orchestrator to replace the
active turn with either one queued entry or the click-time snapshot of the
whole visible queue. Build the exact-entry/batch claim and restoration contract
first, then compose it with the existing cancellation coordinator and expose it
through the frontend queue hook and inline panel. Finish with desktop/mobile
Playwright coverage and the public queue-control guides.
Decision inputs:
- [Queue Send Now Replaces the Active Turn](../../decisions/2026-08-05-queue-send-now-replaces-turn.md)
- [Keep Cancellation Progress Backend Owned](../../decisions/2026-08-03-backend-owned-cancellation-progress.md)
- [Explicit User Cancellation May Complete a Workflow Step](../../decisions/2026-08-02-explicit-user-cancel-completion.md)
- [Version Agent-Ready Events by Prompt Generation](../../decisions/0035-version-agent-ready-events-by-prompt-generation.md)
---
## Backend
### Exact queue dispatch claims
Files:
- `apps/backend/internal/orchestrator/messagequeue/types.go`
- `apps/backend/internal/orchestrator/messagequeue/repository.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_memory.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_sqlite.go`
- `apps/backend/internal/orchestrator/messagequeue/service.go`
- new focused helpers/tests under `apps/backend/internal/orchestrator/messagequeue/`
Add a `SendNowClaim` value that retains the ordered original entries plus the
synthetic dispatch envelope. Add repository/service operations to atomically
claim an exact ordered list of entry IDs, restore the claim, and acknowledge
its durable lifecycle rows.
The claim transaction must fail without partial mutation when any requested row
is missing, belongs to another session, or is already reserved. Ordinary rows
are removed; durable lifecycle rows receive the existing in-flight reservation
and remain until acknowledgement. Restoration reinserts ordinary rows at their
original positions and clears durable reservations.
Build the bulk envelope from the claimed rows: FIFO content joined by `\n\n`
between non-empty bodies, FIFO attachments, canonical reference union, oldest
entry model/plan mode/attribution, and source identity/provenance metadata.
Validate attachment count/bytes and reference count before cancellation using
the same constants as ordinary message admission.
### Non-completing cancel-and-dispatch
Files:
- new `apps/backend/internal/orchestrator/queue_send_now.go`
- `apps/backend/internal/orchestrator/task_operations.go`
- `apps/backend/internal/orchestrator/event_handlers_agent.go`
- `apps/backend/internal/orchestrator/service.go`
Add `Service.SendQueuedNow(ctx, sessionID, scope, entryID)` and a distinct
`cancellationKindQueueSendNow`. Authorize the session first, snapshot the active
turn and exact queue selection, and validate the aggregate before cancellation.
Reuse `cancelInFlightGuard`, the backend cancellation projection, captured turn
identity, and silent cancellation reconciliation. Do not call the explicit
`CancelAgent` path: Send Now must not write the ordinary cancellation message,
move the task to review, or evaluate cancelled-turn completion. Reject an
existing explicit cancellation or Send Now owner. If the observed turn changes,
leave the successor and queue untouched; if the session is already promptable,
claim and dispatch without cancellation.
Refactor the queued execution handoff only as far as necessary to accept a
single- or multi-entry `SendNowClaim`. A successful prompt acknowledges every
durable source; retryable admission/execution failures restore every original
source and publish authoritative queue status. Never fall back to the FIFO head
when the selected entry or bulk snapshot cannot be claimed.
### WebSocket action
Files:
- `apps/backend/pkg/websocket/actions.go`
- `apps/backend/internal/orchestrator/handlers/queue_handlers.go`
- `apps/backend/internal/backendapp/gateway.go` only if constructor wiring must
name a broader dispatcher interface
Register `message.queue.send_now` with request fields `session_id`, `scope`, and
conditional `entry_id`. Extend the existing drainer dependency into a queue
dispatcher interface implemented by `orchestrator.Service`.
Authorize before all queue reads/cancellation, validate the scope combination,
call `SendQueuedNow`, map the spec's stable error codes, publish status, and
return `{session_id, dispatched: true, sent_count}`. Add the action to the
gateway authorization pinning tests so `session_id` receives the existing
backstop.
---
## Frontend
### Queue API and hook
Files:
- `apps/web/lib/api/domains/queue-api.ts`
- `apps/web/lib/api/domains/queue-api.test.ts`
- `apps/web/hooks/domains/session/use-queue.ts`
- `apps/web/hooks/domains/session/use-queue.test.ts`
Add `sendQueuedNow` plus typed error mapping for the stable send-now codes. Add
`sendEntryNow(entryId)` and `sendAllNow()` to `useQueue`; both set queue loading,
invoke the action, and refetch authoritative status on success or failure. A
missing/raced entry is a reconciled result plus focused feedback, not a stale
optimistic removal.
### Queue controls
Files:
- `apps/web/components/task/chat/queued-ghost-list.tsx`
- `apps/web/components/task/chat/queued-ghost-list.test.tsx`
- `apps/web/components/task/chat/queued-ghost-message.tsx`
- `apps/web/components/task/chat/queued-ghost-message.test.tsx`
- `apps/web/src/locales/en/chat.json`
- generated pseudo-locale output if the catalog workflow changes it
Add a per-row **Send Now** button to the existing `RowActions` hover/focus
group and thread the selected entry ID through the queue hook. Add header
**Send Now** immediately before **Clear all** and bind it to `sendAllNow`.
Disable both controls while the queue request or authoritative session
`cancellation_pending` state is true, use the existing spinner/toast patterns,
and localize all labels and failures.
Keep **Run next** unchanged for promptable FIFO-head dispatch. When present, the
header order is **Run next**, **Send Now**, **Clear all**, collapse. Let the
action group wrap on narrow viewports rather than shrink or overflow.
---
## Responsive and Mobile Contract
- **Desktop outcome and mobile entry point:** desktop opens the existing queue
chip and uses hover/focus row actions or the header; mobile opens the same
chip and sees both Send Now controls without hover.
- **Nearest shipped exemplar:**
`apps/web/e2e/tests/chat/mobile-message-queue-management.spec.ts` supplies the
inline panel, single scroll owner, visible touch controls, and 44px geometry.
- **Hierarchy and primary action:** queue content remains primary; per-row Send
Now sits with row actions, while bulk Send Now is the first bulk mutation
immediately before Clear all.
- **Presentation choice:** retain the inline queue panel because the action is a
frequent, short mutation of already visible content; no drawer or navigation
layer is introduced.
- **Geometry and scrolling:** `queue-scroll-region` remains the only internal
scroll owner. The header action group may wrap, controls are at least 44px on
coarse pointers, the composer remains visible, and document horizontal
overflow stays zero.
- **Shared logic:** API calls, loading/cancellation state, selection, aggregation,
and errors are shared. Only the existing pointer-responsive action visibility
differs.
- **Mobile proof:** a `mobile-chrome` test taps row/header Send Now, asserts the
replacement prompt outcome, verifies touch geometry, and checks horizontal
containment.
---
## Tests
- **What:** exact-entry and exact-snapshot batch claims are atomic, preserve FIFO
source order, reserve durable rows, restore originals, and acknowledge every
durable source.
**Files:** new `repository_*_send_now_test.go` coverage for memory, SQLite,
and env-gated PostgreSQL plus `service_test.go`.
**How:** table-driven repository tests for selected/all claims, missing or
changed snapshots, mixed ordinary/durable rows, restoration, and no
cross-session mutation.
- **What:** bulk aggregation joins content correctly, preserves FIFO
attachments, deduplicates references, uses the oldest envelope, and rejects
attachment/reference overflow before mutation.
**Files:** new messagequeue send-now helper tests and orchestrator tests where
task-model attachment limits are applied.
**How:** deterministic unit tests with attachment-only messages, repeated
references, mixed provenance, and over-limit inputs.
- **What:** busy Send Now cancels the captured turn and dispatches the exact
selection without explicit-cancel workflow side effects; promptable Send Now
skips cancellation.
**File:** `apps/backend/internal/orchestrator/queue_send_now_test.go`.
**How:** channel-synchronized lifecycle mocks assert one cancel, no review or
cancelled-turn completion, exact prompt content, and one successor turn.
- **What:** successor-turn, explicit-cancel, duplicate-click, queue-change, and
prompt-failure races fail closed or restore the original queue.
**Files:** `queue_send_now_test.go` and focused existing cancellation tests if
shared coordinator behavior changes.
**How:** captured-turn replacement and cancellation-owner race tests without
sleeps; assert no substitute FIFO dispatch.
- **What:** the WS action validates scope, authorizes before dependencies, maps
stable errors, and publishes the post-action status.
**File:** `apps/backend/internal/orchestrator/handlers/queue_handlers_send_now_test.go`.
- **What:** frontend API/hook calls and both controls use the correct scope,
refetch after every outcome, show localized failures, and disable during
loading/cancellation.
**Files:** existing queue API, hook, list, and row component test files.
---
## E2E Tests
- **Scenario:** while a desktop task agent runs a cancellable slow turn, queue
three distinct messages and activate row Send Now on the second. Verify the
replacement transcript contains the second prompt, the cancelled turn does
not advance the workflow, and the first/third rows remain ordered.
**File:** `apps/web/e2e/tests/chat/message-queue.spec.ts`.
- **Scenario:** while a desktop task agent is busy, queue several messages and
activate header Send Now. Verify one replacement prompt contains all bodies
in FIFO order and the queue disappears.
**File:** `apps/web/e2e/tests/chat/message-queue.spec.ts`.
- **Scenario:** on Pixel 5, open the busy queue panel and tap Send Now. Verify
the row and header controls are 44px, require no hover, remain inside the
viewport with no document horizontal overflow, and complete a replacement
turn.
**File:** `apps/web/e2e/tests/chat/mobile-message-queue-management.spec.ts`.
---
## Public Documentation
Update the how-to/explanation sections in:
- `docs/public/coordination.md`
- `docs/public/sessions-and-review.md`
Explain the difference between **Run next** (promptable FIFO head), **Send Now**
(interrupt and replace without workflow completion), **Clear all**, and the
normal Cancel control. No new page or navigation entry is required.
---
## Verification Results
- Backend queue claims and envelope aggregation: `cd apps/backend && go test -race ./internal/orchestrator/messagequeue -count=1 -v` — 116 tests passed. The memory and SQLite claim suites cover exact atomic selection, click-time snapshot changes, FIFO restoration, durable reservation, acknowledgement, aggregate attachments, and reference limits. The env-gated PostgreSQL cases were included but skipped because `KANDEV_TEST_POSTGRES_DSN` is unset.
- Backend replacement orchestration: `cd apps/backend && go test -race ./internal/orchestrator -run 'SendNow|ExplicitCancellationDoesNotJoin' -count=1 -v` — 6 tests passed; `cd apps/backend && go test -race ./internal/orchestrator/handlers -run 'SendNow|QueueHandler' -count=1 -v` — 24 tests passed; existing cancellation/peer-interrupt regressions — 56 tests passed. The retry regression also proves restored ordinary and durable sources retain the recorded-user-message marker.
- Backend compile sweep: `cd apps/backend && go test ./... -run '^$'` — completed with no test bodies selected, compiling all packages successfully.
- Backend lint: `make -C apps/backend lint` — completed with 0 issues after extracting the repository, handler, and orchestration validation helpers.
- Frontend queue API, hook, and component suite: 4 files, 97 tests passed. `cd apps/web && pnpm run typecheck` passed; full web lint passed with `pnpm --filter @kandev/web run lint`; `i18n:pseudo`, `i18n:check`, and `i18n:ratchet` all passed.
- Public documentation: `node --test scripts/validate-public-docs.test.mjs` — 58 tests passed; `node scripts/validate-public-docs.mjs` — 41 published docs pages validated; `git diff --check` passed.
- E2E discovery found 12 desktop queue tests and 2 mobile queue-management tests. After rebuilding and syncing the embedded web assets with `make build-web` and `make sync-embedded-web && make build-backend`, `cd apps/web && pnpm e2e --project=chromium e2e/tests/chat/message-queue.spec.ts --grep 'Send Now' --retries=0` — 2 passed in 33.4s; the matching `mobile-chrome` command for `mobile-message-queue-management.spec.ts` — 1 passed in 13.1s. The desktop row scenario verifies workflow-step preservation and neighboring FIFO entries; the mobile scenario verifies touch geometry and zero horizontal overflow.
---
## Implementation Waves and Parallel Candidates
The default is sequential execution in the primary conversation. The files are
ordered by dependency; these waves do not authorize subagents.
Wave 1:
- [x] [Task 01: Add exact send-now queue claims](task-01-queue-send-now-claims.md)
Wave 2:
- [x] [Task 02: Orchestrate replacement-turn dispatch](task-02-replacement-turn-dispatch.md)
Wave 3:
- [x] [Task 03: Add Send Now queue controls](task-03-send-now-queue-controls.md)
Wave 4:
- [x] [Task 04: Prove Send Now end to end](task-04-send-now-e2e.md)
- [x] [Task 05: Document Send Now behavior](task-05-document-send-now.md)
Tasks 04 and 05 own disjoint E2E and public-doc files, but the final plan/status
and verification-results update is serialized after both tasks complete so the
durable implementation record cannot be overwritten by parallel edits.
---
## Risks and Boundaries
- `task_operations.go` and cancellation coordination are high-contention
concurrency surfaces. Keep new orchestration in a focused file and preserve
captured-turn and prompt-generation checks.
- Explicit Cancel can complete/advance a workflow step; Send Now must never
reuse or join that semantic path.
- Bulk delivery can mix provenance and durable lifecycle rows. The batch claim
must preserve originals for retry and acknowledge every durable source only
after prompt acceptance.
- Aggregate attachment/reference limits must be checked before cancellation so
a validation error cannot stop useful active work.
- New queue entries accepted after the click-time snapshot remain pending and
must not leak into the replacement prompt.
- No schema migration, feature flag, queue reordering, arbitrary subset
selection, model picker, or change to ordinary FIFO drain is planned.
@@ -0,0 +1,79 @@
---
id: "01-queue-send-now-claims"
title: "Add exact send-now queue claims"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/ui/message-queue-send-now.md"
---
# Task 01: Add exact send-now queue claims
## Intent
Give the orchestrator an atomic, loss-aware way to claim one persisted queue
entry or an exact ordered snapshot, restore the original entries on failure,
and acknowledge every durable source after acceptance.
## Acceptance
1. An exact-ID claim is all-or-none, session-scoped, FIFO-ordered, and treats
ordinary versus durable lifecycle rows according to the existing delivery
guarantees.
2. Bulk aggregation preserves content, attachments, references, execution
envelope, and source provenance exactly as specified, with pre-mutation
overflow errors.
3. Restore and acknowledge operations handle mixed ordinary/durable claims
without changing unrelated or newly queued rows.
## Files likely touched
- `apps/backend/internal/orchestrator/messagequeue/types.go`
- `apps/backend/internal/orchestrator/messagequeue/repository.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_memory.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_sqlite.go`
- `apps/backend/internal/orchestrator/messagequeue/service.go`
- `apps/backend/internal/orchestrator/messagequeue/send_now.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_memory_send_now_test.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_sqlite_send_now_test.go`
- `apps/backend/internal/orchestrator/messagequeue/repository_postgres_send_now_test.go`
- `apps/backend/internal/orchestrator/messagequeue/send_now_test.go`
## Dependencies
None.
## Parallelism
Sequential. This task freezes the claim and restoration contract consumed by
Task 02.
## Inputs
- Spec: API-adjacent aggregation rules, State and Concurrency, Failure Modes.
- Plan: Backend / Exact queue dispatch claims.
- Existing patterns: `ReserveHead`, `TakeByID`, `Restore`,
`AcknowledgeByID`, and `MergeIntoAbove`.
## Verification
```bash
cd apps/backend && go test -race ./internal/orchestrator/messagequeue -run 'SendNow' -count=1
```
If the PostgreSQL DSN is available, the same command must discover and pass the
env-gated PostgreSQL send-now cases; otherwise record the explicit skip.
## Output contract
Report files changed, the exact claim/restore/ack semantics, RED and GREEN test
commands/results, PostgreSQL execution or skip, blockers/risks, and synchronize
this task plus `plan.md` status/results.
## Results
- Added `SendNowClaim`, FIFO envelope aggregation, exact session-scoped claims, restoration, and durable-source acknowledgement to the memory and SQLite/PostgreSQL-compatible repositories.
- Claims are all-or-none, reject missing/duplicate/reserved or changed click-time snapshots without mutation, retain durable rows with an in-flight reservation, restore ordinary rows at their persisted positions, and acknowledge every durable source only after prompt acceptance.
- GREEN: `cd apps/backend && go test -race ./internal/orchestrator/messagequeue -count=1 -v` — 116 tests passed across memory and SQLite; env-gated PostgreSQL cases are included and skipped because `KANDEV_TEST_POSTGRES_DSN` is unset.
- Aggregate envelope coverage proves FIFO content/attachments, oldest execution metadata, canonical reference de-duplication, provenance, attachment-only entries, and pre-mutation attachment/reference overflow errors.
@@ -0,0 +1,86 @@
---
id: "02-replacement-turn-dispatch"
title: "Orchestrate replacement-turn dispatch"
status: done
wave: 2
depends_on: ["01-queue-send-now-claims"]
plan: "plan.md"
spec: "../../specs/ui/message-queue-send-now.md"
---
# Task 02: Orchestrate replacement-turn dispatch
## Intent
Compose the exact queue claim with Kandev's unified cancellation coordinator so
Send Now safely replaces a captured busy turn or directly prompts an idle
session without inheriting explicit Cancel workflow semantics.
## Acceptance
1. `message.queue.send_now` authorizes and dispatches exactly one selected entry
or the exact bulk snapshot, returning the specified response/error contract.
2. Busy dispatch uses backend cancellation progress but never writes the normal
cancel message, moves to review, or evaluates cancelled-turn completion;
promptable dispatch does not issue a cancel.
3. Successor-turn, explicit-cancel, duplicate Send Now, queue-change, and prompt
failure races fail closed or restore the original claim without a substitute
FIFO dispatch.
## Files likely touched
- `apps/backend/internal/orchestrator/queue_send_now.go`
- `apps/backend/internal/orchestrator/queue_send_now_test.go`
- `apps/backend/internal/orchestrator/task_operations.go`
- `apps/backend/internal/orchestrator/event_handlers_agent.go`
- `apps/backend/internal/orchestrator/service.go`
- `apps/backend/pkg/websocket/actions.go`
- `apps/backend/internal/orchestrator/handlers/queue_handlers.go`
- `apps/backend/internal/orchestrator/handlers/queue_handlers_send_now_test.go`
- `apps/backend/internal/orchestrator/handlers/queue_handlers_test.go`
- `apps/backend/internal/backendapp/gateway.go`
## Dependencies
- Task 01 exact queue claim, restoration, and acknowledgement contract.
## Parallelism
Sequential. It changes shared cancellation ownership and the public WebSocket
contract used by Task 03.
## Inputs
- Spec: API Surface, State and Concurrency, Permissions, Failure Modes.
- Plan: Backend / Non-completing cancel-and-dispatch and WebSocket action.
- ADR: `2026-08-05-queue-send-now-replaces-turn`.
- Existing patterns: `QueueAndInterruptForPeerMessage`,
`cancelAgentSilentWithGuardActionKind`, `dispatchTakenQueuedMessage`, and
`CancellationPendingSnapshot`.
## Verification
```bash
cd apps/backend && go test -race ./internal/orchestrator ./internal/orchestrator/handlers -run 'SendQueuedNow|SendNow' -count=1
```
Also run the focused existing cancellation/peer-interrupt regressions affected
by any shared coordinator edit:
```bash
cd apps/backend && go test -race ./internal/orchestrator -run 'Test(CancelAgent|CancellationSources|QueueAndInterruptForPeerMessage)' -count=1
```
## Output contract
Report files changed, cancellation-source behavior, wire contract/error mapping,
RED and GREEN test commands/results, race cases covered, blockers/risks, and
synchronize this task plus `plan.md` status/results.
## Results
- Added `Service.SendQueuedNow`, the `message.queue.send_now` action, stable validation/error mapping, queue status publication, exact selected/bulk dispatch, and the dedicated non-completing cancellation kind.
- Busy Send Now uses the backend-owned cancellation projection and captured-turn guard without joining explicit Cancel; promptable Send Now claims and prompts directly. Duplicate/cross-owner operations fail closed, and prompt/reset failures restore the complete claim.
- GREEN: `cd apps/backend && go test -race ./internal/orchestrator -run 'SendNow|ExplicitCancellationDoesNotJoin' -count=1 -v` — 6 tests passed; handler coverage with `-run 'SendNow|QueueHandler'` — 24 tests passed; affected existing cancellation/peer-interrupt regressions — 56 tests passed.
- PR fixup: carry the validated click-time source snapshot through cancellation and compare persisted queue fields before claiming; mark every source as `user_message_recorded` before prompt admission so ordinary and durable restoration cannot create duplicate transcript rows. Regression coverage includes changed-snapshot atomicity and a retry with a durable source.
- The WS contract validates scope before dispatch and returns `{session_id, dispatched, sent_count}` on success, with stable queue-empty, queue-changed, conflict, turn-changed, attachment, and reference errors.
@@ -0,0 +1,89 @@
---
id: "03-send-now-queue-controls"
title: "Add Send Now queue controls"
status: done
wave: 3
depends_on: ["02-replacement-turn-dispatch"]
plan: "plan.md"
spec: "../../specs/ui/message-queue-send-now.md"
---
# Task 03: Add Send Now queue controls
## Intent
Expose the new action through the shared queue API/hook and add accessible row
and header controls that work through hover/focus on desktop and direct touch on
coarse-pointer layouts.
## Acceptance
1. The API and hook send the exact `entry`/`all` payloads, map stable errors,
and refetch authoritative queue state after every result.
2. Every row exposes hover/focus **Send Now** on fine pointers and an always-
visible 44px touch control on coarse pointers; header **Send Now** appears
immediately before **Clear all** and sends the whole snapshot.
3. Duplicate actions are disabled during local loading or authoritative
cancellation, all new copy is localized, and the narrow header wraps without
adding another scroll owner or horizontal overflow.
## Files likely touched
- `apps/web/lib/api/domains/queue-api.ts`
- `apps/web/lib/api/domains/queue-api.test.ts`
- `apps/web/hooks/domains/session/use-queue.ts`
- `apps/web/hooks/domains/session/use-queue.test.ts`
- `apps/web/components/task/chat/queued-ghost-list.tsx`
- `apps/web/components/task/chat/queued-ghost-list.test.tsx`
- `apps/web/components/task/chat/queued-ghost-message.tsx`
- `apps/web/components/task/chat/queued-ghost-message.test.tsx`
- `apps/web/src/locales/en/chat.json`
- pseudo-locale catalog output if regenerated by the repository script
## Dependencies
- Task 02 WebSocket request, response, and error contract.
## Parallelism
Sequential. It owns the shared frontend surface required by both E2E scenarios.
## Inputs
- Spec: What, API Surface, Responsive and Mobile Behavior.
- Plan: Frontend and Responsive and Mobile Contract.
- Nearest mobile exemplar:
`apps/web/e2e/tests/chat/mobile-message-queue-management.spec.ts`.
- Existing patterns: `drainQueuedMessage`, `useQueuePanelHandlers`,
`RowActions`, and session `cancellation_pending` selectors.
## Verification
Bootstrap once if this worktree has no dependencies:
```bash
cd apps && pnpm install --frozen-lockfile
```
Then run:
```bash
cd apps && pnpm --filter @kandev/web test -- --run lib/api/domains/queue-api.test.ts hooks/domains/session/use-queue.test.ts components/task/chat/queued-ghost-message.test.tsx components/task/chat/queued-ghost-list.test.tsx
cd apps/web && pnpm run typecheck
cd apps && pnpm --filter @kandev/web run lint
cd apps && pnpm --filter @kandev/web run i18n:ratchet && pnpm --filter @kandev/web run i18n:check
```
## Output contract
Report files changed, desktop/mobile interaction details, RED and GREEN test
commands/results, typecheck/lint/i18n outcomes, rendered verification evidence
or its exact blocker, risks, and synchronize this task plus `plan.md`
status/results.
## Results
- Added typed `sendQueuedNow` API errors, exact entry/all payloads, authoritative refetches on every result, and `sendEntryNow`/`sendAllNow` queue-hook actions with loading and cancellation guards.
- Added localized row and header Send Now controls. Desktop row actions use hover/focus reveal, coarse-pointer layouts keep 44px controls visible, the header order is Run next / Send Now / Clear all / collapse, and the action group wraps without adding a scroll owner.
- GREEN: focused queue API/hook/list/message suite — 4 files, 97 tests passed; `cd apps/web && pnpm run typecheck` passed; full web lint passed; `i18n:pseudo`, `i18n:check`, and `i18n:ratchet` passed.
- Missing/raced entries reconcile through the authoritative queue state and show focused localized feedback; no optimistic removal is retained.
@@ -0,0 +1,87 @@
---
id: "04-send-now-e2e"
title: "Prove Send Now end to end"
status: done
wave: 4
depends_on: ["02-replacement-turn-dispatch", "03-send-now-queue-controls"]
plan: "plan.md"
spec: "../../specs/ui/message-queue-send-now.md"
---
# Task 04: Prove Send Now end to end
## Intent
Exercise the real cancel-and-replacement flow through the production frontend
and backend on desktop and mobile, including exact row selection, bulk ordering,
workflow-step preservation, and touch geometry.
## Acceptance
1. Desktop Playwright proves selected Send Now dispatches the chosen row while
preserving remaining order and proves header Send Now creates one FIFO-
concatenated replacement turn.
2. The workflow step does not advance from cancellation semantics, and the
authoritative queue/transcript settle without duplicate turns.
3. Mobile Playwright uses `.tap()`, proves both controls are at least 44px and
reachable without hover, and asserts no document horizontal overflow.
## Files likely touched
- `apps/web/e2e/tests/chat/message-queue.spec.ts`
- `apps/web/e2e/tests/chat/mobile-message-queue-management.spec.ts`
- a focused sibling helper only if needed to keep either spec below repository
size/complexity limits
## Dependencies
- Task 02 backend action and cancellation behavior.
- Task 03 frontend controls and stable test IDs.
## Parallelism
The E2E and public-doc files are disjoint, so implementation work can overlap
after dependencies complete. Final status/results edits to the shared `plan.md`
record are serialized after both tasks finish. User authorization is still
required before using subagents.
## Inputs
- Spec scenarios for selected, all, workflow preservation, and phone parity.
- Plan: E2E Tests and Responsive and Mobile Contract.
- Existing helpers: `openQueuePanel`, `typeWhileBusy`, `SessionPage`, and
`mobile-message-queue-management.spec.ts` touch geometry helper.
## Verification
Bootstrap once if needed:
```bash
cd apps && pnpm install --frozen-lockfile
```
Run the focused scenarios through the managed runner:
```bash
cd apps/web && pnpm e2e --project=chromium e2e/tests/chat/message-queue.spec.ts --grep 'Send Now' --retries=0
cd apps/web && pnpm e2e --project=mobile-chrome e2e/tests/chat/mobile-message-queue-management.spec.ts --grep 'Send Now' --retries=0
```
If the managed runner is required for a fresh embedded build, run the
repository build/sync wrapper first, then use the same focused Playwright
commands. Confirm each command discovers the intended test count before
recording it as evidence.
## Output contract
Report files changed, RED and GREEN runs, discovered/passed test counts,
desktop/mobile rendered evidence or artifact paths, teardown evidence, blockers
or flake analysis, and synchronize this task plus `plan.md` status/results.
## Results
- Added desktop row and bulk replacement scenarios plus the Pixel 5 row scenario. Desktop proves exact second-row selection, remaining FIFO order, one bulk FIFO-concatenated prompt, no ordinary cancellation message, and workflow-step preservation. Mobile uses `.tap()`, checks both Send Now controls, 44px geometry, no hover dependency, replacement content, and document horizontal containment.
- Discovery: desktop queue spec listed 12 tests and mobile queue-management listed 2 tests.
- GREEN desktop: `cd apps/web && pnpm e2e --project=chromium e2e/tests/chat/message-queue.spec.ts --grep 'Send Now' --retries=0` — 2 passed in 33.4s.
- GREEN mobile: `cd apps/web && pnpm e2e --project=mobile-chrome e2e/tests/chat/mobile-message-queue-management.spec.ts --grep 'Send Now' --retries=0` — 1 passed in 13.1s.
- The managed runner initially used stale embedded frontend assets; rebuilding with `make build-web`, `make sync-embedded-web && make build-backend` produced the final no-retry pass. No E2E artifacts are checked in.
@@ -0,0 +1,70 @@
---
id: "05-document-send-now"
title: "Document Send Now behavior"
status: done
wave: 4
depends_on: ["02-replacement-turn-dispatch", "03-send-now-queue-controls"]
plan: "plan.md"
spec: "../../specs/ui/message-queue-send-now.md"
---
# Task 05: Document Send Now behavior
## Intent
Update the existing public queue and session guidance so users can distinguish
Send Now from Run next, Clear all, and the workflow-aware Cancel control.
## Acceptance
1. `coordination.md` documents selected/all Send Now behavior, FIFO bulk
concatenation, and its non-workflow-completing replacement semantics.
2. `sessions-and-review.md` explains when to use Run next, Send Now, Clear all,
or Cancel without duplicating the full queue contract.
3. Public-doc validation and internal links pass; no new page or navigation
entry is introduced.
## Files likely touched
- `docs/public/coordination.md`
- `docs/public/sessions-and-review.md`
## Dependencies
- Task 02 final backend behavior and Task 03 final labels.
## Parallelism
Parallel-safe with Task 04 after dependencies complete. Files are disjoint and
neither task changes a shared contract or package configuration. User
authorization is still required before using subagents.
## Inputs
- Spec: What, Failure Modes, Out of Scope.
- Plan: Public Documentation.
- Public docs type: `coordination.md` is primarily explanation/reference;
`sessions-and-review.md` is primarily a how-to guide.
## Verification
```bash
node --test scripts/validate-public-docs.test.mjs
node scripts/validate-public-docs.mjs
git diff --check
```
The public-doc files are disjoint from Task 04, but final status/results edits
to the shared `plan.md` record are serialized after both tasks finish.
## Output contract
Report public files changed, the terminology/behavior clarified, exact validator
results, link issues or risks, and synchronize this task plus `plan.md`
status/results.
## Results
- Updated `docs/public/coordination.md` and `docs/public/sessions-and-review.md` to distinguish Run next, selected/all Send Now, Clear all, and normal Cancel, including FIFO bulk behavior and non-workflow-completing replacement semantics.
- GREEN: `node --test scripts/validate-public-docs.test.mjs` — 58 tests passed; `node scripts/validate-public-docs.mjs` — 41 published docs pages validated; `git diff --check` passed.
- No new public page or navigation entry was introduced.
+7
View File
@@ -124,6 +124,13 @@ The default delivery mode is queued. Each session accepts 10 queued messages by
In the task workbench, expand the queue chip to manage pending messages. Every visible pending row has **Remove**, whether it came from a user, another agent, workflow automation, or a server action. **Clear all** removes all visible pending rows in that session and releases their capacity. After removal, merge, or drain, displayed positions compact to `#1` through `#N` while FIFO order stays unchanged. Provenance still matters for editing and merging: only user-origin content can be edited. A row already reserved for delivery is hidden from the panel and cannot be cancelled there.
Use the queue controls according to the outcome you want:
- **Run next** dispatches the promptable FIFO head without interrupting an active turn. It is available when the session can accept a prompt.
- **Send Now** sends directly when the session is promptable; when an agent turn is active, it waits for the backend to acknowledge cancellation and then replaces that captured turn with either the selected row or the click-time snapshot of every visible row. Bulk Send Now joins non-empty bodies with a blank line, keeps attachments in FIFO order, and deduplicates references. It creates a replacement turn but does not apply normal Cancel side effects: it does not record a cancellation message, complete the cancelled workflow step, or move the task to review. New rows added after the click remain queued.
- **Clear all** removes every visible pending row without sending a prompt.
- **Cancel** in the chat toolbar stops the active turn as a user cancellation. It may record the cancellation, complete an eligible workflow step, and move the task to review; it does not send queued content.
Choose the control by intent:
| Intent | Operation | Result |
+2
View File
@@ -65,6 +65,8 @@ Stopping a turn does not itself run the next queued message. Expand the queue an
The expanded queue also lets you discard stale work. **Remove** is available for every visible pending row, including messages from users, peer agents, workflows, and server actions; **Clear all** removes all visible pending rows in that session. Only user-origin rows remain editable. A message already reserved for delivery is hidden from the queue and cannot be cancelled with these controls.
The queue panel separates four actions. **Run next** sends the promptable FIFO head and leaves a running turn alone. **Send Now** sends directly when the session is promptable; otherwise it waits for backend cancellation acknowledgement, then replaces the active turn with one selected row or the click-time snapshot of all visible rows as one FIFO-ordered prompt. It does not record ordinary Cancel side effects or complete the cancelled workflow step. **Clear all** discards the visible queue. The chat toolbar's **Cancel** is the normal user cancellation for the active turn; it sends no queued prompt and may complete an eligible workflow step or move the task to review.
A CLI-passthrough profile displays the agent's native terminal interface in a PTY. It still belongs to the task, but it does not provide Kandev's structured chat messages and tool-call presentation.
<details>
+1
View File
@@ -159,6 +159,7 @@ Subscription quota tracking and per-agent cheap-model profile routing.
| [mermaid-rendering](ui/mermaid-rendering.md) | shipped |
| [message-queue-management](ui/message-queue-management.md) | shipped |
| [message-queue-merge](ui/message-queue-merge.md) | shipped |
| [message-queue-send-now](ui/message-queue-send-now.md) | shipped |
| [settings-manual-save](ui/settings-manual-save.md) | shipped |
| [settings-discovery](ui/settings-discovery.md) | shipped |
| [executor-settings-card-spacing](ui/executor-settings-card-spacing.md) | shipped |
+5 -3
View File
@@ -25,7 +25,9 @@ remains full. Those same rows have no individual remove action.
and returns the exact number removed.
- Removal does not change provenance rules for other operations. Only
user-owned messages may be edited. Merge behavior remains defined by
[Merge Enqueued Messages Individually](message-queue-merge.md).
[Merge Enqueued Messages Individually](message-queue-merge.md), and
interrupt-and-dispatch behavior is defined by
[Send Queued Messages Now](message-queue-send-now.md).
- Successful removal publishes the existing
`message.queue.status_changed` event. All connected views reconcile to the
backend result; the initiating view may update optimistically but must
@@ -215,8 +217,8 @@ starts accepting work.
- Editing agent-, workflow-, or server-origin message content.
- Changing the shipped merge compatibility rules.
- Cancelling a prompt after it has entered in-flight delivery or reached the
executor.
- Interrupting an active prompt to dispatch pending work; that separate action
is governed by [Send Queued Messages Now](message-queue-send-now.md).
- Per-workspace, per-task, or per-session capacity overrides.
- Automatically pruning old messages when a lower limit is saved.
- Queue reordering or bulk selection beyond **Clear all**.
+249
View File
@@ -0,0 +1,249 @@
---
status: shipped
created: 2026-08-05
owner: kandev
---
# Send Queued Messages Now
Decision:
[ADR-2026-08-05-queue-send-now-replaces-turn](../../decisions/2026-08-05-queue-send-now-replaces-turn.md)
## Why
When an agent is in a long-running turn, an urgent correction can sit in the
queue until that turn finishes. Users need to replace the current turn with one
specific queued instruction, or with the whole pending queue as one coherent
follow-up, without completing or advancing the task's workflow step.
## What
- Every visible pending queue row offers **Send Now**. On a fine-pointer
desktop it appears with the row actions on hover or keyboard focus; on a
coarse-pointer surface it is always visible and touch-sized.
- Per-row **Send Now** interrupts the active agent turn and dispatches that
exact entry as the first prompt of a replacement turn. Other queued entries
remain pending in their existing FIFO order.
- The queue header offers **Send Now** immediately to the left of **Clear all**.
It dispatches the click-time snapshot of all visible pending entries as one
replacement turn.
- Bulk content is concatenated in FIFO order with one blank line between
non-empty message bodies. Attachment-only entries add no empty separators.
Attachments retain FIFO order, and entity references are combined in first-
occurrence order with canonical duplicates removed.
- The bulk turn uses the oldest selected entry's model and plan-mode snapshot.
Its transcript envelope uses that entry's sender attribution while retaining
source entry identities and provenance in metadata for restoration and
diagnostics.
- If the aggregate would exceed the existing per-message attachment count,
attachment byte, or entity-reference limits, the request is rejected before
cancellation. No content is truncated and the queue is unchanged.
- A promptable session dispatches immediately without cancellation. A busy
session uses the existing backend-owned cancellation progress, cancels only
the turn observed when the action began, and starts the replacement turn
after cancellation settles.
- If ordinary FIFO delivery has reserved a queued entry but has not yet
accepted its prompt, Send Now wins that same-session handoff. The reserved
source is restored before the requested selection is claimed, so an
all-scope replacement can include it in one aggregate prompt. Once FIFO has
accepted its prompt, Send Now fails closed with `send_now_conflict`; it does
not duplicate or cancel that successor turn.
- Send Now is a replacement/steering cancellation. It does not create the
ordinary **Turn cancelled** message, move the task to review, evaluate
`cancel_triggers_turn_complete`, or run the cancelled turn's
`on_turn_complete` actions.
- The action is disabled while its request or any backend cancellation for the
session is pending. The backend also rejects overlapping Send Now or explicit
cancellation operations so rapid clicks and multiple clients cannot create
successor turns.
- Successful dispatch publishes the existing queue-status and session
cancellation updates. The initiating client refetches the authoritative queue
after success or failure.
## API Surface
New WebSocket action:
```text
message.queue.send_now
```
Request:
```json
{
"session_id": "session-id",
"scope": "entry",
"entry_id": "queue-entry-id"
}
```
or:
```json
{
"session_id": "session-id",
"scope": "all"
}
```
`scope` is required and is exactly `entry` or `all`. `entry_id` is required
only for `entry`; malformed combinations are rejected with `validation`.
Successful response:
```json
{
"session_id": "session-id",
"dispatched": true,
"sent_count": 3
}
```
`sent_count` is the number of source queue entries represented by the new
turn. The action returns success only after the selection is claimed and handed
to the replacement-turn dispatch path.
Errors:
- `entry_not_found`: the selected entry is no longer visible and pending.
- `queue_empty`: the `all` snapshot contains no visible pending entries.
- `queue_changed`: one or more bulk-snapshot entries changed eligibility before
the atomic claim; no partial selection is dispatched.
- `send_now_conflict`: another cancellation or Send Now operation already owns
the session.
- `turn_changed`: the active turn changed while the operation waited; the
successor is left untouched.
- `send_now_attachment_overflow`: the aggregate exceeds an attachment limit.
- `send_now_reference_overflow`: the aggregate exceeds the entity-reference
limit.
- `session_not_promptable`: the session has neither an interruptible active
turn nor a promptable state.
All requests require access to `session_id`. Authorization happens before any
queue read, cancellation, or mutation and uses the existing non-enumerating
session-not-found response.
## State and Concurrency
The orchestrator snapshots the active turn and, for `scope=all`, the ordered
visible entry IDs before beginning cancellation. All validation and aggregation
limits are checked before the cancellation signal is sent.
The cancel-and-dispatch decision uses the shared per-session cancellation and
queue-take serialization point. An ordinary FIFO handoff has an explicit
pre-acceptance phase: Send Now may supersede that reservation while the worker
has not claimed prompt ownership, but the worker must claim ownership before
creating a visible user message, running turn-start workflow effects, or
accepting the agent prompt. After that claim, the handoff is terminal for Send
Now and the existing conflict response applies.
When Send Now supersedes a pre-acceptance FIFO reservation, the backend
restores that exact source (including clearing a durable lifecycle
reservation), then atomically claims exactly the selected ID or the complete
bulk snapshot. New messages accepted after the snapshot remain queued. A
missing or newly ineligible bulk member fails the whole claim; the backend
never sends a partial bulk result or substitutes the FIFO head for a missing
selected entry.
Ordinary entries are removed when claimed, matching normal queue delivery.
Durable lifecycle entries remain reserved until the combined prompt is
accepted, then all durable source rows are acknowledged. A retryable dispatch
failure restores every ordinary source at its original FIFO position and
releases every durable reservation before publishing queue status.
## Permissions
- Any user who can access the session may invoke either Send Now action on its
visible pending entries, regardless of entry provenance.
- The action never accepts caller-supplied `task_id`, `user_id`, sender identity,
content, attachments, or metadata. Those values come from the authorized
session and persisted queue rows.
- Hidden durable entries already reserved for another delivery are not eligible.
## Failure Modes
- **Cancellation fails:** no queue selection is claimed; the entries remain
pending and the UI refetches and shows a localized error.
- **Selection changes during cancellation:** the active turn may already be
cancelled, but no replacement is dispatched from a partial or different
selection. The UI refetches and asks the user to retry.
- **FIFO handoff race:** if normal FIFO delivery reserved the head but has not
accepted its prompt, Send Now restores/reclaims that reservation and
dispatches the requested exact selection. If FIFO already accepted the
prompt, Send Now returns `send_now_conflict`; it leaves that successor and
the remaining queue authoritative rather than creating a duplicate turn.
- **Prompt admission fails after claim:** the backend restores the original
entries and their FIFO positions before publishing status. Existing ordinary
queue delivery retains its current process-crash window after a destructive
claim; durable lifecycle rows retain their accepted-until-acknowledged
guarantee.
- **Successor turn appears:** the operation fails with `turn_changed`, leaves
the successor running, and does not claim queue entries.
- **Conflicting explicit Cancel:** the already accepted operation wins. Send Now
never dispatches after a workflow-completing cancellation.
## Responsive and Mobile Behavior
- The existing inline queue panel remains the desktop and phone composition;
its queue list remains the only internal scroll owner and the composer stays
visible.
- Desktop row actions keep their current hover/focus disclosure. Phone and
coarse-pointer layouts expose per-row **Send Now** without hover and give it
at least a 44 by 44 CSS-pixel hit target.
- The header **Send Now**, **Clear all**, and collapse controls remain reachable
without horizontal page overflow. The header may wrap its action group on a
narrow phone rather than shrinking labels below usable touch targets.
- Desktop and mobile share the same queue hook, cancellation state, and backend
action. Mobile Playwright coverage uses touch input and proves the same
replacement-turn result.
## Scenarios
- **GIVEN** an agent is busy and three messages are queued, **WHEN** the user
clicks row **Send Now** on the second message, **THEN** the active turn is
interrupted, the second message starts the replacement turn, and the first
and third messages remain queued in FIFO order.
- **GIVEN** an agent is busy and three messages are queued, **WHEN** the user
clicks header **Send Now**, **THEN** one replacement turn receives the three
message bodies concatenated in FIFO order and the queue becomes empty.
- **GIVEN** queued messages contain attachments and repeated entity references,
**WHEN** the user sends all now, **THEN** the replacement prompt contains all
attachments in FIFO order and one canonical copy of each reference.
- **GIVEN** a bulk aggregate exceeds an existing message limit, **WHEN** the
user clicks header **Send Now**, **THEN** the active turn continues, the queue
is unchanged, and a localized limit error is shown.
- **GIVEN** the session is already promptable with queued work, **WHEN** the user
clicks either Send Now action, **THEN** the requested selection starts without
issuing a cancellation.
- **GIVEN** a promptable session has two queued messages and normal FIFO
delivery has reserved the first one but has not accepted its prompt, **WHEN**
the user clicks header Send Now, **THEN** the FIFO reservation is restored,
both messages are claimed in FIFO order, and exactly one replacement prompt
contains both bodies.
- **GIVEN** normal FIFO delivery has already accepted its successor prompt,
**WHEN** the user clicks Send Now, **THEN** the action fails closed without a
duplicate user message, duplicate prompt, or cancellation of that successor,
and the authoritative remaining queue is preserved.
- **GIVEN** the workflow step enables `cancel_triggers_turn_complete`, **WHEN**
the user sends a queued message now, **THEN** the task stays on the same step
and only the replacement turn's ordinary lifecycle hooks may change it.
- **GIVEN** a successor turn replaces the observed active turn while Send Now
waits, **WHEN** the operation revalidates, **THEN** it leaves the successor
running and the requested queue entries pending.
- **GIVEN** a phone viewport with a busy agent and queued messages, **WHEN** the
user opens the queue panel, **THEN** both per-row and header Send Now controls
are visible, touch-sized, and can start the same replacement-turn flow without
horizontal overflow.
## Out of Scope
- Reordering queued messages before sending.
- Choosing a different model or plan mode for the bulk turn.
- Sending an arbitrary user-selected subset other than one entry or all visible
pending entries.
- Changing normal FIFO auto-drain selection or **Run next**, **Remove**, **Clear
all**, edit, or merge semantics. FIFO participates in Send Now handoff
arbitration only until its prompt is accepted.
- Making ordinary queued-message dispatch crash-durable after its existing
destructive claim boundary.