Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): resume queued messages after stop
cyh56cff46c0737
diff --git a/core/runtime_ownership.py b/core/runtime_ownership.pyindex b526be8c9..cf7830929 100644--- a/core/runtime_ownership.py+++ b/core/runtime_ownership.py@@ -38,18 +38,16 @@ class SessionRuntimeDisposition(str, Enum):ACTIVE = "active"TRANSITIONING = "transitioning"RUNNABLE = "runnable"- WAITING = "waiting"RECLAIMABLE = "reclaimable"UNKNOWN = "unknown"_DISPOSITION_PRIORITY = {SessionRuntimeDisposition.RECLAIMABLE: 0,- SessionRuntimeDisposition.WAITING: 1,- SessionRuntimeDisposition.RUNNABLE: 2,- SessionRuntimeDisposition.TRANSITIONING: 3,- SessionRuntimeDisposition.ACTIVE: 4,- SessionRuntimeDisposition.UNKNOWN: 5,+ SessionRuntimeDisposition.RUNNABLE: 1,+ SessionRuntimeDisposition.TRANSITIONING: 2,+ SessionRuntimeDisposition.ACTIVE: 3,+ SessionRuntimeDisposition.UNKNOWN: 4,}_KNOWN_ACTIVITY_PHASES = frozenset(@@ -101,7 +99,6 @@ class SessionRuntimeOwnershipSnapshot:turn_ids: tuple[str, ...]active_activity_ids: tuple[str, ...]fallback_run_ids: tuple[str, ...]- queue_hold_state: strreasons: tuple[str, ...]@@ -159,8 +156,7 @@ class RuntimeTargetOwnershipSnapshot:@propertydef has_runnable_deliveries(self) -> bool:return any(- session.queue_hold_state == "open"- and any(reason == "delivery:queued" for reason in session.reasons)+ any(reason == "delivery:queued" for reason in session.reasons)for session in self.sessions)@@ -189,13 +185,10 @@ class RuntimeTargetOwnershipSnapshot:reason.removeprefix("delivery:")).ordering== "fence"- or (- session.queue_hold_state == "open"- and policy_for(- reason.removeprefix("delivery:")- ).ordering- == "claimable"- )+ or policy_for(+ reason.removeprefix("delivery:")+ ).ordering+ == "claimable"))for reason in session.reasons@@ -649,12 +642,7 @@ class RuntimeOwnershipProvider:elif ordering == "fence":disposition = SessionRuntimeDisposition.TRANSITIONINGelif ordering == "claimable":- held = str(session_by_id[session_id].get("queue_hold_state") or "open")- disposition = (- SessionRuntimeDisposition.WAITING- if held == "held"- else SessionRuntimeDisposition.RUNNABLE- )+ disposition = SessionRuntimeDisposition.RUNNABLEelse:disposition = SessionRuntimeDisposition.RECLAIMABLEfacts[session_id].append(disposition)@@ -854,7 +842,6 @@ class RuntimeOwnershipProvider:turn_ids=tuple(turn_ids[session_id]),active_activity_ids=tuple(activity_ids[session_id]),fallback_run_ids=tuple(run_ids[session_id]),- queue_hold_state=str(row.get("queue_hold_state") or "open"),reasons=tuple(reasons[session_id]),))diff --git a/core/session_turns.py b/core/session_turns.pyindex 02313b554..8c168f5d1 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -1751,7 +1751,6 @@ class SessionTurnManager:if (delivery_store.active_turn(conn, session_id) is not None- or delivery_store.queue_is_held(conn, session_id)or backend in self._draining_backends):return None@@ -2240,25 +2239,10 @@ class SessionTurnManager:delivery = queuedactive = delivery_store.active_turn(conn, request.session_id)while active is None and not backend_draining:- held = delivery_store.queue_is_held(conn, request.session_id)queued_payloads = delivery_store.claimable_fifo_prefix(conn, request.session_id)- held_fence = (- delivery_store.ordering_head(- conn,- request.session_id,- include_claimable=False,- )- if held- else None- )- if held and held_fence is not None:- segment_payloads = []- elif held:- segment_payloads = [delivery_store.delivery_payload(delivery)]- else:- segment_payloads = _collect_delivery_segment(queued_payloads)+ segment_payloads = _collect_delivery_segment(queued_payloads)segment = [delivery_store.get_delivery(conn, str(row["id"]))for row in segment_payloads@@ -2592,8 +2576,6 @@ class SessionTurnManager:self._delivery_has_attachment_references(row)for row in delivery_rows):- if not delivery_store.set_queue_hold(conn, session_id, held=False):- raise RuntimeError("attachment queue promotion lost its Session hold CAS")return DeliveryResult(delivery_id,None,@@ -2637,8 +2619,6 @@ class SessionTurnManager:)if not claimed_rows:return DeliveryResult(delivery_id, None, "refused", reason="claim_lost")- if not delivery_store.set_queue_hold(conn, session_id, held=False):- raise RuntimeError("successful queue promotion lost its Session hold CAS")leader = claimed_rows[0]if leader["state"] == "claimed" and turn_id:@@ -2876,19 +2856,6 @@ class SessionTurnManager:current_id = str((current or {}).get("id") or "") or Noneif current is None:if request.content is None:- observed_turn_id = str(request.expected_turn_id or "").strip()- if observed_turn_id:- observed_turn = delivery_store.get_turn(conn, observed_turn_id)- if (- observed_turn is not None- and observed_turn["session_id"] == request.session_id- and observed_turn["state"] == "terminal"- ):- delivery_store.set_queue_hold(- conn,- request.session_id,- held=True,- )return DeliveryResult(None, None, "settled", reason="not_active")delivery = self._insert_delivery(conn,@@ -2912,10 +2879,19 @@ class SessionTurnManager:else:interrupt_target_id = current_iddelivery = None- queue_was_held = delivery_store.queue_is_held(- conn,- request.session_id,- )+ expected_turn_id = str(request.expected_turn_id or "").strip()+ if (+ request.content is None+ and expected_turn_id+ and current_id != expected_turn_id+ ):+ return DeliveryResult(+ None,+ None,+ "settled",+ current_id,+ "target_turn_changed",+ )control_in_progress = current.get("control_state") in {"pending","interrupting",@@ -2982,11 +2958,6 @@ class SessionTurnManager:)if not terminalized.get("changed") or retired is None:raise RuntimeError("replacement supersession lost")- delivery_store.set_queue_hold(- conn,- request.session_id,- held=True,- )superseded = delivery_store.cas_turn(conn,current_id,@@ -3018,15 +2989,6 @@ class SessionTurnManager:if queued is None:raise RuntimeError("concurrent P0 loser queue claim lost")else:- # Only an empty-P0 Stop establishes a backlog hold. A content-P0- # replacement preserves whatever policy already existed; its- # successor may bypass that policy but must not rewrite it.- if delivery_id is None:- delivery_store.set_queue_hold(- conn,- request.session_id,- held=True,- )if delivery_id is not None:successor_id = delivery_store.new_turn_id()delivery_store.insert_turn(@@ -3072,10 +3034,7 @@ class SessionTurnManager:"control_attempt_id": attempt_id,"control_expected_native_turn_id": current.get("native_turn_id"),"control_receipt_outcome": None,- "control_receipt_json": json.dumps(- {"queue_hold_was_held": queue_was_held},- sort_keys=True,- ),+ "control_receipt_json": "{}","control_successor_delivery_id": delivery_id,"control_successor_turn_id": successor_id,},@@ -3308,22 +3267,6 @@ class SessionTurnManager:if not terminalized.get("changed") or queued is None:raise RuntimeError("definitive P0 refusal fallback lost")fallback_state = "queued"- if (- definitive- and not terminal_proven- and durable_turn.get("control_mode") == "replace"- ):- try:- control_context = json.loads(- str(durable_turn.get("control_receipt_json") or "{}")- )- except (TypeError, ValueError):- control_context = {}- delivery_store.set_queue_hold(- conn,- session_id,- held=bool(control_context.get("queue_hold_was_held")),- )saved = delivery_store.cas_turn(conn,str(logical_turn_id),@@ -3745,7 +3688,7 @@ class SessionTurnManager:"changed": False,"successor_turn_id": None,"delivery_id": None,- "preserve_queue": False,+ "defer_queue_resume": False,}result: dict[str, Any]materialized_id: str | None = None@@ -3777,9 +3720,7 @@ class SessionTurnManager:"changed": False,"successor_turn_id": None,"delivery_id": None,- "preserve_queue": delivery_store.queue_is_held(- conn, str((turn or {}).get("session_id") or "")- ),+ "defer_queue_resume": False,}else:if outcome not in {"completed", "failed", "canceled", "not_written"}:@@ -3815,7 +3756,7 @@ class SessionTurnManager:"changed": False,"successor_turn_id": None,"delivery_id": None,- "preserve_queue": True,+ "defer_queue_resume": True,"reason": "start_acceptance_unproven",}if initial_batch and all(row["state"] == "claimed" for row in initial_batch):@@ -3959,7 +3900,7 @@ class SessionTurnManager:"changed": False,"successor_turn_id": None,"delivery_id": materialized_id,- "preserve_queue": delivery_store.queue_is_held(conn, session_id),+ "defer_queue_resume": False,}else:# A never-called steer has definitive negative evidence once@@ -4104,8 +4045,8 @@ class SessionTurnManager:if (claimed_successor is Noneand resume_successors- and outcome == "completed"and session_status == "active"+ and (outcome != "not_written" or bool(forced_retire_ids))):claimed_successor = self._claim_fifo_batch_in_transaction(conn,@@ -4119,6 +4060,17 @@ class SessionTurnManager:is not None):start_deferred = True+ elif (+ claimed_successor is None+ and (+ not resume_successors+ or (outcome == "not_written" and not forced_retire_ids)+ )+ and session_status == "active"+ and delivery_store.claimable_fifo_head(conn, session_id)+ is not None+ ):+ start_deferred = Truelatest_turn = delivery_store.get_turn(conn, turn_id)if (not linked_activation_deferred@@ -4146,10 +4098,7 @@ class SessionTurnManager:"changed": True,"successor_turn_id": claimed_successor,"delivery_id": materialized_id,- "preserve_queue": (- delivery_store.queue_is_held(conn, session_id)- or start_deferred- ),+ "defer_queue_resume": start_deferred,"unknown_start_exhausted": unknown_start_exhausted,}terminal_run_ids = (@@ -4248,7 +4197,7 @@ class SessionTurnManager:)if result.get("changed"):self._publish_queue_update(session_id)- if not result.get("preserve_queue"):+ if not result.get("defer_queue_resume"):asyncio.create_task(self._resume_after_native_terminal(session_id, turn_id),name=f"durable-terminal-resume:{session_id}",@@ -4285,7 +4234,7 @@ class SessionTurnManager:try:if cancelled:- interruption = settled_by or SETTLED_BY_STOPPED+ interruption = settled_by or SETTLED_BY_NO_TERMINAL_RESULTreturn self._terminalize_durable_turn(turn_id,"canceled" if interruption == SETTLED_BY_STOPPED else "failed",@@ -4300,7 +4249,7 @@ class SessionTurnManager:if interruption == SETTLED_BY_RESTARTEDelse None),- resume_successors=interruption != SETTLED_BY_RESTARTED,+ resume_successors=interruption == SETTLED_BY_STOPPED,)if failed:# Dispatch may have written before raising. Preserve starting work@@ -4353,7 +4302,7 @@ class SessionTurnManager:successor_id = str(result.get("successor_turn_id") or "")if successor_id:await self._start_persisted_turn(successor_id)- elif result.get("changed") and not result.get("preserve_queue"):+ elif result.get("changed") and not result.get("defer_queue_resume"):with self._sqlite_engine().connect() as conn:terminal = delivery_store.get_turn(conn, turn_id)if terminal is not None:@@ -4686,7 +4635,7 @@ class SessionTurnManager:)current = self.in_flight.get(session_id)should_resume = bool(result.get("successor_turn_id")) or (- current is None and not bool(result.get("preserve_queue"))+ current is None and not bool(result.get("defer_queue_resume")))if result.get("changed") and should_resume:return asyncio.create_task(@@ -4749,7 +4698,6 @@ class SessionTurnManager:.join(delivery_rows, delivery_rows.c.id == head_id).where(agent_sessions.c.status == "active",- agent_sessions.c.queue_hold_state == "open",~live_turn,).order_by(@@ -5983,10 +5931,9 @@ class SessionTurnManager:A no-op chunk sink keeps ``dispatch_turn`` alive for the turn's lifetime so``in_flight`` stays populated (Stop works) and the session-level``turn.start`` / ``turn.end`` lifecycle is published for the browser's- working indicator. On NATURAL completion the queue is flushed: messages the- user sent while this turn ran are merged + run as the next turn when the- durable Session hold is open. Stop and replacement policy lives in that- hold plus the durable Turn control slot, not on this process task.+ working indicator. After every definitive terminal outcome, the oldest+ compatible queued segment starts immediately. A real safety fence can defer+ that resume, but an idle Session never keeps claimable backlog by policy.``source`` selects the human vs. scheduler turn path in ``dispatch_turn``;a scheduled / watch run passes ``SOURCE_SCHEDULED`` so it goes through the@@ -6056,9 +6003,9 @@ class SessionTurnManager:cancelled = True# Do NOT decide the reason here: the canceller knows it, and it is# recorded on the Turn (``cancel_settled_by``) which is only popped- # in the ``finally`` below. A plain Stop leaves it unset and reads- # as ``SETTLED_BY_STOPPED``; a backend runtime refresh sets its own- # value so it is not misreported as a user stop (Codex P1).+ # in the ``finally`` below. The Stop path sets ``stopped`` before+ # cancellation; an unrelated task cancellation remains unknown and+ # must not release queued work as though the user had stopped it.raiseexcept Exception:# Preserve the exact boundary phase even when the handler's own@@ -6100,12 +6047,11 @@ class SessionTurnManager:if cancelled:# Attribute the cancellation to whoever caused it. The Turn# carries the cause when the canceller had a more specific one- # than "the user stopped this"; a plain Stop / send-now leaves- # it unset, and ``stopped`` (→ ``canceled``) stays the default- # reading of a cancelled turn.+ # than an unrelated runner cancellation. Only an explicit+ # Stop is allowed to project ``stopped`` and release backlog.settled_by = (getattr(turn, "cancel_settled_by", None) if turn is not None else None- ) or SETTLED_BY_STOPPED+ ) or SETTLED_BY_NO_TERMINAL_RESULTself._settle_model_hub_turn(context, settled_by)if logical_turn_id and durable_turn_registered:durable_terminal_result = self._reconcile_durable_runner_release(@@ -6141,20 +6087,14 @@ class SessionTurnManager:# emit above so the honest outbound terminal writes first and this# guarded write degrades to a no-op.self._settle_turn_owned_agent_runs(context, settled_by)- # Durable Session policy is the only backlog authority. Legacy- # non-DB turns conservatively avoid draining after Stop/failure.- preserve_durable_queue = bool(+ # A real start/reconciliation fence may defer resume. Stop,+ # failure, and natural completion are all terminal and therefore+ # all release the Session to its oldest claimable queue segment.+ defer_durable_resume = bool(durable_turn_registered- and durable_terminal_result.get("preserve_queue")- )- should_flush = (- not preserve_durable_queue- and not cancelled- and not failed- and not prewrite_refused- and not definitive_prewrite_exit- and settled_by != SETTLED_BY_STOPPED+ and durable_terminal_result.get("defer_queue_resume"))+ should_flush = not defer_durable_resumebackend = self._context_backend(context)if should_flush and backend in self._draining_backends:self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)@@ -6966,7 +6906,7 @@ class SessionTurnManager:returncurrent = self.in_flight.get(session_id)should_resume = bool(terminal.get("successor_turn_id")) or not bool(- terminal.get("preserve_queue")+ terminal.get("defer_queue_resume"))if (terminal.get("changed")@@ -7306,10 +7246,8 @@ class SessionTurnManager:"for Turn=%s",turn_token,)- should_flush = (- not bool(durable_terminal_result.get("preserve_queue"))- and not cancelled- and settled_by != SETTLED_BY_STOPPED+ should_flush = not bool(+ durable_terminal_result.get("defer_queue_resume"))if should_flush:try:diff --git a/docs/plans/agent-message-priority.md b/docs/plans/agent-message-priority.mdindex 7337b564a..2e4d86108 100644--- a/docs/plans/agent-message-priority.md+++ b/docs/plans/agent-message-priority.md@@ -98,8 +98,8 @@ instead of claiming equivalent durability.| Show annotation | P1 | Delivers the annotation to the current Turn when possible. || Session callback | P1 | Delivers each completed child Run independently. || Scheduled Task | P3 | Never interrupts or steers the work a user is already doing. |-| Stop | Empty P0 | Stops the exact live Turn and establishes the durable queue hold. |-| Send Now existing head | Empty P1 | Releases the hold and promotes only the exact observed FIFO head. |+| Stop | Empty P0 | Stops the exact live Turn. Definitive terminal settlement immediately starts the oldest claimable P3 segment. |+| Send Now existing head | Empty P1 | Promotes only the exact observed FIFO head. |Attachments remain part of the same Delivery. Because native steer adaptersaccept text only, an attachment-bearing P1 is preserved as P3 and starts a newdiff --git a/docs/plans/harness-run-reliability.md b/docs/plans/harness-run-reliability.mdindex dbaf83b14..ec75bdf04 100644--- a/docs/plans/harness-run-reliability.md+++ b/docs/plans/harness-run-reliability.md@@ -80,12 +80,11 @@ Every remaining change must preserve these rules:## 3. Runtime supervision design-Consider one concrete Session. It has an old P3 Delivery `Q1`, queue hold is-`held`, and no Turn is live. The backend process may be reclaimed because `Q1`-is durable and policy deliberately forbids autonomous drain. Later the user-issues send-now: the existing synchronous writer validates the observed head,-releases the hold, and claims exactly `Q1` in one transaction before returning.-The backend runtime is recreated only when that Turn starts. A subsequent+Consider one concrete Session. It has an old P3 Delivery `Q1` and no live Turn.+That durable fact is `runnable`: the delivery lane must claim `Q1`, while the+idle backend process remains reclaimable until the Turn actually starts. If an+empty P1 send-now races the recovery wake, its synchronous writer validates and+claims exactly the observed head in one transaction. A subsequent`queue.updated` hint is for projection and passive recovery, never the authorityfor send-now's stale-head/refusal result. At no point is `last_activity`falsified, and neither the hint nor the reclaimer owns `Q1`.@@ -150,7 +149,6 @@ class SessionRuntimeDisposition(str, Enum):ACTIVE = "active" # an exact live owner needs the runtimeTRANSITIONING = "transitioning" # an unresolved handoff forbids reclamationRUNNABLE = "runnable" # durable work should be activated now- WAITING = "waiting" # durable policy intentionally blocks activationRECLAIMABLE = "reclaimable" # no durable or in-process owner remainsUNKNOWN = "unknown" # the snapshot could not prove safety@@ -162,7 +160,6 @@ class SessionRuntimeOwnershipSnapshot:turn_ids: tuple[str, ...]active_activity_ids: tuple[str, ...]fallback_run_ids: tuple[str, ...]- queue_hold_state: strreasons: tuple[str, ...]@dataclass(frozen=True)@@ -221,18 +218,17 @@ The exact classification is:| `starting|active` Turn with its exact owned Delivery, persisted active Activity, or exact in-process backend operation | `active` | forbid ordinary idle reclamation || exact linked `waiting` Turn plus its initial `interrupt_waiting` Delivery | `transitioning` | fail closed for this pass and reconcile that exact predecessor/successor owner || unresolved Delivery fence or an ownership handoff that cannot yet be classified | `transitioning` | fail closed; reconcile the exact owner |-| open-hold ownerless FIFO head or queued execution-bearing fallback Run not yet represented by a Delivery | `runnable` | wake its delivery/request lane; it does not itself pin backend resources |+| ownerless FIFO head or queued execution-bearing fallback Run not yet represented by a Delivery | `runnable` | wake its delivery/request lane; it does not itself pin backend resources || claimed fallback Run in normalized `running` / legacy `processing` with no persisted execution-start marker (`pid IS NULL` or absent) | `transitioning` | preserve the pre-execution handoff until exact recovery requeues or starts it || fallback Run in normalized `running` / legacy `processing` with the persisted execution-start marker (`pid IS NOT NULL`) | `active` | preserve its runtime until #1140's exact terminal/teardown settlement |-| held FIFO backlog with no live Turn/fence | `waiting` | preserve durable work but allow disposable backend runtime reclamation || terminal Delivery/Turn history and terminal Runs only | `reclaimable` | no pin || read failure, unknown Delivery state or execution-bearing Run type, or an unpaired/mismatched `waiting`/`interrupt_waiting` half | `unknown` | fail closed for this cycle and log the reason |`queued` therefore does not mean "keep a backend process alive forever". An-open queue head means "activate it now"; a held queue means "keep it durable but-do not execute it". Both survive runtime reclamation. This resolves the apparent-contradiction between an idle runtime and durable queued input without inventing-fake activity.+ownerless queue head means "activate it now", while its durable row survives+runtime reclamation until the delivery lane creates the exact Turn owner. This+resolves the apparent contradiction between an idle runtime and durable queued+input without inventing fake activity or a second policy state.The provider consumes `DELIVERY_STATE_MATRIX` and the current Turn-statecontract as related facts, not as independent liveness enums. The exact@@ -303,7 +299,7 @@ refreshes `session_last_activity` or pins the old runtime.Activation and transition recovery never depend on a runtime target alreadyexisting or reaching the cleanup loop. The `session_deliveries` lane has two-bounded indexed eligibility queries: open-hold Session ids with a queued head+bounded indexed eligibility queries: Session ids with a claimable queued headand no live Turn, and unresolved Delivery/Turn fences, starting owners, orwaiting successors that require exact reconciliation. It invokes a narrow`SessionTurnManager` claim/recovery entry for the exact Session plus observed@@ -688,8 +684,8 @@ Minimum baseline cases:Make runtime reclamation and durable work activation consume one coherentsession disposition. Active or transitioning work must not lose its runtime,-open runnable work must be woken, and held backlog must remain durable without-keeping a backend process alive forever.+and ownerless runnable work must be woken without keeping a backend process+alive forever.### Required behavior@@ -709,11 +705,9 @@ keeping a backend process alive forever.Session-less fallback Runs from their persisted legacy Session key plusbackend/agent execution identity to the exact resource target; an unresolvednonterminal route fails closed for that backend cycle.-2. Derive `active`, `transitioning`, `runnable`, `waiting`, `reclaimable`, or+2. Derive `active`, `transitioning`, `runnable`, `reclaimable`, or`unknown` exactly as §3.2 specifies. In particular:- an open, ownerless FIFO head is `runnable`, not a permanent runtime pin;- - a held backlog with no live owner is `waiting` and may release backend- resources without changing durable queue state;- a fence or Turn owner forbids reclamation;- terminal history and `watch_runtime` do not pin;- an execution-bearing Run is considered only when its exact Delivery/Turn@@ -749,7 +743,7 @@ keeping a backend process alive forever.boundary through generation detach/cleanup initiation so no delayedold-generation admission can become a new durable pin after the finalsnapshot.- The lane itself uses separate bounded indexed queries for open-hold queued+ The lane itself uses separate bounded indexed queries for claimable queuedSessions without live Turns and for unresolved Delivery/Turn fences,starting owners, and waiting successors. It invokes a manager entry guardedby the observed Session, Delivery, Turn, attempt, and native identity; stalediff --git a/docs/plans/session-delivery-foundation.md b/docs/plans/session-delivery-foundation.mdindex 5dd888962..5b442636c 100644--- a/docs/plans/session-delivery-foundation.md+++ b/docs/plans/session-delivery-foundation.md@@ -15,7 +15,9 @@ coherent before dispatch, during a native Turn, and after acceptance.identity, and terminal snapshot.- `messages` owns accepted communication only. One accepted initial batchmaterializes one Message; every Delivery in that batch links to it.-- `agent_sessions` owns archive state, queue hold, and composer draft.+- `agent_sessions` owns archive state and composer draft. Queue liveness is+ derived: an active Session with no live Turn and a claimable FIFO head is+ runnable, so no independent hold state can leave queued work idle by policy.- `agent_runs` may reference the Delivery created for that Run. It does not ownqueue order and never binds directly to a Message. Each Run has at most oneDelivery, while one Turn may accept several Deliveries and therefore severaldiff --git a/storage/alembic/versions/20260806_0047_remove_session_queue_hold.py b/storage/alembic/versions/20260806_0047_remove_session_queue_hold.pynew file mode 100644index 000000000..c97c97eb4--- /dev/null+++ b/storage/alembic/versions/20260806_0047_remove_session_queue_hold.py@@ -0,0 +1,107 @@+"""remove the Session queue hold policy++Revision ID: 20260806_0047+Revises: 20260804_0046+Create Date: 2026-08-06+"""++from __future__ import annotations++import sqlalchemy as sa+from alembic import op++revision = "20260806_0047"+down_revision = "20260804_0046"+branch_labels = None+depends_on = None++_COLUMNS = ("queue_hold_state", "queue_hold_version", "queue_held_at")+_CHECK = "ck_agent_sessions_queue_hold_state"+++def _column_names(bind) -> set[str]:+ return {+ str(column["name"])+ for column in sa.inspect(bind).get_columns("agent_sessions")+ }+++def _check_names(bind) -> set[str]:+ return {+ str(check["name"])+ for check in sa.inspect(bind).get_check_constraints("agent_sessions")+ if check.get("name")+ }+++def _drop_hold_columns(bind) -> None:+ columns = _column_names(bind)+ checks = _check_names(bind)+ with op.batch_alter_table("agent_sessions") as batch:+ if _CHECK in checks:+ batch.drop_constraint(_CHECK, type_="check")+ for column in reversed(_COLUMNS):+ if column in columns:+ batch.drop_column(column)+++def _restore_hold_columns(bind) -> None:+ columns = _column_names(bind)+ with op.batch_alter_table("agent_sessions") as batch:+ if "queue_hold_state" not in columns:+ batch.add_column(+ sa.Column(+ "queue_hold_state",+ sa.String(),+ server_default="open",+ nullable=False,+ )+ )+ if "queue_hold_version" not in columns:+ batch.add_column(+ sa.Column(+ "queue_hold_version",+ sa.Integer(),+ server_default="1",+ nullable=False,+ )+ )+ if "queue_held_at" not in columns:+ batch.add_column(sa.Column("queue_held_at", sa.String(), nullable=True))+ if _CHECK not in _check_names(bind):+ batch.create_check_constraint(+ _CHECK,+ "queue_hold_state in ('open', 'held')",+ )+++def _sqlite_rebuild(operation) -> None:+ bind = op.get_bind()+ # SQLite cannot rebuild a referenced parent table while FK enforcement is+ # enabled. Keep the exception local to this autocommit block, restore it+ # immediately, and fail if the rebuilt schema has any dangling references.+ with op.get_context().autocommit_block():+ bind.exec_driver_sql("PRAGMA foreign_keys=OFF")+ try:+ operation(bind)+ finally:+ bind.exec_driver_sql("PRAGMA foreign_keys=ON")+ violations = bind.exec_driver_sql("PRAGMA foreign_key_check").fetchall()+ if violations:+ raise RuntimeError("queue hold removal left invalid SQLite foreign keys")+++def upgrade() -> None:+ bind = op.get_bind()+ if bind.dialect.name == "sqlite":+ _sqlite_rebuild(_drop_hold_columns)+ else:+ _drop_hold_columns(bind)+++def downgrade() -> None:+ bind = op.get_bind()+ if bind.dialect.name == "sqlite":+ _sqlite_rebuild(_restore_hold_columns)+ else:+ _restore_hold_columns(bind)diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex df229f5c5..cd06fcaba 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -1602,8 +1602,6 @@ def message_for_delivery(conn: Connection, delivery: dict[str, Any]) -> dict[strdef queued_session_ids_without_live_turns(conn: Connection,session_id: str | None = None,- *,- include_held: bool = False,) -> list[str]:live = select(session_turns.c.id).where(session_turns.c.session_id == message_deliveries.c.session_id,@@ -1616,8 +1614,6 @@ def queued_session_ids_without_live_turns(.where(agent_sessions.c.status == "active").where(~live))- if not include_held:- query = query.where(agent_sessions.c.queue_hold_state == "open")if session_id:query = query.where(message_deliveries.c.session_id == session_id)return [str(value) for value in conn.execute(query.distinct()).scalars()]@@ -1914,33 +1910,6 @@ def retire_for_archive(conn: Connection, session_id: str) -> dict[str, Any]:}-def set_queue_hold(conn: Connection, session_id: str, *, held: bool) -> bool:- row = conn.execute(- select(agent_sessions.c.queue_hold_version).where(agent_sessions.c.id == session_id)- ).first()- if row is None:- return False- version = int(row[0])- result = conn.execute(- update(agent_sessions)- .where(agent_sessions.c.id == session_id)- .where(agent_sessions.c.queue_hold_version == version)- .values(- queue_hold_state="held" if held else "open",- queue_hold_version=version + 1,- queue_held_at=utc_now_iso() if held else None,- )- )- return result.rowcount == 1---def queue_is_held(conn: Connection, session_id: str) -> bool:- value = conn.execute(- select(agent_sessions.c.queue_hold_state).where(agent_sessions.c.id == session_id)- ).scalar_one_or_none()- return value == "held"--def set_draft(conn: Connection, session_id: str, text: str | None) -> bool:now = utc_now_iso()result = conn.execute(diff --git a/storage/migrations.py b/storage/migrations.pyindex 073f9d547..b7397d93d 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -115,9 +115,6 @@ PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS = {HEAD_REQUIRED_COLUMNS = PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS | {"agent_sessions": PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS["agent_sessions"]| {- "queue_hold_state",- "queue_hold_version",- "queue_held_at","composer_draft_text","composer_draft_updated_at",},diff --git a/storage/models.py b/storage/models.pyindex 9ba6368b4..39fbacd2c 100644--- a/storage/models.py+++ b/storage/models.py@@ -138,11 +138,6 @@ agent_sessions = Table(# ``running`` while a turn is in flight, ``failed`` when the most recent# turn errored, ``idle`` otherwise. Drives the workbench sidebar status dot.Column("agent_status", String, nullable=False, server_default="idle"),- # Session-level policy/state. The hold blocks only autonomous backlog drain;- # explicit admission and empty-P1 release remain Delivery-manager decisions.- Column("queue_hold_state", String, nullable=False, server_default="open"),- Column("queue_hold_version", Integer, nullable=False, server_default="1"),- Column("queue_held_at", String, nullable=True),# Composer state is one value per Session, not a communication record.Column("composer_draft_text", Text, nullable=True),Column("composer_draft_updated_at", String, nullable=True),@@ -171,10 +166,6 @@ agent_sessions = Table("id",),Index("ix_agent_sessions_native_session", "native_session_id"),- CheckConstraint(- "queue_hold_state in ('open', 'held')",- name="ck_agent_sessions_queue_hold_state",- ),)runtime_records = Table(diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex aa1d85863..b70a842fa 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -2343,7 +2343,7 @@ scenarios:kind: cancellationlayer: scenariobackend: shared- test: tests/test_scheduled_tasks.py::test_service_teardown_terminalizes_transferred_durable_turn_without_draining_held_queue+ test: tests/test_scheduled_tasks.py::test_service_teardown_terminalizes_transferred_turn_without_starting_queued_work- id: HFR-104name: restart recovery fails executed Runs and preserves separately owned rowsstatus: covered@@ -2380,12 +2380,12 @@ scenarios:backend: codextest: tests/test_runtime_ownership.py::test_hfr_131_open_head_wakes_survives_reclaim_and_claims_exact_head- id: HFR-132- name: a held head survives reclamation and starts only after explicit release+ name: a queued head wakes without an explicit Session policy releasestatus: coveredkind: recoverylayer: scenariobackend: codex- test: tests/test_runtime_ownership.py::test_hfr_132_held_head_survives_reclaim_then_explicit_release_starts+ test: tests/test_runtime_ownership.py::test_hfr_132_queued_head_wakes_without_an_explicit_release- id: HFR-133name: unresolved Delivery fences and Turn ownership block reclamationstatus: covereddiff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex 66004bb57..6ad34bb9b 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -141,11 +141,11 @@ scenarios:layer: contracttest: tests/test_session_delivery_fsm.py::test_unresolved_p1_fence_blocks_later_but_not_older_fifo- id: MESSAGE-DELIVERY-102- name: Queue hold blocks autonomous backlog but not a new idle admission+ name: Stop terminalization immediately resumes the oldest queued segmentstatus: coveredkind: lifecyclelayer: contract- test: tests/test_session_delivery_fsm.py::test_held_old_backlog_does_not_block_new_idle_p3+ test: tests/test_session_delivery_fsm.py::test_stop_terminalization_resumes_oldest_queued_segment- id: MESSAGE-DELIVERY-201name: Every approved producer class maps to one explicit delivery prioritystatus: covereddiff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex e588bec5e..bf4142be6 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -1700,7 +1700,7 @@ def test_startup_recovered_annotation_retries_reserved_dispatch_text(assert transcript[0]["content"]["annotation"]["quote"] == "Quarterly summary"-def test_idle_show_admission_starts_itself_without_releasing_held_backlog(+def test_idle_show_p1_admission_starts_before_recovery_drain(monkeypatch,tmp_path,):@@ -1734,9 +1734,8 @@ def test_idle_show_admission_starts_itself_without_releasing_held_backlog(conn,scope_id=scope_id,session_id=session["id"],- text="older stopped message",+ text="older queued message",)- assert message_deliveries.set_queue_hold(conn, session["id"], held=True)store = ShowSessionEventStore()try:annotation = store.append(@@ -1776,12 +1775,6 @@ def test_idle_show_admission_starts_itself_without_releasing_held_backlog():runs.append((sid, text, source))_bind_test_native_start(engine, context)- manager._terminalize_durable_turn(- logical_turn_id,- "completed",- settled_by=SETTLED_BY_TERMINAL_RESULT,- evidence_kind="test_terminal",- )manager._run = capture_runtransport = httpx.ASGITransport(app=app)@@ -2177,10 +2170,8 @@ def test_async_dispatch_flushes_one_compatible_queue_segment_on_turn_end(monkeypassert transcript["messages"][1]["metadata"]["_web_push_user_key"] == "remote:user-a"-def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):- """A user Stop interrupts the turn but must NOT flush the queue — the user- asked to keep queued messages on stop ('不清空队列'). The queued rows survive- the cancellation; only a natural turn end (or send-now) runs them."""+def test_cancel_resumes_the_oldest_queued_segment(monkeypatch, tmp_path):+ """Once Stop makes the Session idle, its queued work starts immediately."""from core.services import sessions as sessions_servicefrom storage import messages_servicefrom storage.db import create_sqlite_engine@@ -2207,11 +2198,16 @@ def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):session_id = session["id"]started = asyncio.Event()+ seen: list[str] = []async def long_handler(ctx, text):_bind_test_native_start(engine, ctx)- started.set()- await asyncio.sleep(5) # held until the test cancels it+ seen.append(text)+ if text == "first":+ started.set()+ await asyncio.sleep(5) # held until the test cancels it+ else:+ controller.mark_turn_complete(ctx)return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)controller = _build_controller_double(handler=long_handler)@@ -2233,8 +2229,8 @@ def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):with engine.begin() as conn:message_deliveries.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")await client.post(f"/internal/cancel/{session_id}")- for _ in range(200):- if session_id not in app.state.in_flight_dispatches:+ for _ in range(300):+ if seen == ["first", "q1"] and session_id not in app.state.in_flight_dispatches:breakawait asyncio.sleep(0.02)@@ -2242,8 +2238,9 @@ def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):with engine.connect() as conn:queued = message_deliveries.list_queued(conn, session_id)transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))- assert [q["text"] for q in queued] == ["q1"], "Stop must keep the queue intact"- assert [row["text"] for row in transcript["messages"]] == ["first"]+ assert seen == ["first", "q1"]+ assert queued == []+ assert [row["text"] for row in transcript["messages"]] == ["first", "q1"]def test_turn_state_reflects_in_flight():@@ -2876,7 +2873,6 @@ def test_stop_during_backend_drain_keeps_existing_queue_parked(tmp_path, monkeypassert result["status"] == "cancel_requested"assert held is Truewith engine.connect() as conn:- assert message_deliveries.queue_is_held(conn, session_id) is Trueassert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == ["queued"]assert manager._deferred_restart_sessions == {"codex": {session_id}}@@ -3454,7 +3450,6 @@ def test_concurrent_agent_run_send_now_callers_share_one_interrupt_and_drain_fifassert seen == ["original work", "first correction", "second correction"]with engine.connect() as conn:assert message_deliveries.list_queued(conn, session_id) == []- assert message_deliveries.queue_is_held(conn, session_id) is Falsefor request, expected_status in zip(requests,("waiting_terminal", "queued"),@@ -3612,7 +3607,6 @@ def test_agent_run_send_now_on_an_idle_backlog_does_not_stop_the_head(monkeypatcsession_id=session_id,text="older queued input",)- assert message_deliveries.set_queue_hold(conn, session_id, held=True)request_store = TaskExecutionStore()request = request_store.enqueue_agent_run(@@ -3669,7 +3663,6 @@ def test_agent_run_send_now_on_an_idle_backlog_does_not_stop_the_head(monkeypatcassert [row["text"] for row in message_deliveries.list_queued(conn, session_id)] == ["older queued input"]- assert message_deliveries.queue_is_held(conn, session_id)controller.command_handler.handle_stop.assert_not_awaited()@@ -3909,7 +3902,6 @@ def test_idle_send_now_releases_hold_and_starts_the_exact_head(session_id=session_id,text="retry me later",)- assert message_deliveries.set_queue_hold(conn, session_id, held=True)controller = _build_controller_double()app = internal_server.create_app(controller)@@ -3946,7 +3938,6 @@ def test_idle_send_now_releases_hold_and_starts_the_exact_head(}with engine.connect() as conn:assert message_deliveries.list_queued(conn, session_id) == []- assert not message_deliveries.queue_is_held(conn, session_id)assert messages_service.get_message(conn, queued["id"], session_id=session_id)diff --git a/tests/test_message_delivery_authority.py b/tests/test_message_delivery_authority.pyindex 60c1b9a17..320f7a41a 100644--- a/tests/test_message_delivery_authority.py+++ b/tests/test_message_delivery_authority.py@@ -43,9 +43,6 @@ def _seed_session(conn, session_id: str = "ses_authority") -> None:visibility="foreground",pinned=0,agent_status="idle",- queue_hold_state="open",- queue_hold_version=1,- queue_held_at=None,composer_draft_text=None,composer_draft_updated_at=None,metadata_json="{}",diff --git a/tests/test_runtime_ownership.py b/tests/test_runtime_ownership.pyindex 752e6a51e..243bd1a09 100644--- a/tests/test_runtime_ownership.py+++ b/tests/test_runtime_ownership.py@@ -56,7 +56,6 @@ def _session(anchor: str,workdir: str,backend: str = "codex",- hold: str = "open",) -> None:conn.execute(agent_sessions.insert().values(@@ -76,9 +75,6 @@ def _session(visibility="foreground",pinned=0,agent_status="idle",- queue_hold_state=hold,- queue_hold_version=1,- queue_held_at=NOW if hold == "held" else None,metadata_json="{}",created_at=NOW,updated_at=NOW,@@ -128,41 +124,34 @@ async def test_hfr_131_open_head_wakes_survives_reclaim_and_claims_exact_head(@pytest.mark.anyio-async def test_hfr_132_held_head_survives_reclaim_then_explicit_release_starts(+async def test_hfr_132_queued_head_wakes_without_an_explicit_release(tmp_path: Path,) -> None:- """HFR-132: a durable hold permits reclamation until explicit release."""+ """HFR-132: runnable backlog needs no Session policy transition."""engine = _engine(tmp_path, "hfr-132.sqlite")with engine.begin() as conn:- _session(- conn,- "ses-held",- anchor="base-held",- workdir="/work",- hold="held",- )- _delivery(conn, "delivery-held", "ses-held")+ _session(conn, "ses-queued", anchor="base-queued", workdir="/work")+ _delivery(conn, "delivery-queued", "ses-queued")agent, _manager, stopped, wakes = _codex_reclaimer(engine,- [("ses-held", "base-held", "/work", "route:held")],+ [("ses-queued", "base-queued", "/work", "route:queued")],)with pytest.MonkeyPatch.context() as monkeypatch:monkeypatch.setattr("modules.agents.codex.agent.time.monotonic", lambda: 1000.0)assert await agent.evict_idle_transports(600) == 1assert stopped == ["stop"]- assert wakes == []- with engine.begin() as conn:- durable = delivery_store.get_delivery(conn, "delivery-held")- assert durable is not None and durable["state"] == "queued"- assert delivery_store.set_queue_hold(conn, "ses-held", held=False)+ assert any(RuntimeWorkLane.SESSION_DELIVERIES in lanes for lanes in wakes)+ with engine.connect() as conn:+ durable = delivery_store.get_delivery(conn, "delivery-queued")+ assert durable is not None and durable["state"] == "queued"turn_manager = SessionTurnManager(SimpleNamespace())turn_manager._engine = engineturn_manager._start_persisted_turn = AsyncMock(return_value=True)assert await turn_manager.drain_delivery_queue(- "ses-held",- expected_head_id="delivery-held",+ "ses-queued",+ expected_head_id="delivery-queued",expected_head_version=int(durable["version"]),)engine.dispose()@@ -258,27 +247,21 @@ async def test_hfr_146_shared_codex_target_and_claude_mapping_use_exact_bindingsdispatch_text="delivery-active",attempt_id="attempt-active",)- _session(- conn,- "ses-held",- anchor="base-held",- workdir="/work",- hold="held",- )- _delivery(conn, "delivery-held", "ses-held")+ _session(conn, "ses-queued", anchor="base-queued", workdir="/work")+ _delivery(conn, "delivery-queued", "ses-queued")agent, manager, stopped, _wakes = _codex_reclaimer(engine,[("ses-active", "base-active", "/work", "route:active"),- ("ses-held", "base-held", "/work", "route:held"),+ ("ses-queued", "base-queued", "/work", "route:queued"),],)with pytest.MonkeyPatch.context() as monkeypatch:monkeypatch.setattr("modules.agents.codex.agent.time.monotonic", lambda: 1000.0)assert await agent.evict_idle_transports(600) == 0assert stopped == []- assert "base-held" not in agent._session_last_activity+ assert "base-queued" not in agent._session_last_activityclaude_client = SimpleNamespace(_vibe_agent_session_id="ses-active",@@ -675,7 +658,6 @@ def test_snapshot_many_reads_backend_owner_tables_once(tmp_path: Path) -> None:turn_ids=("turn-a",),active_activity_ids=(),fallback_run_ids=(),- queue_hold_state="open",reasons=("delivery:claimed", "turn:starting"),),),@@ -698,7 +680,6 @@ def test_snapshot_many_reads_backend_owner_tables_once(tmp_path: Path) -> None:turn_ids=("turn-a",),active_activity_ids=(),fallback_run_ids=(),- queue_hold_state="open",reasons=("delivery:claimed", "turn:active"),),),diff --git a/tests/test_runtime_recovery.py b/tests/test_runtime_recovery.pyindex 35d30fda0..a2ec8a105 100644--- a/tests/test_runtime_recovery.py+++ b/tests/test_runtime_recovery.py@@ -50,9 +50,6 @@ def _session(conn, session_id: str) -> None:visibility="foreground",pinned=0,agent_status="idle",- queue_hold_state="open",- queue_hold_version=1,- queue_held_at=None,metadata_json="{}",created_at=NOW,updated_at=NOW,diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex b55f74f3c..7ea88a646 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -3003,7 +3003,7 @@ def test_task_definition_projection_follows_the_exact_terminal_cas_winner(@pytest.mark.parametrize("shutdown_entrypoint", ["stop", "lease_loss"])@pytest.mark.parametrize("user_stopped", [False, True])-def test_service_teardown_terminalizes_transferred_durable_turn_without_draining_held_queue(+def test_service_teardown_terminalizes_transferred_turn_without_starting_queued_work(tmp_path: Path,monkeypatch,shutdown_entrypoint: str,@@ -3092,7 +3092,6 @@ def test_service_teardown_terminalizes_transferred_durable_turn_without_drainingturn_id=turn_id,evidence={"kind": "native_acceptance"},)- message_deliveries.set_queue_hold(conn, session_id, held=True)queued = message_deliveries.enqueue_queued(conn,scope_id=session["scope_id"],@@ -3100,7 +3099,7 @@ def test_service_teardown_terminalizes_transferred_durable_turn_without_drainingauthor="user",source="user",message_type="user",- text="keep me held",+ text="keep me queued",native_message_id="held-after-shutdown",)successor_delivery_id = None@@ -3271,7 +3270,6 @@ def test_service_teardown_terminalizes_transferred_durable_turn_without_drainingif successor_delivery_idelse None)- assert message_deliveries.queue_is_held(conn, session_id) is Trueassert terminal_turn is not Noneassert terminal_turn["state"] == "terminal"assert terminal_turn["terminal_outcome"] == expected_statusdiff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 9dc4239a6..fc4fcb647 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -1387,11 +1387,11 @@ def test_older_reserved_submission_fences_later_queue_drain(managers) -> None:assert _row(engine, "msg_queued_second")["state"] == "queued"-def test_hold_bypass_still_respects_an_unresolved_reservation_fence(managers) -> None:+def test_idle_admission_still_respects_an_unresolved_reservation_fence(managers) -> None:manager, _other, engine, _engine_b, starts = managerswith engine.begin() as conn:for delivery_id, state, submitted_at in (- ("msg_held_backlog", "queued", "2026-08-01T00:00:01Z"),+ ("msg_older_backlog", "queued", "2026-08-01T00:00:01Z"),("msg_reserved_fence", "reserved", "2026-08-01T00:00:02Z"),):delivery_store.insert_delivery(@@ -1412,23 +1412,23 @@ def test_hold_bypass_still_respects_an_unresolved_reservation_fence(managers) ->dispatch_text=delivery_id,now=submitted_at,)- assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)-admitted = asyncio.run(manager.deliver(DeliveryRequest(session_id="ses_fsm",priority="p3",- content="new held admission",+ content="new idle admission",),context=_context(),))assert admitted.state == "queued"- assert starts == []+ assert [text for _turn, text in starts] == ["msg_older_backlog"]with engine.connect() as conn:- assert delivery_store.active_turn(conn, "ses_fsm") is None+ active = delivery_store.active_turn(conn, "ses_fsm")+ assert active is not None+ assert active["initial_delivery_id"] == "msg_older_backlog"assert _row(engine, "msg_reserved_fence")["state"] == "reserved"@@ -1987,7 +1987,7 @@ def test_definitive_refusal_racing_idle_drain_starts_same_delivery_once(managersassert matching_starts[0][0] == row["turn_id"]-def test_definitive_p1_refusal_requeues_behind_existing_fifo_head(managers) -> None:+def test_definitive_p1_refusal_stays_behind_the_started_fifo_head(managers) -> None:manager, _other, engine, _engine_b, starts = managersturn_id, _ = asyncio.run(_activate(manager))older = asyncio.run(@@ -1996,8 +1996,6 @@ def test_definitive_p1_refusal_requeues_behind_existing_fifo_head(managers) -> Ncontext=_context(),))- with engine.begin() as conn:- assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)entered = threading.Event()release = threading.Event()@@ -2017,8 +2015,6 @@ def test_definitive_p1_refusal_requeues_behind_existing_fifo_head(managers) -> N)assert await asyncio.to_thread(entered.wait, 5)assert await manager.terminalize_turn(turn_id)- with engine.begin() as conn:- assert delivery_store.set_queue_hold(conn, "ses_fsm", held=False)release.set()return await pending@@ -2026,9 +2022,8 @@ def test_definitive_p1_refusal_requeues_behind_existing_fifo_head(managers) -> Nolder_row = _row(engine, str(older.delivery_id))fallback_row = _row(engine, str(fallback.delivery_id))assert older_row["state"] == "claimed"- assert fallback_row["state"] == "claimed"- assert fallback_row["turn_id"] == older_row["turn_id"]- assert [text for _turn, text in starts].count("older backlog\nfallback") == 1+ assert fallback_row["state"] == "queued"+ assert [text for _turn, text in starts].count("older backlog") == 1def test_p0_successor_persistence_failure_never_calls_stop(managers, monkeypatch) -> None:@@ -2067,13 +2062,15 @@ def test_p0_successor_persistence_failure_never_calls_stop(managers, monkeypatchassert all(row["dispatch_text"] != "replacement" for row in _rows(engine))-def test_definitive_p0_refusal_restores_preexisting_queue_hold(managers) -> None:+def test_definitive_p0_refusal_leaves_backlog_behind_the_active_turn(managers) -> None:manager, _other, engine, _engine_b, _starts = managersasync def run() -> None:turn_id, context = await _activate(manager)- with engine.begin() as conn:- assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)+ queued = await manager.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="backlog"),+ context=_context(),+ )holder = asyncio.create_task(asyncio.Event().wait())manager.in_flight["ses_fsm"] = Turn(task=holder,@@ -2095,13 +2092,16 @@ def test_definitive_p0_refusal_restores_preexisting_queue_hold(managers) -> Noneholder.cancel()await asyncio.gather(holder, return_exceptions=True)assert result.state == "refused"+ return str(queued.delivery_id), turn_id- asyncio.run(run())+ queued_id, turn_id = asyncio.run(run())with engine.connect() as conn:- assert delivery_store.queue_is_held(conn, "ses_fsm") is True+ active = delivery_store.active_turn(conn, "ses_fsm")+ assert active is not None and active["id"] == turn_id+ assert _row(engine, queued_id)["state"] == "queued"-def test_empty_p0_establishes_durable_hold_before_stop(managers) -> None:+def test_empty_p0_uses_the_control_slot_without_creating_a_message_delivery(managers) -> None:manager, _other, engine, _engine_b, _starts = managersasync def run() -> None:@@ -2112,6 +2112,7 @@ def test_empty_p0_establishes_durable_hold_before_stop(managers) -> None:context=context,logical_turn_id=turn_id,)+ before = {row["id"] for row in _rows(engine)}try:result = await manager.deliver(DeliveryRequest(session_id="ses_fsm", priority="p0", content=None),@@ -2119,7 +2120,10 @@ def test_empty_p0_establishes_durable_hold_before_stop(managers) -> None:)assert result.state == "waiting_terminal"with engine.connect() as conn:- assert delivery_store.queue_is_held(conn, "ses_fsm") is True+ controlled = delivery_store.get_turn(conn, turn_id)+ assert controlled is not None+ assert controlled["control_mode"] == "stop_only"+ assert {row["id"] for row in _rows(engine)} == beforefinally:holder.cancel()await asyncio.gather(holder, return_exceptions=True)@@ -2127,7 +2131,7 @@ def test_empty_p0_establishes_durable_hold_before_stop(managers) -> None:asyncio.run(run())-def test_empty_p0_preserves_hold_when_observed_turn_terminalizes_before_claim(+def test_empty_p0_terminal_race_still_resumes_the_queued_head(managers,monkeypatch,) -> None:@@ -2157,11 +2161,9 @@ def test_empty_p0_preserves_hold_when_observed_turn_terminalizes_before_claim(assert result["ok"] is Trueassert result["status"] == "stale_released"- with engine.connect() as conn:- assert delivery_store.queue_is_held(conn, "ses_fsm") is Trueasyncio.run(manager._resume_post_terminal("ses_fsm"))- assert _row(engine, str(queued.delivery_id))["state"] == "queued"- assert [text for _turn, text in starts].count("backlog") == 0+ assert _row(engine, str(queued.delivery_id))["state"] == "claimed"+ assert [text for _turn, text in starts].count("backlog") == 1def test_content_p0_preserves_open_hold_and_claims_successor_once(managers) -> None:@@ -2199,8 +2201,6 @@ def test_content_p0_preserves_open_hold_and_claims_successor_once(managers) -> Nassert manager.controller.command_handler.handle_stop.await_count == 1delivery = _row(engine, delivery_id)assert delivery["state"] == "claimed"- with engine.connect() as conn:- assert delivery_store.queue_is_held(conn, "ses_fsm") is Falsedef test_stopped_runner_starts_successor_already_activated_by_terminal_result(@@ -2589,7 +2589,6 @@ def test_empty_p0_supersedes_in_flight_content_replacement(managers) -> None:agent_runs.c.id == run_id)).one()- assert delivery_store.queue_is_held(conn, "ses_fsm") is Trueassert target is not None and target["control_mode"] == "stop_only"assert target["control_successor_turn_id"] is Noneassert target["control_successor_delivery_id"] is None@@ -2981,11 +2980,11 @@ async def test_permanent_start_rejection_retires_delivery_without_retry(managersassert delivery["state"] == "retired"history = json.loads(delivery["delivery_history_json"])["events"]assert history[-1]["outcome"] == "invalid_input"- assert _row(engine, str(following.delivery_id))["state"] == "queued"+ assert _row(engine, str(following.delivery_id))["state"] == "claimed"assert len(starts) == 1with engine.connect() as conn:terminal = delivery_store.get_turn(conn, str(admitted.turn_id))- assert delivery_store.claimable_fifo_head(conn, "ses_fsm") is not None+ assert delivery_store.claimable_fifo_head(conn, "ses_fsm") is Noneassert terminal is not Noneassert terminal["terminal_outcome"] == "not_written"@@ -3430,7 +3429,7 @@ def test_forced_backend_refresh_fails_unresolved_start_instead_of_blocking(assert status == "failed"-def test_backend_refresh_preserves_successor_activated_by_old_turn_cancellation(+def test_backend_refresh_defers_successor_activated_by_old_turn_cancellation(managers,monkeypatch,) -> None:@@ -3501,8 +3500,8 @@ def test_backend_refresh_preserves_successor_activated_by_old_turn_cancellation(successor = delivery_store.get_turn(conn, successor_turn_id)replacement = delivery_store.get_delivery(conn, replacement_delivery_id)assert old_turn is not None and old_turn["state"] == "terminal"- assert successor is not None and successor["state"] == "starting"- assert replacement is not None and replacement["state"] == "claimed"+ assert successor is not None and successor["state"] == "terminal"+ assert replacement is not None and replacement["state"] == "queued"assert manager._deferred_restart_sessions == {"codex": {"ses_fsm"}}@@ -4137,13 +4136,11 @@ def test_send_now_retires_head_whose_agent_run_can_no_longer_start(_insert_queued_delivery_with_run(engine,delivery_id=poisoned_id,- text="held head whose run failed",+ text="head whose run failed",now="2026-08-01T00:00:01Z",- run_id="run_settled_behind_hold",+ run_id="run_settled_at_head",run_status="failed",)- with engine.begin() as conn:- assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)promoted = asyncio.run(manager.deliver(@@ -4161,8 +4158,6 @@ def test_send_now_retires_head_whose_agent_run_can_no_longer_start(assert promoted.reason == "stale_head"assert _row(engine, poisoned_id)["state"] == "retired"assert starts == []- with engine.connect() as conn:- assert delivery_store.queue_is_held(conn, "ses_fsm")def test_p3_admission_retires_poisoned_backlog_and_still_starts(@@ -4470,15 +4465,15 @@ def test_unresolved_p1_fence_blocks_later_but_not_older_fifo(managers) -> None:assert [text for _, text in starts].count("later") == 0-def test_held_old_backlog_does_not_block_new_idle_p3(managers) -> None:- """MESSAGE-DELIVERY-102: hold blocks autonomous backlog only."""+def test_stop_terminalization_resumes_oldest_queued_segment(managers) -> None:+ """MESSAGE-DELIVERY-102: an idle Session cannot retain claimable backlog."""manager, other, engine, _engine_b, starts = managersasync def run() -> None:turn_id, context = await _activate(manager)await manager.deliver(- DeliveryRequest(session_id="ses_fsm", priority="p3", content="held-old"),+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="queued-after-stop"),context=_context(),)holder = asyncio.create_task(asyncio.Event().wait())@@ -4495,18 +4490,12 @@ def test_held_old_backlog_does_not_block_new_idle_p3(managers) -> None:assert await other.terminalize_turn(turn_id)holder.cancel()await asyncio.gather(holder, return_exceptions=True)- admitted = await other.deliver(- DeliveryRequest(session_id="ses_fsm", priority="p3", content="new-idle"),- context=_context(),- )- assert admitted.state == "claimed"asyncio.run(run())rows = _rows(engine)- assert next(row for row in rows if row["dispatch_text"] == "held-old")["state"] == "queued"- assert [text for _, text in starts].count("new-idle") == 1- with engine.connect() as conn:- assert delivery_store.queue_is_held(conn, "ses_fsm") is True+ queued = next(row for row in rows if row["dispatch_text"] == "queued-after-stop")+ assert queued["state"] == "claimed"+ assert [text for _, text in starts].count("queued-after-stop") == 1def test_open_backlog_starts_oldest_before_new_idle_p3(managers) -> None:@@ -5083,9 +5072,14 @@ def test_repeated_refusal_then_acceptance_preserves_attempt_history(managers) ->))assert _row(engine, str(first_attempt.delivery_id))["state"] == "queued"- with engine.begin() as conn:- delivery_store.set_queue_hold(conn, "ses_fsm", held=True)- assert asyncio.run(other.terminalize_turn(t1))+ terminal = other._terminalize_durable_turn(+ t1,+ "completed",+ settled_by="service_shutdown",+ evidence_kind="test_deferred_resume",+ resume_successors=False,+ )+ assert terminal["changed"] is Truet2, context2 = asyncio.run(_activate(other, text="new priority work", priority="p1"))@@ -5108,21 +5102,26 @@ def test_repeated_refusal_then_acceptance_preserves_attempt_history(managers) ->assert row["current_attempt_id"] is None-def test_stale_send_now_does_not_release_the_queue_hold(managers) -> None:+def test_stale_send_now_does_not_mutate_the_deferred_queue(managers) -> None:manager, _other, engine, _engine_b, _starts = managersold_turn_id, _ = asyncio.run(_activate(manager, text="old turn"))queued = asyncio.run(manager.deliver(- DeliveryRequest(session_id="ses_fsm", priority="p3", content="held backlog"),+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="deferred backlog"),context=_context(),))with engine.connect() as conn:old_turn = delivery_store.get_turn(conn, old_turn_id)assert old_turn is not None- with engine.begin() as conn:- assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)- assert asyncio.run(manager.terminalize_turn(old_turn_id))+ terminal = manager._terminalize_durable_turn(+ old_turn_id,+ "completed",+ settled_by="service_shutdown",+ evidence_kind="test_deferred_resume",+ resume_successors=False,+ )+ assert terminal["changed"] is Truereplacement_turn_id, replacement_context = asyncio.run(_activate(manager, text="replacement turn", priority="p1"))@@ -5146,7 +5145,6 @@ def test_stale_send_now_does_not_release_the_queue_hold(managers) -> None:assert result.state == "refused"assert result.reason == "stale_turn"with engine.connect() as conn:- assert delivery_store.queue_is_held(conn, "ses_fsm")current = delivery_store.active_turn(conn, "ses_fsm")assert current is not None and current["id"] == replacement_turn_idassert _row(engine, str(queued.delivery_id))["state"] == "queued"@@ -5184,8 +5182,6 @@ def test_send_now_keeps_attachment_head_for_the_next_turn(context=_context(),))- with engine.begin() as conn:- assert delivery_store.set_queue_hold(conn, "ses_fsm", held=True)manager._steer = AsyncMock(return_value=steer_result(SteerOutcome.ACCEPTED))promoted = asyncio.run(@@ -5204,8 +5200,6 @@ def test_send_now_keeps_attachment_head_for_the_next_turn(assert promoted.reason == "attachments_wait_for_new_turn"manager._steer.assert_not_awaited()assert _row(engine, str(queued.delivery_id))["state"] == "queued"- with engine.connect() as conn:- assert not delivery_store.queue_is_held(conn, "ses_fsm")def test_content_p1_with_attachment_queues_behind_an_active_turn(diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex ed19a939b..03c440cfa 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -28,7 +28,7 @@ from storage.settings_service import SQLiteSettingsService, upsert_scopefrom vibe.message_types import build_partial_index_predicate-HEAD_REVISION = "20260804_0046"+HEAD_REVISION = "20260806_0047"MESSAGE_PARTIAL_INDEX_PREDICATES = {"ix_messages_inbox_activity": ("session_id is not null and type in "@@ -158,6 +158,45 @@ def test_message_transcript_order_upgrade_normalizes_and_indexes_exact_time()+def test_session_queue_hold_removal_is_schema_complete_and_reversible(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260804_0046")+ with sqlite3.connect(db_path) as conn:+ _insert_scope(conn, "scope_queue_hold")+ _insert_agent_session(+ conn,+ row_id="ses_queue_hold",+ scope_id="scope_queue_hold",+ anchor="queue-hold",+ workdir=None,+ backend="codex",+ native="native-queue-hold",+ last_active="now",+ )+ conn.execute(+ "update agent_sessions set queue_hold_state='held', "+ "queue_hold_version=7, queue_held_at='now' where id='ses_queue_hold'"+ )+ conn.commit()++ run_migrations(db_path)+ with sqlite3.connect(db_path) as conn:+ columns = {row[1] for row in conn.execute("pragma table_info(agent_sessions)")}+ version = conn.execute("select version_num from alembic_version").fetchone()+ assert not {"queue_hold_state", "queue_hold_version", "queue_held_at"} & columns+ assert version == (HEAD_REVISION,)++ command.downgrade(migrations.alembic_config(db_path), "20260804_0046")+ with sqlite3.connect(db_path) as conn:+ restored = conn.execute(+ "select queue_hold_state, queue_hold_version, queue_held_at "+ "from agent_sessions where id='ses_queue_hold'"+ ).fetchone()+ assert restored == ("open", 1, None)++def test_scoped_native_message_identity_upgrade_and_safe_downgrade(tmp_path: Path,) -> None:@@ -442,9 +481,9 @@ def test_session_delivery_fsm_upgrade_and_downgrade_preserve_existing_rows("select state, dedupe_key, snapshot_json from message_deliveries ""where id = 'msg_fsm_agent_run'").fetchone()- hold_state = conn.execute(- "select queue_hold_state from agent_sessions where id = 'ses_fsm'"- ).fetchone()+ session_columns = {+ row[1] for row in conn.execute("pragma table_info(agent_sessions)")+ }draft_state = conn.execute("select composer_draft_text, composer_draft_updated_at ""from agent_sessions where id = 'ses_fsm'"@@ -481,7 +520,7 @@ def test_session_delivery_fsm_upgrade_and_downgrade_preserve_existing_rows(assert json.loads(migrated_dedupe[2])["type"] == "harness"assert migrated_agent_run[0:2] == ("queued", "avibe:agent_run:run-legacy")assert json.loads(migrated_agent_run[2])["type"] == "harness"- assert hold_state == ("held",)+ assert not {"queue_hold_state", "queue_hold_version", "queue_held_at"} & session_columnsassert draft_state == ("unfinished thought", now)assert message_session_fk[6] == "NO ACTION"assert version == (HEAD_REVISION,)@@ -491,11 +530,9 @@ def test_session_delivery_fsm_upgrade_and_downgrade_preserve_existing_rows(engine = create_sqlite_engine(db_path)try:with engine.connect() as conn:- assert message_deliveries.queued_session_ids_without_live_turns(conn) == []- assert message_deliveries.queued_session_ids_without_live_turns(- conn,- include_held=True,- ) == ["ses_fsm"]+ assert message_deliveries.queued_session_ids_without_live_turns(conn) == [+ "ses_fsm"+ ]finally:engine.dispose()@@ -738,8 +775,7 @@ def test_session_delivery_migration_binds_each_live_scheduled_run(with sqlite3.connect(db_path) as conn:migrated = conn.execute("""- select r.id, r.delivery_id, d.state, d.dedupe_key,- s.queue_hold_state+ select r.id, r.delivery_id, d.state, d.dedupe_keyfrom agent_runs rjoin message_deliveries d on d.id = r.delivery_idjoin agent_sessions s on s.id = r.session_id@@ -753,7 +789,6 @@ def test_session_delivery_migration_binds_each_live_scheduled_run(f"msg_{name}_migration","queued",f"avibe:{name}:migration",- "open",)for name, _trigger_kind, _run_status in sorted(cases)]diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 7d8ffb382..aa7e83468 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -2278,8 +2278,8 @@ export const ChatPage: React.FC = () => {};// Pending send-while-busy messages, shown between the transcript and the-// composer (Codex-GUI style). Each can be dropped; "立即发送" interrupts the-// running turn and flushes the whole queue now (the queue flushes merged).+// composer. Queued work is visually grouped, but each Delivery stays+// independently removable and compatible rows merge only at claim time.// One queued message. Its text is a single truncated line by default; clicking// it expands to the full wrapped text (and clicking again collapses it) so a// long queued prompt can be read without sending it.@@ -2321,7 +2321,10 @@ export const QueueRow: React.FC<{// has none, and would sit here as a title, a separator, and empty space.const standIn = annotationView && annotationStandIn(annotationView, item.text, hasAttachments);return (- <div className="flex items-start gap-2 rounded-lg bg-surface-2 px-2.5 py-1.5">+ <div+ data-queue-row="true"+ className="relative flex items-start gap-2 px-2.5 py-1.5 transition-[background-color,box-shadow,border-radius] hover:z-10 hover:rounded-lg hover:bg-surface-1 hover:ring-1 hover:ring-border focus-within:z-10 focus-within:rounded-lg focus-within:bg-surface-1 focus-within:ring-1 focus-within:ring-border motion-reduce:transition-none"+ ><divrole="button"tabIndex={0}@@ -2595,7 +2598,7 @@ const ActivityStrip: React.FC<{);};-const QueueStrip: React.FC<{+export const QueueStrip: React.FC<{queue: WorkbenchMessage[];onRemove: (id: string) => void;onRecall: (item: WorkbenchMessage) => void;@@ -2615,7 +2618,10 @@ const QueueStrip: React.FC<{{t('chat.queue.sendNow')}</Button></div>- <div className="flex max-h-32 flex-col gap-1 overflow-y-auto">+ <div+ data-queue-batch="true"+ className="flex max-h-32 flex-col overflow-y-auto rounded-lg bg-surface-2"+ >{queue.map((item) => (<QueueRow key={item.id} item={item} onRemove={onRemove} onRecall={onRecall} />))}diff --git a/ui/src/components/workbench/ChatQueueRow.test.tsx b/ui/src/components/workbench/ChatQueueRow.test.tsxindex bbebdcd80..ee2f9df7b 100644--- a/ui/src/components/workbench/ChatQueueRow.test.tsx+++ b/ui/src/components/workbench/ChatQueueRow.test.tsx@@ -6,7 +6,7 @@ import { describe, expect, it } from 'vitest';import en from '../../i18n/en.json';import type { WorkbenchMessage } from '../../context/ApiContext';import { AnnotationMessage } from './AnnotationMessage';-import { QueueRow } from './ChatPage';+import { QueueRow, QueueStrip } from './ChatPage';const i18n = createInstance();void i18n.use(initReactI18next).init({@@ -39,6 +39,25 @@ const queued = (over: Partial<WorkbenchMessage> = {}): WorkbenchMessage =>const renderQueued = (item: WorkbenchMessage) =>wrap(<QueueRow item={item} onRemove={() => undefined} onRecall={() => undefined} />);+describe('QueueStrip — compatible queued messages read as one batch', () => {+ it('uses one shared bubble and reveals each original row boundary on hover or focus', () => {+ const html = wrap(+ <QueueStrip+ queue={[queued({ id: 'msg_1', text: 'One' }), queued({ id: 'msg_2', text: 'Two' })]}+ onRemove={() => undefined}+ onRecall={() => undefined}+ onSendNow={() => undefined}+ />,+ );++ expect(html.match(/data-queue-batch="true"/g)).toHaveLength(1);+ expect(html.match(/data-queue-row="true"/g)).toHaveLength(2);+ expect(html).toContain('hover:rounded-lg');+ expect(html).toContain('focus-within:rounded-lg');+ expect(html).not.toContain('flex-col gap-1');+ });+});+describe('QueueRow — a queued annotation in the strip (rule 08)', () => {it('names a queued annotation, and leaves an ordinary queued prompt unlabelled', () => {expect(renderQueued(queued())).toContain('User annotation');